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. */
68 atomic_type_kind_t akind;
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
102 * Capture a MS __base extension.
104 typedef struct based_spec_t {
105 source_position_t source_position;
106 variable_t *base_variable;
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
111 /** The current token. */
112 static token_t token;
113 /** The lookahead ring-buffer. */
114 static token_t lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static int lookahead_bufpos;
117 static stack_entry_t *environment_stack = NULL;
118 static stack_entry_t *label_stack = NULL;
119 static scope_t *file_scope = NULL;
120 static scope_t *current_scope = NULL;
121 /** Point to the current function declaration if inside a function. */
122 static function_t *current_function = NULL;
123 static entity_t *current_init_decl = NULL;
124 static switch_statement_t *current_switch = NULL;
125 static statement_t *current_loop = NULL;
126 static statement_t *current_parent = NULL;
127 static ms_try_statement_t *current_try = NULL;
128 static linkage_kind_t current_linkage = LINKAGE_INVALID;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t **goto_anchor = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t **label_anchor = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
140 static entity_t *anonymous_entity;
141 static declaration_t **incomplete_arrays;
144 #define PUSH_PARENT(stmt) \
145 statement_t *const prev_parent = current_parent; \
146 ((void)(current_parent = (stmt)))
147 #define POP_PARENT ((void)(current_parent = prev_parent))
149 /** special symbol used for anonymous entities. */
150 static const symbol_t *sym_anonymous = NULL;
152 /* symbols for Microsoft extended-decl-modifier */
153 static const symbol_t *sym_align = NULL;
154 static const symbol_t *sym_allocate = NULL;
155 static const symbol_t *sym_dllimport = NULL;
156 static const symbol_t *sym_dllexport = NULL;
157 static const symbol_t *sym_naked = NULL;
158 static const symbol_t *sym_noinline = NULL;
159 static const symbol_t *sym_returns_twice = NULL;
160 static const symbol_t *sym_noreturn = NULL;
161 static const symbol_t *sym_nothrow = NULL;
162 static const symbol_t *sym_novtable = NULL;
163 static const symbol_t *sym_property = NULL;
164 static const symbol_t *sym_get = NULL;
165 static const symbol_t *sym_put = NULL;
166 static const symbol_t *sym_selectany = NULL;
167 static const symbol_t *sym_thread = NULL;
168 static const symbol_t *sym_uuid = NULL;
169 static const symbol_t *sym_deprecated = NULL;
170 static const symbol_t *sym_restrict = NULL;
171 static const symbol_t *sym_noalias = NULL;
173 /** The token anchor set */
174 static unsigned char token_anchor_set[T_LAST_TOKEN];
176 /** The current source position. */
177 #define HERE (&token.source_position)
179 /** true if we are in GCC mode. */
180 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
182 static type_t *type_valist;
184 static statement_t *parse_compound_statement(bool inside_expression_statement);
185 static statement_t *parse_statement(void);
187 static expression_t *parse_sub_expression(precedence_t);
188 static expression_t *parse_expression(void);
189 static type_t *parse_typename(void);
190 static void parse_externals(void);
191 static void parse_external(void);
193 static void parse_compound_type_entries(compound_t *compound_declaration);
195 typedef enum declarator_flags_t {
197 DECL_MAY_BE_ABSTRACT = 1U << 0,
198 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
199 DECL_IS_PARAMETER = 1U << 2
200 } declarator_flags_t;
202 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
203 declarator_flags_t flags);
205 static entity_t *record_entity(entity_t *entity, bool is_definition);
207 static void semantic_comparison(binary_expression_t *expression);
209 #define STORAGE_CLASSES \
210 STORAGE_CLASSES_NO_EXTERN \
213 #define STORAGE_CLASSES_NO_EXTERN \
220 #define TYPE_QUALIFIERS \
225 case T__forceinline: \
226 case T___attribute__:
228 #define COMPLEX_SPECIFIERS \
230 #define IMAGINARY_SPECIFIERS \
233 #define TYPE_SPECIFIERS \
235 case T___builtin_va_list: \
255 #define DECLARATION_START \
260 #define DECLARATION_START_NO_EXTERN \
261 STORAGE_CLASSES_NO_EXTERN \
265 #define TYPENAME_START \
269 #define EXPRESSION_START \
278 case T_CHARACTER_CONSTANT: \
279 case T_FLOATINGPOINT: \
283 case T_STRING_LITERAL: \
284 case T_WIDE_CHARACTER_CONSTANT: \
285 case T_WIDE_STRING_LITERAL: \
286 case T___FUNCDNAME__: \
287 case T___FUNCSIG__: \
288 case T___FUNCTION__: \
289 case T___PRETTY_FUNCTION__: \
290 case T___alignof__: \
291 case T___builtin_alloca: \
292 case T___builtin_classify_type: \
293 case T___builtin_constant_p: \
294 case T___builtin_expect: \
295 case T___builtin_huge_val: \
296 case T___builtin_inf: \
297 case T___builtin_inff: \
298 case T___builtin_infl: \
299 case T___builtin_isgreater: \
300 case T___builtin_isgreaterequal: \
301 case T___builtin_isless: \
302 case T___builtin_islessequal: \
303 case T___builtin_islessgreater: \
304 case T___builtin_isunordered: \
305 case T___builtin_nan: \
306 case T___builtin_nanf: \
307 case T___builtin_nanl: \
308 case T___builtin_offsetof: \
309 case T___builtin_prefetch: \
310 case T___builtin_va_arg: \
311 case T___builtin_va_end: \
312 case T___builtin_va_start: \
323 * Allocate an AST node with given size and
324 * initialize all fields with zero.
326 static void *allocate_ast_zero(size_t size)
328 void *res = allocate_ast(size);
329 memset(res, 0, size);
334 * Returns the size of an entity node.
336 * @param kind the entity kind
338 static size_t get_entity_struct_size(entity_kind_t kind)
340 static const size_t sizes[] = {
341 [ENTITY_VARIABLE] = sizeof(variable_t),
342 [ENTITY_PARAMETER] = sizeof(parameter_t),
343 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
344 [ENTITY_FUNCTION] = sizeof(function_t),
345 [ENTITY_TYPEDEF] = sizeof(typedef_t),
346 [ENTITY_STRUCT] = sizeof(compound_t),
347 [ENTITY_UNION] = sizeof(compound_t),
348 [ENTITY_ENUM] = sizeof(enum_t),
349 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
350 [ENTITY_LABEL] = sizeof(label_t),
351 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
352 [ENTITY_NAMESPACE] = sizeof(namespace_t)
354 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
355 assert(sizes[kind] != 0);
360 * Allocate an entity of given kind and initialize all
363 static entity_t *allocate_entity_zero(entity_kind_t kind)
365 size_t size = get_entity_struct_size(kind);
366 entity_t *entity = allocate_ast_zero(size);
372 * Returns the size of a statement node.
374 * @param kind the statement kind
376 static size_t get_statement_struct_size(statement_kind_t kind)
378 static const size_t sizes[] = {
379 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
380 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
381 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
382 [STATEMENT_RETURN] = sizeof(return_statement_t),
383 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
384 [STATEMENT_IF] = sizeof(if_statement_t),
385 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
386 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
387 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
388 [STATEMENT_BREAK] = sizeof(statement_base_t),
389 [STATEMENT_GOTO] = sizeof(goto_statement_t),
390 [STATEMENT_LABEL] = sizeof(label_statement_t),
391 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
392 [STATEMENT_WHILE] = sizeof(while_statement_t),
393 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
394 [STATEMENT_FOR] = sizeof(for_statement_t),
395 [STATEMENT_ASM] = sizeof(asm_statement_t),
396 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
397 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
399 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
400 assert(sizes[kind] != 0);
405 * Returns the size of an expression node.
407 * @param kind the expression kind
409 static size_t get_expression_struct_size(expression_kind_t kind)
411 static const size_t sizes[] = {
412 [EXPR_INVALID] = sizeof(expression_base_t),
413 [EXPR_REFERENCE] = sizeof(reference_expression_t),
414 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
415 [EXPR_CONST] = sizeof(const_expression_t),
416 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
417 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
418 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
419 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
420 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
421 [EXPR_CALL] = sizeof(call_expression_t),
422 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
423 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
424 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
425 [EXPR_SELECT] = sizeof(select_expression_t),
426 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
427 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
428 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
429 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
430 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
431 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
432 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
433 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
434 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
435 [EXPR_VA_START] = sizeof(va_start_expression_t),
436 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
437 [EXPR_STATEMENT] = sizeof(statement_expression_t),
438 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
440 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
441 return sizes[EXPR_UNARY_FIRST];
443 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
444 return sizes[EXPR_BINARY_FIRST];
446 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
447 assert(sizes[kind] != 0);
452 * Allocate a statement node of given kind and initialize all
453 * fields with zero. Sets its source position to the position
454 * of the current token.
456 static statement_t *allocate_statement_zero(statement_kind_t kind)
458 size_t size = get_statement_struct_size(kind);
459 statement_t *res = allocate_ast_zero(size);
461 res->base.kind = kind;
462 res->base.parent = current_parent;
463 res->base.source_position = token.source_position;
468 * Allocate an expression node of given kind and initialize all
471 static expression_t *allocate_expression_zero(expression_kind_t kind)
473 size_t size = get_expression_struct_size(kind);
474 expression_t *res = allocate_ast_zero(size);
476 res->base.kind = kind;
477 res->base.type = type_error_type;
478 res->base.source_position = token.source_position;
483 * Creates a new invalid expression at the source position
484 * of the current token.
486 static expression_t *create_invalid_expression(void)
488 return allocate_expression_zero(EXPR_INVALID);
492 * Creates a new invalid statement.
494 static statement_t *create_invalid_statement(void)
496 return allocate_statement_zero(STATEMENT_INVALID);
500 * Allocate a new empty statement.
502 static statement_t *create_empty_statement(void)
504 return allocate_statement_zero(STATEMENT_EMPTY);
508 * Returns the size of a type node.
510 * @param kind the type kind
512 static size_t get_type_struct_size(type_kind_t kind)
514 static const size_t sizes[] = {
515 [TYPE_ATOMIC] = sizeof(atomic_type_t),
516 [TYPE_COMPLEX] = sizeof(complex_type_t),
517 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
518 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
519 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
520 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
521 [TYPE_ENUM] = sizeof(enum_type_t),
522 [TYPE_FUNCTION] = sizeof(function_type_t),
523 [TYPE_POINTER] = sizeof(pointer_type_t),
524 [TYPE_ARRAY] = sizeof(array_type_t),
525 [TYPE_BUILTIN] = sizeof(builtin_type_t),
526 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
527 [TYPE_TYPEOF] = sizeof(typeof_type_t),
529 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
530 assert(kind <= TYPE_TYPEOF);
531 assert(sizes[kind] != 0);
536 * Allocate a type node of given kind and initialize all
539 * @param kind type kind to allocate
541 static type_t *allocate_type_zero(type_kind_t kind)
543 size_t size = get_type_struct_size(kind);
544 type_t *res = obstack_alloc(type_obst, size);
545 memset(res, 0, size);
546 res->base.kind = kind;
552 * Returns the size of an initializer node.
554 * @param kind the initializer kind
556 static size_t get_initializer_size(initializer_kind_t kind)
558 static const size_t sizes[] = {
559 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
560 [INITIALIZER_STRING] = sizeof(initializer_string_t),
561 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
562 [INITIALIZER_LIST] = sizeof(initializer_list_t),
563 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
565 assert(kind < sizeof(sizes) / sizeof(*sizes));
566 assert(sizes[kind] != 0);
571 * Allocate an initializer node of given kind and initialize all
574 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
576 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
583 * 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 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
973 * and esp. footnote 108). However we can't fold constants (yet), so we
974 * can't decide whether unsigned int is possible, while int always works.
975 * (unsigned int would be preferable when possible... for stuff like
976 * struct { enum { ... } bla : 4; } ) */
977 if (type->kind == TYPE_ENUM)
978 return get_akind_rank(ATOMIC_TYPE_INT);
980 assert(type->kind == TYPE_ATOMIC);
981 return get_akind_rank(type->atomic.akind);
985 * Do integer promotion for a given type.
987 * @param type the type to promote
988 * @return the promoted type
990 static type_t *promote_integer(type_t *type)
992 if (type->kind == TYPE_BITFIELD)
993 type = type->bitfield.base_type;
995 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
1002 * Create a cast expression.
1004 * @param expression the expression to cast
1005 * @param dest_type the destination type
1007 static expression_t *create_cast_expression(expression_t *expression,
1010 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1012 cast->unary.value = expression;
1013 cast->base.type = dest_type;
1019 * Check if a given expression represents a null pointer constant.
1021 * @param expression the expression to check
1023 static bool is_null_pointer_constant(const expression_t *expression)
1025 /* skip void* cast */
1026 if (expression->kind == EXPR_UNARY_CAST ||
1027 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1028 type_t *const type = skip_typeref(expression->base.type);
1029 if (types_compatible(type, type_void_ptr))
1030 expression = expression->unary.value;
1033 type_t *const type = skip_typeref(expression->base.type);
1035 is_type_integer(type) &&
1036 is_constant_expression(expression) &&
1037 fold_constant(expression) == 0;
1041 * Create an implicit cast expression.
1043 * @param expression the expression to cast
1044 * @param dest_type the destination type
1046 static expression_t *create_implicit_cast(expression_t *expression,
1049 type_t *const source_type = expression->base.type;
1051 if (source_type == dest_type)
1054 return create_cast_expression(expression, dest_type);
1057 typedef enum assign_error_t {
1059 ASSIGN_ERROR_INCOMPATIBLE,
1060 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1061 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1062 ASSIGN_WARNING_POINTER_FROM_INT,
1063 ASSIGN_WARNING_INT_FROM_POINTER
1066 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1067 const expression_t *const right,
1068 const char *context,
1069 const source_position_t *source_position)
1071 type_t *const orig_type_right = right->base.type;
1072 type_t *const type_left = skip_typeref(orig_type_left);
1073 type_t *const type_right = skip_typeref(orig_type_right);
1076 case ASSIGN_SUCCESS:
1078 case ASSIGN_ERROR_INCOMPATIBLE:
1079 errorf(source_position,
1080 "destination type '%T' in %s is incompatible with type '%T'",
1081 orig_type_left, context, orig_type_right);
1084 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1085 if (warning.other) {
1086 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1087 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1089 /* the left type has all qualifiers from the right type */
1090 unsigned missing_qualifiers
1091 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1092 warningf(source_position,
1093 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1094 orig_type_left, context, orig_type_right, missing_qualifiers);
1099 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1100 if (warning.other) {
1101 warningf(source_position,
1102 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1103 orig_type_left, context, right, orig_type_right);
1107 case ASSIGN_WARNING_POINTER_FROM_INT:
1108 if (warning.other) {
1109 warningf(source_position,
1110 "%s makes pointer '%T' from integer '%T' without a cast",
1111 context, orig_type_left, orig_type_right);
1115 case ASSIGN_WARNING_INT_FROM_POINTER:
1116 if (warning.other) {
1117 warningf(source_position,
1118 "%s makes integer '%T' from pointer '%T' without a cast",
1119 context, orig_type_left, orig_type_right);
1124 panic("invalid error value");
1128 /** Implements the rules from § 6.5.16.1 */
1129 static assign_error_t semantic_assign(type_t *orig_type_left,
1130 const expression_t *const right)
1132 type_t *const orig_type_right = right->base.type;
1133 type_t *const type_left = skip_typeref(orig_type_left);
1134 type_t *const type_right = skip_typeref(orig_type_right);
1136 if (is_type_pointer(type_left)) {
1137 if (is_null_pointer_constant(right)) {
1138 return ASSIGN_SUCCESS;
1139 } else if (is_type_pointer(type_right)) {
1140 type_t *points_to_left
1141 = skip_typeref(type_left->pointer.points_to);
1142 type_t *points_to_right
1143 = skip_typeref(type_right->pointer.points_to);
1144 assign_error_t res = ASSIGN_SUCCESS;
1146 /* the left type has all qualifiers from the right type */
1147 unsigned missing_qualifiers
1148 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1149 if (missing_qualifiers != 0) {
1150 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1153 points_to_left = get_unqualified_type(points_to_left);
1154 points_to_right = get_unqualified_type(points_to_right);
1156 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1159 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1160 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1161 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1164 if (!types_compatible(points_to_left, points_to_right)) {
1165 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1169 } else if (is_type_integer(type_right)) {
1170 return ASSIGN_WARNING_POINTER_FROM_INT;
1172 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1173 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1174 && is_type_pointer(type_right))) {
1175 return ASSIGN_SUCCESS;
1176 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1177 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1178 type_t *const unqual_type_left = get_unqualified_type(type_left);
1179 type_t *const unqual_type_right = get_unqualified_type(type_right);
1180 if (types_compatible(unqual_type_left, unqual_type_right)) {
1181 return ASSIGN_SUCCESS;
1183 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1184 return ASSIGN_WARNING_INT_FROM_POINTER;
1187 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1188 return ASSIGN_SUCCESS;
1190 return ASSIGN_ERROR_INCOMPATIBLE;
1193 static expression_t *parse_constant_expression(void)
1195 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1197 if (!is_constant_expression(result)) {
1198 errorf(&result->base.source_position,
1199 "expression '%E' is not constant", result);
1205 static expression_t *parse_assignment_expression(void)
1207 return parse_sub_expression(PREC_ASSIGNMENT);
1210 static string_t parse_string_literals(void)
1212 assert(token.type == T_STRING_LITERAL);
1213 string_t result = token.v.string;
1217 while (token.type == T_STRING_LITERAL) {
1218 result = concat_strings(&result, &token.v.string);
1225 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1226 [GNU_AK_CONST] = "const",
1227 [GNU_AK_VOLATILE] = "volatile",
1228 [GNU_AK_CDECL] = "cdecl",
1229 [GNU_AK_STDCALL] = "stdcall",
1230 [GNU_AK_FASTCALL] = "fastcall",
1231 [GNU_AK_DEPRECATED] = "deprecated",
1232 [GNU_AK_NOINLINE] = "noinline",
1233 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1234 [GNU_AK_NORETURN] = "noreturn",
1235 [GNU_AK_NAKED] = "naked",
1236 [GNU_AK_PURE] = "pure",
1237 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1238 [GNU_AK_MALLOC] = "malloc",
1239 [GNU_AK_WEAK] = "weak",
1240 [GNU_AK_CONSTRUCTOR] = "constructor",
1241 [GNU_AK_DESTRUCTOR] = "destructor",
1242 [GNU_AK_NOTHROW] = "nothrow",
1243 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1244 [GNU_AK_COMMON] = "common",
1245 [GNU_AK_NOCOMMON] = "nocommon",
1246 [GNU_AK_PACKED] = "packed",
1247 [GNU_AK_SHARED] = "shared",
1248 [GNU_AK_NOTSHARED] = "notshared",
1249 [GNU_AK_USED] = "used",
1250 [GNU_AK_UNUSED] = "unused",
1251 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1252 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1253 [GNU_AK_LONGCALL] = "longcall",
1254 [GNU_AK_SHORTCALL] = "shortcall",
1255 [GNU_AK_LONG_CALL] = "long_call",
1256 [GNU_AK_SHORT_CALL] = "short_call",
1257 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1258 [GNU_AK_INTERRUPT] = "interrupt",
1259 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1260 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1261 [GNU_AK_NESTING] = "nesting",
1262 [GNU_AK_NEAR] = "near",
1263 [GNU_AK_FAR] = "far",
1264 [GNU_AK_SIGNAL] = "signal",
1265 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1266 [GNU_AK_TINY_DATA] = "tiny_data",
1267 [GNU_AK_SAVEALL] = "saveall",
1268 [GNU_AK_FLATTEN] = "flatten",
1269 [GNU_AK_SSEREGPARM] = "sseregparm",
1270 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1271 [GNU_AK_RETURN_TWICE] = "return_twice",
1272 [GNU_AK_MAY_ALIAS] = "may_alias",
1273 [GNU_AK_MS_STRUCT] = "ms_struct",
1274 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1275 [GNU_AK_DLLIMPORT] = "dllimport",
1276 [GNU_AK_DLLEXPORT] = "dllexport",
1277 [GNU_AK_ALIGNED] = "aligned",
1278 [GNU_AK_ALIAS] = "alias",
1279 [GNU_AK_SECTION] = "section",
1280 [GNU_AK_FORMAT] = "format",
1281 [GNU_AK_FORMAT_ARG] = "format_arg",
1282 [GNU_AK_WEAKREF] = "weakref",
1283 [GNU_AK_NONNULL] = "nonnull",
1284 [GNU_AK_TLS_MODEL] = "tls_model",
1285 [GNU_AK_VISIBILITY] = "visibility",
1286 [GNU_AK_REGPARM] = "regparm",
1287 [GNU_AK_MODE] = "mode",
1288 [GNU_AK_MODEL] = "model",
1289 [GNU_AK_TRAP_EXIT] = "trap_exit",
1290 [GNU_AK_SP_SWITCH] = "sp_switch",
1291 [GNU_AK_SENTINEL] = "sentinel"
1295 * compare two string, ignoring double underscores on the second.
1297 static int strcmp_underscore(const char *s1, const char *s2)
1299 if (s2[0] == '_' && s2[1] == '_') {
1300 size_t len2 = strlen(s2);
1301 size_t len1 = strlen(s1);
1302 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1303 return strncmp(s1, s2+2, len2-4);
1307 return strcmp(s1, s2);
1311 * Allocate a new gnu temporal attribute of given kind.
1313 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1315 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1316 attribute->kind = kind;
1317 attribute->next = NULL;
1318 attribute->invalid = false;
1319 attribute->has_arguments = false;
1325 * Parse one constant expression argument of the given attribute.
1327 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1329 expression_t *expression;
1330 add_anchor_token(')');
1331 expression = parse_constant_expression();
1332 rem_anchor_token(')');
1333 expect(')', end_error);
1334 attribute->u.argument = fold_constant(expression);
1337 attribute->invalid = true;
1341 * Parse a list of constant expressions arguments of the given attribute.
1343 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1345 argument_list_t **list = &attribute->u.arguments;
1346 argument_list_t *entry;
1347 expression_t *expression;
1348 add_anchor_token(')');
1349 add_anchor_token(',');
1351 expression = parse_constant_expression();
1352 entry = obstack_alloc(&temp_obst, sizeof(entry));
1353 entry->argument = fold_constant(expression);
1356 list = &entry->next;
1357 if (token.type != ',')
1361 rem_anchor_token(',');
1362 rem_anchor_token(')');
1363 expect(')', end_error);
1366 attribute->invalid = true;
1370 * Parse one string literal argument of the given attribute.
1372 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1375 add_anchor_token('(');
1376 if (token.type != T_STRING_LITERAL) {
1377 parse_error_expected("while parsing attribute directive",
1378 T_STRING_LITERAL, NULL);
1381 *string = parse_string_literals();
1382 rem_anchor_token('(');
1383 expect(')', end_error);
1386 attribute->invalid = true;
1390 * Parse one tls model of the given attribute.
1392 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1394 static const char *const tls_models[] = {
1400 string_t string = { NULL, 0 };
1401 parse_gnu_attribute_string_arg(attribute, &string);
1402 if (string.begin != NULL) {
1403 for (size_t i = 0; i < 4; ++i) {
1404 if (strcmp(tls_models[i], string.begin) == 0) {
1405 attribute->u.value = i;
1409 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1411 attribute->invalid = true;
1415 * Parse one tls model of the given attribute.
1417 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1419 static const char *const visibilities[] = {
1425 string_t string = { NULL, 0 };
1426 parse_gnu_attribute_string_arg(attribute, &string);
1427 if (string.begin != NULL) {
1428 for (size_t i = 0; i < 4; ++i) {
1429 if (strcmp(visibilities[i], string.begin) == 0) {
1430 attribute->u.value = i;
1434 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1436 attribute->invalid = true;
1440 * Parse one (code) model of the given attribute.
1442 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1444 static const char *const visibilities[] = {
1449 string_t string = { NULL, 0 };
1450 parse_gnu_attribute_string_arg(attribute, &string);
1451 if (string.begin != NULL) {
1452 for (int i = 0; i < 3; ++i) {
1453 if (strcmp(visibilities[i], string.begin) == 0) {
1454 attribute->u.value = i;
1458 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1460 attribute->invalid = true;
1464 * Parse one mode of the given attribute.
1466 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1468 /* TODO: find out what is allowed here... */
1470 /* at least: byte, word, pointer, list of machine modes
1471 * __XXX___ is interpreted as XXX */
1472 add_anchor_token(')');
1474 if (token.type != T_IDENTIFIER) {
1475 expect(T_IDENTIFIER, end_error);
1478 /* This isn't really correct, the backend should provide a list of machine
1479 * specific modes (according to gcc philosophy that is...) */
1480 const char *symbol_str = token.v.symbol->string;
1481 if (strcmp_underscore("QI", symbol_str) == 0 ||
1482 strcmp_underscore("byte", symbol_str) == 0) {
1483 attribute->u.akind = ATOMIC_TYPE_CHAR;
1484 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1485 attribute->u.akind = ATOMIC_TYPE_SHORT;
1486 } else if (strcmp_underscore("SI", symbol_str) == 0
1487 || strcmp_underscore("word", symbol_str) == 0
1488 || strcmp_underscore("pointer", symbol_str) == 0) {
1489 attribute->u.akind = ATOMIC_TYPE_INT;
1490 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1491 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1494 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1495 attribute->invalid = true;
1499 rem_anchor_token(')');
1500 expect(')', end_error);
1503 attribute->invalid = true;
1507 * Parse one interrupt argument of the given attribute.
1509 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1511 static const char *const interrupts[] = {
1518 string_t string = { NULL, 0 };
1519 parse_gnu_attribute_string_arg(attribute, &string);
1520 if (string.begin != NULL) {
1521 for (size_t i = 0; i < 5; ++i) {
1522 if (strcmp(interrupts[i], string.begin) == 0) {
1523 attribute->u.value = i;
1527 errorf(HERE, "'%s' is not an interrupt", string.begin);
1529 attribute->invalid = true;
1533 * Parse ( identifier, const expression, const expression )
1535 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1537 static const char *const format_names[] = {
1545 if (token.type != T_IDENTIFIER) {
1546 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1549 const char *name = token.v.symbol->string;
1550 for (i = 0; i < 4; ++i) {
1551 if (strcmp_underscore(format_names[i], name) == 0)
1555 if (warning.attribute)
1556 warningf(HERE, "'%s' is an unrecognized format function type", name);
1560 expect(',', end_error);
1561 add_anchor_token(')');
1562 add_anchor_token(',');
1563 parse_constant_expression();
1564 rem_anchor_token(',');
1565 rem_anchor_token(')');
1567 expect(',', end_error);
1568 add_anchor_token(')');
1569 parse_constant_expression();
1570 rem_anchor_token(')');
1571 expect(')', end_error);
1574 attribute->u.value = true;
1578 * Check that a given GNU attribute has no arguments.
1580 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1582 if (!attribute->has_arguments)
1585 /* should have no arguments */
1586 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1587 eat_until_matching_token('(');
1588 /* we have already consumed '(', so we stop before ')', eat it */
1590 attribute->invalid = true;
1594 * Parse one GNU attribute.
1596 * Note that attribute names can be specified WITH or WITHOUT
1597 * double underscores, ie const or __const__.
1599 * The following attributes are parsed without arguments
1624 * no_instrument_function
1625 * warn_unused_result
1642 * externally_visible
1650 * The following attributes are parsed with arguments
1651 * aligned( const expression )
1652 * alias( string literal )
1653 * section( string literal )
1654 * format( identifier, const expression, const expression )
1655 * format_arg( const expression )
1656 * tls_model( string literal )
1657 * visibility( string literal )
1658 * regparm( const expression )
1659 * model( string leteral )
1660 * trap_exit( const expression )
1661 * sp_switch( string literal )
1663 * The following attributes might have arguments
1664 * weak_ref( string literal )
1665 * non_null( const expression // ',' )
1666 * interrupt( string literal )
1667 * sentinel( constant expression )
1669 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1671 gnu_attribute_t *head = *attributes;
1672 gnu_attribute_t *last = *attributes;
1673 decl_modifiers_t modifiers = 0;
1674 gnu_attribute_t *attribute;
1676 eat(T___attribute__);
1677 expect('(', end_error);
1678 expect('(', end_error);
1680 if (token.type != ')') {
1681 /* find the end of the list */
1683 while (last->next != NULL)
1687 /* non-empty attribute list */
1690 if (token.type == T_const) {
1692 } else if (token.type == T_volatile) {
1694 } else if (token.type == T_cdecl) {
1695 /* __attribute__((cdecl)), WITH ms mode */
1697 } else if (token.type == T_IDENTIFIER) {
1698 const symbol_t *sym = token.v.symbol;
1701 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1708 for (i = 0; i < GNU_AK_LAST; ++i) {
1709 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1712 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1715 if (kind == GNU_AK_LAST) {
1716 if (warning.attribute)
1717 warningf(HERE, "'%s' attribute directive ignored", name);
1719 /* skip possible arguments */
1720 if (token.type == '(') {
1721 eat_until_matching_token(')');
1724 /* check for arguments */
1725 attribute = allocate_gnu_attribute(kind);
1726 if (token.type == '(') {
1728 if (token.type == ')') {
1729 /* empty args are allowed */
1732 attribute->has_arguments = true;
1736 case GNU_AK_VOLATILE:
1741 case GNU_AK_NOCOMMON:
1743 case GNU_AK_NOTSHARED:
1744 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1745 case GNU_AK_WARN_UNUSED_RESULT:
1746 case GNU_AK_LONGCALL:
1747 case GNU_AK_SHORTCALL:
1748 case GNU_AK_LONG_CALL:
1749 case GNU_AK_SHORT_CALL:
1750 case GNU_AK_FUNCTION_VECTOR:
1751 case GNU_AK_INTERRUPT_HANDLER:
1752 case GNU_AK_NMI_HANDLER:
1753 case GNU_AK_NESTING:
1757 case GNU_AK_EIGTHBIT_DATA:
1758 case GNU_AK_TINY_DATA:
1759 case GNU_AK_SAVEALL:
1760 case GNU_AK_FLATTEN:
1761 case GNU_AK_SSEREGPARM:
1762 case GNU_AK_EXTERNALLY_VISIBLE:
1763 case GNU_AK_RETURN_TWICE:
1764 case GNU_AK_MAY_ALIAS:
1765 case GNU_AK_MS_STRUCT:
1766 case GNU_AK_GCC_STRUCT:
1769 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1770 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1771 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1772 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1773 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1774 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1775 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1776 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1777 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1778 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1779 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1780 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1781 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1782 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1783 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1784 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1785 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1786 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1787 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1789 case GNU_AK_ALIGNED:
1790 /* __align__ may be used without an argument */
1791 if (attribute->has_arguments) {
1792 parse_gnu_attribute_const_arg(attribute);
1796 case GNU_AK_FORMAT_ARG:
1797 case GNU_AK_REGPARM:
1798 case GNU_AK_TRAP_EXIT:
1799 if (!attribute->has_arguments) {
1800 /* should have arguments */
1801 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1802 attribute->invalid = true;
1804 parse_gnu_attribute_const_arg(attribute);
1807 case GNU_AK_SECTION:
1808 case GNU_AK_SP_SWITCH:
1809 if (!attribute->has_arguments) {
1810 /* should have arguments */
1811 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1812 attribute->invalid = true;
1814 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1817 if (!attribute->has_arguments) {
1818 /* should have arguments */
1819 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1820 attribute->invalid = true;
1822 parse_gnu_attribute_format_args(attribute);
1824 case GNU_AK_WEAKREF:
1825 /* may have one string argument */
1826 if (attribute->has_arguments)
1827 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1829 case GNU_AK_NONNULL:
1830 if (attribute->has_arguments)
1831 parse_gnu_attribute_const_arg_list(attribute);
1833 case GNU_AK_TLS_MODEL:
1834 if (!attribute->has_arguments) {
1835 /* should have arguments */
1836 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1838 parse_gnu_attribute_tls_model_arg(attribute);
1840 case GNU_AK_VISIBILITY:
1841 if (!attribute->has_arguments) {
1842 /* should have arguments */
1843 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1845 parse_gnu_attribute_visibility_arg(attribute);
1848 if (!attribute->has_arguments) {
1849 /* should have arguments */
1850 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1852 parse_gnu_attribute_model_arg(attribute);
1856 if (!attribute->has_arguments) {
1857 /* should have arguments */
1858 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1860 parse_gnu_attribute_mode_arg(attribute);
1863 case GNU_AK_INTERRUPT:
1864 /* may have one string argument */
1865 if (attribute->has_arguments)
1866 parse_gnu_attribute_interrupt_arg(attribute);
1868 case GNU_AK_SENTINEL:
1869 /* may have one string argument */
1870 if (attribute->has_arguments)
1871 parse_gnu_attribute_const_arg(attribute);
1874 /* already handled */
1878 check_no_argument(attribute, name);
1881 if (attribute != NULL) {
1883 last->next = attribute;
1886 head = last = attribute;
1890 if (token.type != ',')
1895 expect(')', end_error);
1896 expect(')', end_error);
1904 * Parse GNU attributes.
1906 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1908 decl_modifiers_t modifiers = 0;
1911 switch (token.type) {
1912 case T___attribute__:
1913 modifiers |= parse_gnu_attribute(attributes);
1918 expect('(', end_error);
1919 if (token.type != T_STRING_LITERAL) {
1920 parse_error_expected("while parsing assembler attribute",
1921 T_STRING_LITERAL, NULL);
1922 eat_until_matching_token('(');
1925 parse_string_literals();
1927 expect(')', end_error);
1930 case T_cdecl: modifiers |= DM_CDECL; break;
1931 case T__fastcall: modifiers |= DM_FASTCALL; break;
1932 case T__stdcall: modifiers |= DM_STDCALL; break;
1935 /* TODO record modifier */
1937 warningf(HERE, "Ignoring declaration modifier %K", &token);
1941 default: return modifiers;
1948 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1950 static entity_t *determine_lhs_ent(expression_t *const expr,
1953 switch (expr->kind) {
1954 case EXPR_REFERENCE: {
1955 entity_t *const entity = expr->reference.entity;
1956 /* we should only find variables as lvalues... */
1957 if (entity->base.kind != ENTITY_VARIABLE
1958 && entity->base.kind != ENTITY_PARAMETER)
1964 case EXPR_ARRAY_ACCESS: {
1965 expression_t *const ref = expr->array_access.array_ref;
1966 entity_t * ent = NULL;
1967 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1968 ent = determine_lhs_ent(ref, lhs_ent);
1971 mark_vars_read(expr->select.compound, lhs_ent);
1973 mark_vars_read(expr->array_access.index, lhs_ent);
1978 if (is_type_compound(skip_typeref(expr->base.type))) {
1979 return determine_lhs_ent(expr->select.compound, lhs_ent);
1981 mark_vars_read(expr->select.compound, lhs_ent);
1986 case EXPR_UNARY_DEREFERENCE: {
1987 expression_t *const val = expr->unary.value;
1988 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1990 return determine_lhs_ent(val->unary.value, lhs_ent);
1992 mark_vars_read(val, NULL);
1998 mark_vars_read(expr, NULL);
2003 #define ENT_ANY ((entity_t*)-1)
2006 * Mark declarations, which are read. This is used to detect variables, which
2010 * x is not marked as "read", because it is only read to calculate its own new
2014 * x and y are not detected as "not read", because multiple variables are
2017 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2019 switch (expr->kind) {
2020 case EXPR_REFERENCE: {
2021 entity_t *const entity = expr->reference.entity;
2022 if (entity->kind != ENTITY_VARIABLE
2023 && entity->kind != ENTITY_PARAMETER)
2026 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2027 if (entity->kind == ENTITY_VARIABLE) {
2028 entity->variable.read = true;
2030 entity->parameter.read = true;
2037 // TODO respect pure/const
2038 mark_vars_read(expr->call.function, NULL);
2039 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2040 mark_vars_read(arg->expression, NULL);
2044 case EXPR_CONDITIONAL:
2045 // TODO lhs_decl should depend on whether true/false have an effect
2046 mark_vars_read(expr->conditional.condition, NULL);
2047 if (expr->conditional.true_expression != NULL)
2048 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2049 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2053 if (lhs_ent == ENT_ANY
2054 && !is_type_compound(skip_typeref(expr->base.type)))
2056 mark_vars_read(expr->select.compound, lhs_ent);
2059 case EXPR_ARRAY_ACCESS: {
2060 expression_t *const ref = expr->array_access.array_ref;
2061 mark_vars_read(ref, lhs_ent);
2062 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2063 mark_vars_read(expr->array_access.index, lhs_ent);
2068 mark_vars_read(expr->va_arge.ap, lhs_ent);
2071 case EXPR_UNARY_CAST:
2072 /* Special case: Use void cast to mark a variable as "read" */
2073 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2078 case EXPR_UNARY_THROW:
2079 if (expr->unary.value == NULL)
2082 case EXPR_UNARY_DEREFERENCE:
2083 case EXPR_UNARY_DELETE:
2084 case EXPR_UNARY_DELETE_ARRAY:
2085 if (lhs_ent == ENT_ANY)
2089 case EXPR_UNARY_NEGATE:
2090 case EXPR_UNARY_PLUS:
2091 case EXPR_UNARY_BITWISE_NEGATE:
2092 case EXPR_UNARY_NOT:
2093 case EXPR_UNARY_TAKE_ADDRESS:
2094 case EXPR_UNARY_POSTFIX_INCREMENT:
2095 case EXPR_UNARY_POSTFIX_DECREMENT:
2096 case EXPR_UNARY_PREFIX_INCREMENT:
2097 case EXPR_UNARY_PREFIX_DECREMENT:
2098 case EXPR_UNARY_CAST_IMPLICIT:
2099 case EXPR_UNARY_ASSUME:
2101 mark_vars_read(expr->unary.value, lhs_ent);
2104 case EXPR_BINARY_ADD:
2105 case EXPR_BINARY_SUB:
2106 case EXPR_BINARY_MUL:
2107 case EXPR_BINARY_DIV:
2108 case EXPR_BINARY_MOD:
2109 case EXPR_BINARY_EQUAL:
2110 case EXPR_BINARY_NOTEQUAL:
2111 case EXPR_BINARY_LESS:
2112 case EXPR_BINARY_LESSEQUAL:
2113 case EXPR_BINARY_GREATER:
2114 case EXPR_BINARY_GREATEREQUAL:
2115 case EXPR_BINARY_BITWISE_AND:
2116 case EXPR_BINARY_BITWISE_OR:
2117 case EXPR_BINARY_BITWISE_XOR:
2118 case EXPR_BINARY_LOGICAL_AND:
2119 case EXPR_BINARY_LOGICAL_OR:
2120 case EXPR_BINARY_SHIFTLEFT:
2121 case EXPR_BINARY_SHIFTRIGHT:
2122 case EXPR_BINARY_COMMA:
2123 case EXPR_BINARY_ISGREATER:
2124 case EXPR_BINARY_ISGREATEREQUAL:
2125 case EXPR_BINARY_ISLESS:
2126 case EXPR_BINARY_ISLESSEQUAL:
2127 case EXPR_BINARY_ISLESSGREATER:
2128 case EXPR_BINARY_ISUNORDERED:
2129 mark_vars_read(expr->binary.left, lhs_ent);
2130 mark_vars_read(expr->binary.right, lhs_ent);
2133 case EXPR_BINARY_ASSIGN:
2134 case EXPR_BINARY_MUL_ASSIGN:
2135 case EXPR_BINARY_DIV_ASSIGN:
2136 case EXPR_BINARY_MOD_ASSIGN:
2137 case EXPR_BINARY_ADD_ASSIGN:
2138 case EXPR_BINARY_SUB_ASSIGN:
2139 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2140 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2141 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2142 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2143 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2144 if (lhs_ent == ENT_ANY)
2146 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2147 mark_vars_read(expr->binary.right, lhs_ent);
2152 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2158 case EXPR_CHARACTER_CONSTANT:
2159 case EXPR_WIDE_CHARACTER_CONSTANT:
2160 case EXPR_STRING_LITERAL:
2161 case EXPR_WIDE_STRING_LITERAL:
2162 case EXPR_COMPOUND_LITERAL: // TODO init?
2164 case EXPR_CLASSIFY_TYPE:
2167 case EXPR_BUILTIN_SYMBOL:
2168 case EXPR_BUILTIN_CONSTANT_P:
2169 case EXPR_BUILTIN_PREFETCH:
2171 case EXPR_STATEMENT: // TODO
2172 case EXPR_LABEL_ADDRESS:
2173 case EXPR_REFERENCE_ENUM_VALUE:
2177 panic("unhandled expression");
2180 static designator_t *parse_designation(void)
2182 designator_t *result = NULL;
2183 designator_t *last = NULL;
2186 designator_t *designator;
2187 switch (token.type) {
2189 designator = allocate_ast_zero(sizeof(designator[0]));
2190 designator->source_position = token.source_position;
2192 add_anchor_token(']');
2193 designator->array_index = parse_constant_expression();
2194 rem_anchor_token(']');
2195 expect(']', end_error);
2198 designator = allocate_ast_zero(sizeof(designator[0]));
2199 designator->source_position = token.source_position;
2201 if (token.type != T_IDENTIFIER) {
2202 parse_error_expected("while parsing designator",
2203 T_IDENTIFIER, NULL);
2206 designator->symbol = token.v.symbol;
2210 expect('=', end_error);
2214 assert(designator != NULL);
2216 last->next = designator;
2218 result = designator;
2226 static initializer_t *initializer_from_string(array_type_t *type,
2227 const string_t *const string)
2229 /* TODO: check len vs. size of array type */
2232 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2233 initializer->string.string = *string;
2238 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2239 wide_string_t *const string)
2241 /* TODO: check len vs. size of array type */
2244 initializer_t *const initializer =
2245 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2246 initializer->wide_string.string = *string;
2252 * Build an initializer from a given expression.
2254 static initializer_t *initializer_from_expression(type_t *orig_type,
2255 expression_t *expression)
2257 /* TODO check that expression is a constant expression */
2259 /* § 6.7.8.14/15 char array may be initialized by string literals */
2260 type_t *type = skip_typeref(orig_type);
2261 type_t *expr_type_orig = expression->base.type;
2262 type_t *expr_type = skip_typeref(expr_type_orig);
2263 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2264 array_type_t *const array_type = &type->array;
2265 type_t *const element_type = skip_typeref(array_type->element_type);
2267 if (element_type->kind == TYPE_ATOMIC) {
2268 atomic_type_kind_t akind = element_type->atomic.akind;
2269 switch (expression->kind) {
2270 case EXPR_STRING_LITERAL:
2271 if (akind == ATOMIC_TYPE_CHAR
2272 || akind == ATOMIC_TYPE_SCHAR
2273 || akind == ATOMIC_TYPE_UCHAR) {
2274 return initializer_from_string(array_type,
2275 &expression->string.value);
2278 case EXPR_WIDE_STRING_LITERAL: {
2279 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2280 if (get_unqualified_type(element_type) == bare_wchar_type) {
2281 return initializer_from_wide_string(array_type,
2282 &expression->wide_string.value);
2292 assign_error_t error = semantic_assign(type, expression);
2293 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2295 report_assign_error(error, type, expression, "initializer",
2296 &expression->base.source_position);
2298 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2300 if (type->kind == TYPE_BITFIELD) {
2301 type = type->bitfield.base_type;
2304 result->value.value = create_implicit_cast(expression, type);
2310 * Checks if a given expression can be used as an constant initializer.
2312 static bool is_initializer_constant(const expression_t *expression)
2314 return is_constant_expression(expression)
2315 || is_address_constant(expression);
2319 * Parses an scalar initializer.
2321 * § 6.7.8.11; eat {} without warning
2323 static initializer_t *parse_scalar_initializer(type_t *type,
2324 bool must_be_constant)
2326 /* there might be extra {} hierarchies */
2328 if (token.type == '{') {
2330 warningf(HERE, "extra curly braces around scalar initializer");
2334 } while (token.type == '{');
2337 expression_t *expression = parse_assignment_expression();
2338 mark_vars_read(expression, NULL);
2339 if (must_be_constant && !is_initializer_constant(expression)) {
2340 errorf(&expression->base.source_position,
2341 "Initialisation expression '%E' is not constant",
2345 initializer_t *initializer = initializer_from_expression(type, expression);
2347 if (initializer == NULL) {
2348 errorf(&expression->base.source_position,
2349 "expression '%E' (type '%T') doesn't match expected type '%T'",
2350 expression, expression->base.type, type);
2355 bool additional_warning_displayed = false;
2356 while (braces > 0) {
2357 if (token.type == ',') {
2360 if (token.type != '}') {
2361 if (!additional_warning_displayed && warning.other) {
2362 warningf(HERE, "additional elements in scalar initializer");
2363 additional_warning_displayed = true;
2374 * An entry in the type path.
2376 typedef struct type_path_entry_t type_path_entry_t;
2377 struct type_path_entry_t {
2378 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2380 size_t index; /**< For array types: the current index. */
2381 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2386 * A type path expression a position inside compound or array types.
2388 typedef struct type_path_t type_path_t;
2389 struct type_path_t {
2390 type_path_entry_t *path; /**< An flexible array containing the current path. */
2391 type_t *top_type; /**< type of the element the path points */
2392 size_t max_index; /**< largest index in outermost array */
2396 * Prints a type path for debugging.
2398 static __attribute__((unused)) void debug_print_type_path(
2399 const type_path_t *path)
2401 size_t len = ARR_LEN(path->path);
2403 for (size_t i = 0; i < len; ++i) {
2404 const type_path_entry_t *entry = & path->path[i];
2406 type_t *type = skip_typeref(entry->type);
2407 if (is_type_compound(type)) {
2408 /* in gcc mode structs can have no members */
2409 if (entry->v.compound_entry == NULL) {
2413 fprintf(stderr, ".%s",
2414 entry->v.compound_entry->base.symbol->string);
2415 } else if (is_type_array(type)) {
2416 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2418 fprintf(stderr, "-INVALID-");
2421 if (path->top_type != NULL) {
2422 fprintf(stderr, " (");
2423 print_type(path->top_type);
2424 fprintf(stderr, ")");
2429 * Return the top type path entry, ie. in a path
2430 * (type).a.b returns the b.
2432 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2434 size_t len = ARR_LEN(path->path);
2436 return &path->path[len-1];
2440 * Enlarge the type path by an (empty) element.
2442 static type_path_entry_t *append_to_type_path(type_path_t *path)
2444 size_t len = ARR_LEN(path->path);
2445 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2447 type_path_entry_t *result = & path->path[len];
2448 memset(result, 0, sizeof(result[0]));
2453 * Descending into a sub-type. Enter the scope of the current top_type.
2455 static void descend_into_subtype(type_path_t *path)
2457 type_t *orig_top_type = path->top_type;
2458 type_t *top_type = skip_typeref(orig_top_type);
2460 type_path_entry_t *top = append_to_type_path(path);
2461 top->type = top_type;
2463 if (is_type_compound(top_type)) {
2464 compound_t *compound = top_type->compound.compound;
2465 entity_t *entry = compound->members.entities;
2467 if (entry != NULL) {
2468 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2469 top->v.compound_entry = &entry->declaration;
2470 path->top_type = entry->declaration.type;
2472 path->top_type = NULL;
2474 } else if (is_type_array(top_type)) {
2476 path->top_type = top_type->array.element_type;
2478 assert(!is_type_valid(top_type));
2483 * Pop an entry from the given type path, ie. returning from
2484 * (type).a.b to (type).a
2486 static void ascend_from_subtype(type_path_t *path)
2488 type_path_entry_t *top = get_type_path_top(path);
2490 path->top_type = top->type;
2492 size_t len = ARR_LEN(path->path);
2493 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2497 * Pop entries from the given type path until the given
2498 * path level is reached.
2500 static void ascend_to(type_path_t *path, size_t top_path_level)
2502 size_t len = ARR_LEN(path->path);
2504 while (len > top_path_level) {
2505 ascend_from_subtype(path);
2506 len = ARR_LEN(path->path);
2510 static bool walk_designator(type_path_t *path, const designator_t *designator,
2511 bool used_in_offsetof)
2513 for (; designator != NULL; designator = designator->next) {
2514 type_path_entry_t *top = get_type_path_top(path);
2515 type_t *orig_type = top->type;
2517 type_t *type = skip_typeref(orig_type);
2519 if (designator->symbol != NULL) {
2520 symbol_t *symbol = designator->symbol;
2521 if (!is_type_compound(type)) {
2522 if (is_type_valid(type)) {
2523 errorf(&designator->source_position,
2524 "'.%Y' designator used for non-compound type '%T'",
2528 top->type = type_error_type;
2529 top->v.compound_entry = NULL;
2530 orig_type = type_error_type;
2532 compound_t *compound = type->compound.compound;
2533 entity_t *iter = compound->members.entities;
2534 for (; iter != NULL; iter = iter->base.next) {
2535 if (iter->base.symbol == symbol) {
2540 errorf(&designator->source_position,
2541 "'%T' has no member named '%Y'", orig_type, symbol);
2544 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2545 if (used_in_offsetof) {
2546 type_t *real_type = skip_typeref(iter->declaration.type);
2547 if (real_type->kind == TYPE_BITFIELD) {
2548 errorf(&designator->source_position,
2549 "offsetof designator '%Y' may not specify bitfield",
2555 top->type = orig_type;
2556 top->v.compound_entry = &iter->declaration;
2557 orig_type = iter->declaration.type;
2560 expression_t *array_index = designator->array_index;
2561 assert(designator->array_index != NULL);
2563 if (!is_type_array(type)) {
2564 if (is_type_valid(type)) {
2565 errorf(&designator->source_position,
2566 "[%E] designator used for non-array type '%T'",
2567 array_index, orig_type);
2572 long index = fold_constant(array_index);
2573 if (!used_in_offsetof) {
2575 errorf(&designator->source_position,
2576 "array index [%E] must be positive", array_index);
2577 } else if (type->array.size_constant) {
2578 long array_size = type->array.size;
2579 if (index >= array_size) {
2580 errorf(&designator->source_position,
2581 "designator [%E] (%d) exceeds array size %d",
2582 array_index, index, array_size);
2587 top->type = orig_type;
2588 top->v.index = (size_t) index;
2589 orig_type = type->array.element_type;
2591 path->top_type = orig_type;
2593 if (designator->next != NULL) {
2594 descend_into_subtype(path);
2603 static void advance_current_object(type_path_t *path, size_t top_path_level)
2605 type_path_entry_t *top = get_type_path_top(path);
2607 type_t *type = skip_typeref(top->type);
2608 if (is_type_union(type)) {
2609 /* in unions only the first element is initialized */
2610 top->v.compound_entry = NULL;
2611 } else if (is_type_struct(type)) {
2612 declaration_t *entry = top->v.compound_entry;
2614 entity_t *next_entity = entry->base.next;
2615 if (next_entity != NULL) {
2616 assert(is_declaration(next_entity));
2617 entry = &next_entity->declaration;
2622 top->v.compound_entry = entry;
2623 if (entry != NULL) {
2624 path->top_type = entry->type;
2627 } else if (is_type_array(type)) {
2628 assert(is_type_array(type));
2632 if (!type->array.size_constant || top->v.index < type->array.size) {
2636 assert(!is_type_valid(type));
2640 /* we're past the last member of the current sub-aggregate, try if we
2641 * can ascend in the type hierarchy and continue with another subobject */
2642 size_t len = ARR_LEN(path->path);
2644 if (len > top_path_level) {
2645 ascend_from_subtype(path);
2646 advance_current_object(path, top_path_level);
2648 path->top_type = NULL;
2653 * skip until token is found.
2655 static void skip_until(int type)
2657 while (token.type != type) {
2658 if (token.type == T_EOF)
2665 * skip any {...} blocks until a closing bracket is reached.
2667 static void skip_initializers(void)
2669 if (token.type == '{')
2672 while (token.type != '}') {
2673 if (token.type == T_EOF)
2675 if (token.type == '{') {
2683 static initializer_t *create_empty_initializer(void)
2685 static initializer_t empty_initializer
2686 = { .list = { { INITIALIZER_LIST }, 0 } };
2687 return &empty_initializer;
2691 * Parse a part of an initialiser for a struct or union,
2693 static initializer_t *parse_sub_initializer(type_path_t *path,
2694 type_t *outer_type, size_t top_path_level,
2695 parse_initializer_env_t *env)
2697 if (token.type == '}') {
2698 /* empty initializer */
2699 return create_empty_initializer();
2702 type_t *orig_type = path->top_type;
2703 type_t *type = NULL;
2705 if (orig_type == NULL) {
2706 /* We are initializing an empty compound. */
2708 type = skip_typeref(orig_type);
2711 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2714 designator_t *designator = NULL;
2715 if (token.type == '.' || token.type == '[') {
2716 designator = parse_designation();
2717 goto finish_designator;
2718 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2719 /* GNU-style designator ("identifier: value") */
2720 designator = allocate_ast_zero(sizeof(designator[0]));
2721 designator->source_position = token.source_position;
2722 designator->symbol = token.v.symbol;
2727 /* reset path to toplevel, evaluate designator from there */
2728 ascend_to(path, top_path_level);
2729 if (!walk_designator(path, designator, false)) {
2730 /* can't continue after designation error */
2734 initializer_t *designator_initializer
2735 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2736 designator_initializer->designator.designator = designator;
2737 ARR_APP1(initializer_t*, initializers, designator_initializer);
2739 orig_type = path->top_type;
2740 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2745 if (token.type == '{') {
2746 if (type != NULL && is_type_scalar(type)) {
2747 sub = parse_scalar_initializer(type, env->must_be_constant);
2751 if (env->entity != NULL) {
2753 "extra brace group at end of initializer for '%Y'",
2754 env->entity->base.symbol);
2756 errorf(HERE, "extra brace group at end of initializer");
2759 descend_into_subtype(path);
2761 add_anchor_token('}');
2762 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2764 rem_anchor_token('}');
2767 ascend_from_subtype(path);
2768 expect('}', end_error);
2770 expect('}', end_error);
2771 goto error_parse_next;
2775 /* must be an expression */
2776 expression_t *expression = parse_assignment_expression();
2777 mark_vars_read(expression, NULL);
2779 if (env->must_be_constant && !is_initializer_constant(expression)) {
2780 errorf(&expression->base.source_position,
2781 "Initialisation expression '%E' is not constant",
2786 /* we are already outside, ... */
2787 type_t *const outer_type_skip = skip_typeref(outer_type);
2788 if (is_type_compound(outer_type_skip) &&
2789 !outer_type_skip->compound.compound->complete) {
2790 goto error_parse_next;
2795 /* handle { "string" } special case */
2796 if ((expression->kind == EXPR_STRING_LITERAL
2797 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2798 && outer_type != NULL) {
2799 sub = initializer_from_expression(outer_type, expression);
2801 if (token.type == ',') {
2804 if (token.type != '}' && warning.other) {
2805 warningf(HERE, "excessive elements in initializer for type '%T'",
2808 /* TODO: eat , ... */
2813 /* descend into subtypes until expression matches type */
2815 orig_type = path->top_type;
2816 type = skip_typeref(orig_type);
2818 sub = initializer_from_expression(orig_type, expression);
2822 if (!is_type_valid(type)) {
2825 if (is_type_scalar(type)) {
2826 errorf(&expression->base.source_position,
2827 "expression '%E' doesn't match expected type '%T'",
2828 expression, orig_type);
2832 descend_into_subtype(path);
2836 /* update largest index of top array */
2837 const type_path_entry_t *first = &path->path[0];
2838 type_t *first_type = first->type;
2839 first_type = skip_typeref(first_type);
2840 if (is_type_array(first_type)) {
2841 size_t index = first->v.index;
2842 if (index > path->max_index)
2843 path->max_index = index;
2847 /* append to initializers list */
2848 ARR_APP1(initializer_t*, initializers, sub);
2851 if (warning.other) {
2852 if (env->entity != NULL) {
2853 warningf(HERE, "excess elements in struct initializer for '%Y'",
2854 env->entity->base.symbol);
2856 warningf(HERE, "excess elements in struct initializer");
2862 if (token.type == '}') {
2865 expect(',', end_error);
2866 if (token.type == '}') {
2871 /* advance to the next declaration if we are not at the end */
2872 advance_current_object(path, top_path_level);
2873 orig_type = path->top_type;
2874 if (orig_type != NULL)
2875 type = skip_typeref(orig_type);
2881 size_t len = ARR_LEN(initializers);
2882 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2883 initializer_t *result = allocate_ast_zero(size);
2884 result->kind = INITIALIZER_LIST;
2885 result->list.len = len;
2886 memcpy(&result->list.initializers, initializers,
2887 len * sizeof(initializers[0]));
2889 DEL_ARR_F(initializers);
2890 ascend_to(path, top_path_level+1);
2895 skip_initializers();
2896 DEL_ARR_F(initializers);
2897 ascend_to(path, top_path_level+1);
2902 * Parses an initializer. Parsers either a compound literal
2903 * (env->declaration == NULL) or an initializer of a declaration.
2905 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2907 type_t *type = skip_typeref(env->type);
2908 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2909 initializer_t *result;
2911 if (is_type_scalar(type)) {
2912 result = parse_scalar_initializer(type, env->must_be_constant);
2913 } else if (token.type == '{') {
2917 memset(&path, 0, sizeof(path));
2918 path.top_type = env->type;
2919 path.path = NEW_ARR_F(type_path_entry_t, 0);
2921 descend_into_subtype(&path);
2923 add_anchor_token('}');
2924 result = parse_sub_initializer(&path, env->type, 1, env);
2925 rem_anchor_token('}');
2927 max_index = path.max_index;
2928 DEL_ARR_F(path.path);
2930 expect('}', end_error);
2932 /* parse_scalar_initializer() also works in this case: we simply
2933 * have an expression without {} around it */
2934 result = parse_scalar_initializer(type, env->must_be_constant);
2937 /* § 6.7.8:22 array initializers for arrays with unknown size determine
2938 * the array type size */
2939 if (is_type_array(type) && type->array.size_expression == NULL
2940 && result != NULL) {
2942 switch (result->kind) {
2943 case INITIALIZER_LIST:
2944 assert(max_index != 0xdeadbeaf);
2945 size = max_index + 1;
2948 case INITIALIZER_STRING:
2949 size = result->string.string.size;
2952 case INITIALIZER_WIDE_STRING:
2953 size = result->wide_string.string.size;
2956 case INITIALIZER_DESIGNATOR:
2957 case INITIALIZER_VALUE:
2958 /* can happen for parse errors */
2963 internal_errorf(HERE, "invalid initializer type");
2966 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2967 cnst->base.type = type_size_t;
2968 cnst->conste.v.int_value = size;
2970 type_t *new_type = duplicate_type(type);
2972 new_type->array.size_expression = cnst;
2973 new_type->array.size_constant = true;
2974 new_type->array.has_implicit_size = true;
2975 new_type->array.size = size;
2976 env->type = new_type;
2984 static void append_entity(scope_t *scope, entity_t *entity)
2986 if (scope->last_entity != NULL) {
2987 scope->last_entity->base.next = entity;
2989 scope->entities = entity;
2991 scope->last_entity = entity;
2995 static compound_t *parse_compound_type_specifier(bool is_struct)
2997 gnu_attribute_t *attributes = NULL;
2998 decl_modifiers_t modifiers = 0;
3005 symbol_t *symbol = NULL;
3006 compound_t *compound = NULL;
3008 if (token.type == T___attribute__) {
3009 modifiers |= parse_attributes(&attributes);
3012 if (token.type == T_IDENTIFIER) {
3013 symbol = token.v.symbol;
3016 namespace_tag_t const namespc =
3017 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3018 entity_t *entity = get_entity(symbol, namespc);
3019 if (entity != NULL) {
3020 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3021 compound = &entity->compound;
3022 if (compound->base.parent_scope != current_scope &&
3023 (token.type == '{' || token.type == ';')) {
3024 /* we're in an inner scope and have a definition. Shadow
3025 * existing definition in outer scope */
3027 } else if (compound->complete && token.type == '{') {
3028 assert(symbol != NULL);
3029 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3030 is_struct ? "struct" : "union", symbol,
3031 &compound->base.source_position);
3032 /* clear members in the hope to avoid further errors */
3033 compound->members.entities = NULL;
3036 } else if (token.type != '{') {
3038 parse_error_expected("while parsing struct type specifier",
3039 T_IDENTIFIER, '{', NULL);
3041 parse_error_expected("while parsing union type specifier",
3042 T_IDENTIFIER, '{', NULL);
3048 if (compound == NULL) {
3049 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3050 entity_t *entity = allocate_entity_zero(kind);
3051 compound = &entity->compound;
3053 compound->base.namespc =
3054 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3055 compound->base.source_position = token.source_position;
3056 compound->base.symbol = symbol;
3057 compound->base.parent_scope = current_scope;
3058 if (symbol != NULL) {
3059 environment_push(entity);
3061 append_entity(current_scope, entity);
3064 if (token.type == '{') {
3065 parse_compound_type_entries(compound);
3066 modifiers |= parse_attributes(&attributes);
3068 if (symbol == NULL) {
3069 assert(anonymous_entity == NULL);
3070 anonymous_entity = (entity_t*)compound;
3074 compound->modifiers |= modifiers;
3078 static void parse_enum_entries(type_t *const enum_type)
3082 if (token.type == '}') {
3083 errorf(HERE, "empty enum not allowed");
3088 add_anchor_token('}');
3090 if (token.type != T_IDENTIFIER) {
3091 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3093 rem_anchor_token('}');
3097 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3098 entity->enum_value.enum_type = enum_type;
3099 entity->base.symbol = token.v.symbol;
3100 entity->base.source_position = token.source_position;
3103 if (token.type == '=') {
3105 expression_t *value = parse_constant_expression();
3107 value = create_implicit_cast(value, enum_type);
3108 entity->enum_value.value = value;
3113 record_entity(entity, false);
3115 if (token.type != ',')
3118 } while (token.type != '}');
3119 rem_anchor_token('}');
3121 expect('}', end_error);
3127 static type_t *parse_enum_specifier(void)
3129 gnu_attribute_t *attributes = NULL;
3134 if (token.type == T_IDENTIFIER) {
3135 symbol = token.v.symbol;
3138 entity = get_entity(symbol, NAMESPACE_ENUM);
3139 if (entity != NULL) {
3140 assert(entity->kind == ENTITY_ENUM);
3141 if (entity->base.parent_scope != current_scope &&
3142 (token.type == '{' || token.type == ';')) {
3143 /* we're in an inner scope and have a definition. Shadow
3144 * existing definition in outer scope */
3146 } else if (entity->enume.complete && token.type == '{') {
3147 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3148 symbol, &entity->base.source_position);
3151 } else if (token.type != '{') {
3152 parse_error_expected("while parsing enum type specifier",
3153 T_IDENTIFIER, '{', NULL);
3160 if (entity == NULL) {
3161 entity = allocate_entity_zero(ENTITY_ENUM);
3162 entity->base.namespc = NAMESPACE_ENUM;
3163 entity->base.source_position = token.source_position;
3164 entity->base.symbol = symbol;
3165 entity->base.parent_scope = current_scope;
3168 type_t *const type = allocate_type_zero(TYPE_ENUM);
3169 type->enumt.enume = &entity->enume;
3171 if (token.type == '{') {
3172 if (symbol != NULL) {
3173 environment_push(entity);
3175 append_entity(current_scope, entity);
3176 entity->enume.complete = true;
3178 parse_enum_entries(type);
3179 parse_attributes(&attributes);
3181 if (symbol == NULL) {
3182 assert(anonymous_entity == NULL);
3183 anonymous_entity = entity;
3185 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3186 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3194 * if a symbol is a typedef to another type, return true
3196 static bool is_typedef_symbol(symbol_t *symbol)
3198 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3199 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3202 static type_t *parse_typeof(void)
3208 expect('(', end_error);
3209 add_anchor_token(')');
3211 expression_t *expression = NULL;
3213 bool old_type_prop = in_type_prop;
3214 bool old_gcc_extension = in_gcc_extension;
3215 in_type_prop = true;
3217 while (token.type == T___extension__) {
3218 /* This can be a prefix to a typename or an expression. */
3220 in_gcc_extension = true;
3222 switch (token.type) {
3224 if (is_typedef_symbol(token.v.symbol)) {
3225 type = parse_typename();
3227 expression = parse_expression();
3228 type = expression->base.type;
3233 type = parse_typename();
3237 expression = parse_expression();
3238 type = expression->base.type;
3241 in_type_prop = old_type_prop;
3242 in_gcc_extension = old_gcc_extension;
3244 rem_anchor_token(')');
3245 expect(')', end_error);
3247 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3248 typeof_type->typeoft.expression = expression;
3249 typeof_type->typeoft.typeof_type = type;
3256 typedef enum specifiers_t {
3257 SPECIFIER_SIGNED = 1 << 0,
3258 SPECIFIER_UNSIGNED = 1 << 1,
3259 SPECIFIER_LONG = 1 << 2,
3260 SPECIFIER_INT = 1 << 3,
3261 SPECIFIER_DOUBLE = 1 << 4,
3262 SPECIFIER_CHAR = 1 << 5,
3263 SPECIFIER_WCHAR_T = 1 << 6,
3264 SPECIFIER_SHORT = 1 << 7,
3265 SPECIFIER_LONG_LONG = 1 << 8,
3266 SPECIFIER_FLOAT = 1 << 9,
3267 SPECIFIER_BOOL = 1 << 10,
3268 SPECIFIER_VOID = 1 << 11,
3269 SPECIFIER_INT8 = 1 << 12,
3270 SPECIFIER_INT16 = 1 << 13,
3271 SPECIFIER_INT32 = 1 << 14,
3272 SPECIFIER_INT64 = 1 << 15,
3273 SPECIFIER_INT128 = 1 << 16,
3274 SPECIFIER_COMPLEX = 1 << 17,
3275 SPECIFIER_IMAGINARY = 1 << 18,
3278 static type_t *create_builtin_type(symbol_t *const symbol,
3279 type_t *const real_type)
3281 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3282 type->builtin.symbol = symbol;
3283 type->builtin.real_type = real_type;
3284 return identify_new_type(type);
3287 static type_t *get_typedef_type(symbol_t *symbol)
3289 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3290 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3293 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3294 type->typedeft.typedefe = &entity->typedefe;
3300 * check for the allowed MS alignment values.
3302 static bool check_alignment_value(long long intvalue)
3304 if (intvalue < 1 || intvalue > 8192) {
3305 errorf(HERE, "illegal alignment value");
3308 unsigned v = (unsigned)intvalue;
3309 for (unsigned i = 1; i <= 8192; i += i) {
3313 errorf(HERE, "alignment must be power of two");
3317 #define DET_MOD(name, tag) do { \
3318 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3319 *modifiers |= tag; \
3322 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3324 decl_modifiers_t *modifiers = &specifiers->modifiers;
3327 if (token.type == T_restrict) {
3329 DET_MOD(restrict, DM_RESTRICT);
3331 } else if (token.type != T_IDENTIFIER)
3333 symbol_t *symbol = token.v.symbol;
3334 if (symbol == sym_align) {
3336 expect('(', end_error);
3337 if (token.type != T_INTEGER)
3339 if (check_alignment_value(token.v.intvalue)) {
3340 if (specifiers->alignment != 0 && warning.other)
3341 warningf(HERE, "align used more than once");
3342 specifiers->alignment = (unsigned char)token.v.intvalue;
3345 expect(')', end_error);
3346 } else if (symbol == sym_allocate) {
3348 expect('(', end_error);
3349 if (token.type != T_IDENTIFIER)
3351 (void)token.v.symbol;
3352 expect(')', end_error);
3353 } else if (symbol == sym_dllimport) {
3355 DET_MOD(dllimport, DM_DLLIMPORT);
3356 } else if (symbol == sym_dllexport) {
3358 DET_MOD(dllexport, DM_DLLEXPORT);
3359 } else if (symbol == sym_thread) {
3361 DET_MOD(thread, DM_THREAD);
3362 } else if (symbol == sym_naked) {
3364 DET_MOD(naked, DM_NAKED);
3365 } else if (symbol == sym_noinline) {
3367 DET_MOD(noinline, DM_NOINLINE);
3368 } else if (symbol == sym_returns_twice) {
3370 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3371 } else if (symbol == sym_noreturn) {
3373 DET_MOD(noreturn, DM_NORETURN);
3374 } else if (symbol == sym_nothrow) {
3376 DET_MOD(nothrow, DM_NOTHROW);
3377 } else if (symbol == sym_novtable) {
3379 DET_MOD(novtable, DM_NOVTABLE);
3380 } else if (symbol == sym_property) {
3382 expect('(', end_error);
3384 bool is_get = false;
3385 if (token.type != T_IDENTIFIER)
3387 if (token.v.symbol == sym_get) {
3389 } else if (token.v.symbol == sym_put) {
3391 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3395 expect('=', end_error);
3396 if (token.type != T_IDENTIFIER)
3399 if (specifiers->get_property_sym != NULL) {
3400 errorf(HERE, "get property name already specified");
3402 specifiers->get_property_sym = token.v.symbol;
3405 if (specifiers->put_property_sym != NULL) {
3406 errorf(HERE, "put property name already specified");
3408 specifiers->put_property_sym = token.v.symbol;
3412 if (token.type == ',') {
3418 expect(')', end_error);
3419 } else if (symbol == sym_selectany) {
3421 DET_MOD(selectany, DM_SELECTANY);
3422 } else if (symbol == sym_uuid) {
3424 expect('(', end_error);
3425 if (token.type != T_STRING_LITERAL)
3428 expect(')', end_error);
3429 } else if (symbol == sym_deprecated) {
3431 if (specifiers->deprecated != 0 && warning.other)
3432 warningf(HERE, "deprecated used more than once");
3433 specifiers->deprecated = true;
3434 if (token.type == '(') {
3436 if (token.type == T_STRING_LITERAL) {
3437 specifiers->deprecated_string = token.v.string.begin;
3440 errorf(HERE, "string literal expected");
3442 expect(')', end_error);
3444 } else if (symbol == sym_noalias) {
3446 DET_MOD(noalias, DM_NOALIAS);
3449 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3451 if (token.type == '(')
3455 if (token.type == ',')
3462 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3464 entity_t *entity = allocate_entity_zero(kind);
3465 entity->base.source_position = *HERE;
3466 entity->base.symbol = symbol;
3467 if (is_declaration(entity)) {
3468 entity->declaration.type = type_error_type;
3469 entity->declaration.implicit = true;
3470 } else if (kind == ENTITY_TYPEDEF) {
3471 entity->typedefe.type = type_error_type;
3472 entity->typedefe.builtin = true;
3474 if (kind != ENTITY_COMPOUND_MEMBER)
3475 record_entity(entity, false);
3479 static void parse_microsoft_based(based_spec_t *based_spec)
3481 if (token.type != T_IDENTIFIER) {
3482 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3485 symbol_t *symbol = token.v.symbol;
3486 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3488 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3489 errorf(HERE, "'%Y' is not a variable name.", symbol);
3490 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3492 variable_t *variable = &entity->variable;
3494 if (based_spec->base_variable != NULL) {
3495 errorf(HERE, "__based type qualifier specified more than once");
3497 based_spec->source_position = token.source_position;
3498 based_spec->base_variable = variable;
3500 type_t *const type = variable->base.type;
3502 if (is_type_valid(type)) {
3503 if (! is_type_pointer(skip_typeref(type))) {
3504 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3506 if (variable->base.base.parent_scope != file_scope) {
3507 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3515 * Finish the construction of a struct type by calculating
3516 * its size, offsets, alignment.
3518 static void finish_struct_type(compound_type_t *type)
3520 assert(type->compound != NULL);
3522 compound_t *compound = type->compound;
3523 if (!compound->complete)
3528 il_alignment_t alignment = 1;
3529 bool need_pad = false;
3531 entity_t *entry = compound->members.entities;
3532 for (; entry != NULL; entry = entry->base.next) {
3533 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3536 type_t *m_type = skip_typeref(entry->declaration.type);
3537 if (! is_type_valid(m_type)) {
3538 /* simply ignore errors here */
3541 il_alignment_t m_alignment = m_type->base.alignment;
3542 if (m_alignment > alignment)
3543 alignment = m_alignment;
3545 offset = (size + m_alignment - 1) & -m_alignment;
3549 entry->compound_member.offset = offset;
3550 size = offset + m_type->base.size;
3552 if (type->base.alignment != 0) {
3553 alignment = type->base.alignment;
3556 offset = (size + alignment - 1) & -alignment;
3561 if (warning.padded) {
3562 warningf(&compound->base.source_position, "'%T' needs padding", type);
3565 if (compound->modifiers & DM_PACKED && warning.packed) {
3566 warningf(&compound->base.source_position,
3567 "superfluous packed attribute on '%T'", type);
3571 type->base.size = offset;
3572 type->base.alignment = alignment;
3576 * Finish the construction of an union type by calculating
3577 * its size and alignment.
3579 static void finish_union_type(compound_type_t *type)
3581 assert(type->compound != NULL);
3583 compound_t *compound = type->compound;
3584 if (! compound->complete)
3588 il_alignment_t alignment = 1;
3590 entity_t *entry = compound->members.entities;
3591 for (; entry != NULL; entry = entry->base.next) {
3592 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3595 type_t *m_type = skip_typeref(entry->declaration.type);
3596 if (! is_type_valid(m_type))
3599 entry->compound_member.offset = 0;
3600 if (m_type->base.size > size)
3601 size = m_type->base.size;
3602 if (m_type->base.alignment > alignment)
3603 alignment = m_type->base.alignment;
3605 if (type->base.alignment != 0) {
3606 alignment = type->base.alignment;
3608 size = (size + alignment - 1) & -alignment;
3609 type->base.size = size;
3610 type->base.alignment = alignment;
3613 static type_t *handle_mode_attribute(const gnu_attribute_t *attribute,
3616 type_t *type = skip_typeref(orig_type);
3617 if (type->kind != TYPE_ATOMIC) {
3619 "__attribute__(mode)) only allowed for atomic types");
3622 atomic_type_kind_t akind = attribute->u.akind;
3623 if (!is_type_signed(type)) {
3625 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3626 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3627 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3628 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3630 errorf(HERE, "invalid akind in mode attribute");
3635 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
3636 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
3637 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
3638 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
3640 errorf(HERE, "invalid akind in mode attribute");
3645 type_t *copy = duplicate_type(type);
3646 copy->atomic.akind = akind;
3647 return identify_new_type(copy);
3650 static type_t *handle_type_attributes(const gnu_attribute_t *attributes,
3653 /* handle these strange/stupid mode attributes */
3654 const gnu_attribute_t *attribute = attributes;
3655 for ( ; attribute != NULL; attribute = attribute->next) {
3656 if (attribute->invalid)
3659 if (attribute->kind == GNU_AK_MODE) {
3660 type = handle_mode_attribute(attribute, type);
3661 } else if (attribute->kind == GNU_AK_ALIGNED) {
3662 int alignment = 32; /* TODO: fill in maximum useful alignment for
3664 if (attribute->has_arguments)
3665 alignment = attribute->u.argument;
3667 type_t *copy = duplicate_type(type);
3668 copy->base.alignment = attribute->u.argument;
3669 type = identify_new_type(copy);
3676 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3678 type_t *type = NULL;
3679 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3680 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3681 unsigned type_specifiers = 0;
3682 bool newtype = false;
3683 bool saw_error = false;
3684 bool old_gcc_extension = in_gcc_extension;
3686 specifiers->source_position = token.source_position;
3689 specifiers->modifiers
3690 |= parse_attributes(&specifiers->gnu_attributes);
3692 switch (token.type) {
3694 #define MATCH_STORAGE_CLASS(token, class) \
3696 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3697 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3699 specifiers->storage_class = class; \
3700 if (specifiers->thread_local) \
3701 goto check_thread_storage_class; \
3705 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3706 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3707 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3708 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3709 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3713 expect('(', end_error);
3714 add_anchor_token(')');
3715 parse_microsoft_extended_decl_modifier(specifiers);
3716 rem_anchor_token(')');
3717 expect(')', end_error);
3721 if (specifiers->thread_local) {
3722 errorf(HERE, "duplicate '__thread'");
3724 specifiers->thread_local = true;
3725 check_thread_storage_class:
3726 switch (specifiers->storage_class) {
3727 case STORAGE_CLASS_EXTERN:
3728 case STORAGE_CLASS_NONE:
3729 case STORAGE_CLASS_STATIC:
3733 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3734 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3735 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3736 wrong_thread_stoarge_class:
3737 errorf(HERE, "'__thread' used with '%s'", wrong);
3744 /* type qualifiers */
3745 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3747 qualifiers |= qualifier; \
3751 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3752 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3753 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3754 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3755 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3756 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3757 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3758 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3760 case T___extension__:
3762 in_gcc_extension = true;
3765 /* type specifiers */
3766 #define MATCH_SPECIFIER(token, specifier, name) \
3768 if (type_specifiers & specifier) { \
3769 errorf(HERE, "multiple " name " type specifiers given"); \
3771 type_specifiers |= specifier; \
3776 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3777 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3778 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3779 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3780 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3781 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3782 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3783 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3784 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3785 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3786 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3787 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3788 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3789 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3790 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3791 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3792 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3793 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3795 case T__forceinline:
3796 /* only in microsoft mode */
3797 specifiers->modifiers |= DM_FORCEINLINE;
3802 specifiers->is_inline = true;
3806 if (type_specifiers & SPECIFIER_LONG_LONG) {
3807 errorf(HERE, "multiple type specifiers given");
3808 } else if (type_specifiers & SPECIFIER_LONG) {
3809 type_specifiers |= SPECIFIER_LONG_LONG;
3811 type_specifiers |= SPECIFIER_LONG;
3817 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3819 type->compound.compound = parse_compound_type_specifier(true);
3820 finish_struct_type(&type->compound);
3824 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3825 type->compound.compound = parse_compound_type_specifier(false);
3826 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3827 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3828 finish_union_type(&type->compound);
3832 type = parse_enum_specifier();
3835 type = parse_typeof();
3837 case T___builtin_va_list:
3838 type = duplicate_type(type_valist);
3842 case T_IDENTIFIER: {
3843 /* only parse identifier if we haven't found a type yet */
3844 if (type != NULL || type_specifiers != 0) {
3845 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3846 * declaration, so it doesn't generate errors about expecting '(' or
3848 switch (look_ahead(1)->type) {
3855 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3859 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3864 goto finish_specifiers;
3868 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3869 if (typedef_type == NULL) {
3870 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3871 * declaration, so it doesn't generate 'implicit int' followed by more
3872 * errors later on. */
3873 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3879 errorf(HERE, "%K does not name a type", &token);
3882 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3884 type = allocate_type_zero(TYPE_TYPEDEF);
3885 type->typedeft.typedefe = &entity->typedefe;
3889 if (la1_type == '&' || la1_type == '*')
3890 goto finish_specifiers;
3895 goto finish_specifiers;
3900 type = typedef_type;
3904 /* function specifier */
3906 goto finish_specifiers;
3911 specifiers->modifiers
3912 |= parse_attributes(&specifiers->gnu_attributes);
3914 in_gcc_extension = old_gcc_extension;
3916 if (type == NULL || (saw_error && type_specifiers != 0)) {
3917 atomic_type_kind_t atomic_type;
3919 /* match valid basic types */
3920 switch (type_specifiers) {
3921 case SPECIFIER_VOID:
3922 atomic_type = ATOMIC_TYPE_VOID;
3924 case SPECIFIER_WCHAR_T:
3925 atomic_type = ATOMIC_TYPE_WCHAR_T;
3927 case SPECIFIER_CHAR:
3928 atomic_type = ATOMIC_TYPE_CHAR;
3930 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3931 atomic_type = ATOMIC_TYPE_SCHAR;
3933 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3934 atomic_type = ATOMIC_TYPE_UCHAR;
3936 case SPECIFIER_SHORT:
3937 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3938 case SPECIFIER_SHORT | SPECIFIER_INT:
3939 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3940 atomic_type = ATOMIC_TYPE_SHORT;
3942 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3943 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3944 atomic_type = ATOMIC_TYPE_USHORT;
3947 case SPECIFIER_SIGNED:
3948 case SPECIFIER_SIGNED | SPECIFIER_INT:
3949 atomic_type = ATOMIC_TYPE_INT;
3951 case SPECIFIER_UNSIGNED:
3952 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3953 atomic_type = ATOMIC_TYPE_UINT;
3955 case SPECIFIER_LONG:
3956 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3957 case SPECIFIER_LONG | SPECIFIER_INT:
3958 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3959 atomic_type = ATOMIC_TYPE_LONG;
3961 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3962 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3963 atomic_type = ATOMIC_TYPE_ULONG;
3966 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3967 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3968 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3969 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3971 atomic_type = ATOMIC_TYPE_LONGLONG;
3972 goto warn_about_long_long;
3974 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3975 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3977 atomic_type = ATOMIC_TYPE_ULONGLONG;
3978 warn_about_long_long:
3979 if (warning.long_long) {
3980 warningf(&specifiers->source_position,
3981 "ISO C90 does not support 'long long'");
3985 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3986 atomic_type = unsigned_int8_type_kind;
3989 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3990 atomic_type = unsigned_int16_type_kind;
3993 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3994 atomic_type = unsigned_int32_type_kind;
3997 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3998 atomic_type = unsigned_int64_type_kind;
4001 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
4002 atomic_type = unsigned_int128_type_kind;
4005 case SPECIFIER_INT8:
4006 case SPECIFIER_SIGNED | SPECIFIER_INT8:
4007 atomic_type = int8_type_kind;
4010 case SPECIFIER_INT16:
4011 case SPECIFIER_SIGNED | SPECIFIER_INT16:
4012 atomic_type = int16_type_kind;
4015 case SPECIFIER_INT32:
4016 case SPECIFIER_SIGNED | SPECIFIER_INT32:
4017 atomic_type = int32_type_kind;
4020 case SPECIFIER_INT64:
4021 case SPECIFIER_SIGNED | SPECIFIER_INT64:
4022 atomic_type = int64_type_kind;
4025 case SPECIFIER_INT128:
4026 case SPECIFIER_SIGNED | SPECIFIER_INT128:
4027 atomic_type = int128_type_kind;
4030 case SPECIFIER_FLOAT:
4031 atomic_type = ATOMIC_TYPE_FLOAT;
4033 case SPECIFIER_DOUBLE:
4034 atomic_type = ATOMIC_TYPE_DOUBLE;
4036 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
4037 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4039 case SPECIFIER_BOOL:
4040 atomic_type = ATOMIC_TYPE_BOOL;
4042 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
4043 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
4044 atomic_type = ATOMIC_TYPE_FLOAT;
4046 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4047 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4048 atomic_type = ATOMIC_TYPE_DOUBLE;
4050 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4051 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4052 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4055 /* invalid specifier combination, give an error message */
4056 if (type_specifiers == 0) {
4060 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4061 if (!(c_mode & _CXX) && !strict_mode) {
4062 if (warning.implicit_int) {
4063 warningf(HERE, "no type specifiers in declaration, using 'int'");
4065 atomic_type = ATOMIC_TYPE_INT;
4068 errorf(HERE, "no type specifiers given in declaration");
4070 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4071 (type_specifiers & SPECIFIER_UNSIGNED)) {
4072 errorf(HERE, "signed and unsigned specifiers given");
4073 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4074 errorf(HERE, "only integer types can be signed or unsigned");
4076 errorf(HERE, "multiple datatypes in declaration");
4081 if (type_specifiers & SPECIFIER_COMPLEX) {
4082 type = allocate_type_zero(TYPE_COMPLEX);
4083 type->complex.akind = atomic_type;
4084 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4085 type = allocate_type_zero(TYPE_IMAGINARY);
4086 type->imaginary.akind = atomic_type;
4088 type = allocate_type_zero(TYPE_ATOMIC);
4089 type->atomic.akind = atomic_type;
4091 type->base.alignment = get_atomic_type_alignment(atomic_type);
4092 unsigned const size = get_atomic_type_size(atomic_type);
4094 type_specifiers & SPECIFIER_COMPLEX ? size * 2 : size;
4096 } else if (type_specifiers != 0) {
4097 errorf(HERE, "multiple datatypes in declaration");
4100 /* FIXME: check type qualifiers here */
4102 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
4103 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4104 type->base.qualifiers = qualifiers;
4105 type->base.modifiers = modifiers;
4107 type = identify_new_type(type);
4109 type = handle_type_attributes(specifiers->gnu_attributes, type);
4110 specifiers->type = type;
4114 specifiers->type = type_error_type;
4118 static type_qualifiers_t parse_type_qualifiers(void)
4120 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4123 switch (token.type) {
4124 /* type qualifiers */
4125 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4126 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4127 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4128 /* microsoft extended type modifiers */
4129 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4130 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4131 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4132 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4133 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4142 * Parses an K&R identifier list
4144 static void parse_identifier_list(scope_t *scope)
4147 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4148 entity->base.source_position = token.source_position;
4149 entity->base.namespc = NAMESPACE_NORMAL;
4150 entity->base.symbol = token.v.symbol;
4151 /* a K&R parameter has no type, yet */
4155 append_entity(scope, entity);
4157 if (token.type != ',') {
4161 } while (token.type == T_IDENTIFIER);
4164 static entity_t *parse_parameter(void)
4166 declaration_specifiers_t specifiers;
4167 memset(&specifiers, 0, sizeof(specifiers));
4169 parse_declaration_specifiers(&specifiers);
4171 entity_t *entity = parse_declarator(&specifiers,
4172 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4173 anonymous_entity = NULL;
4177 static void semantic_parameter_incomplete(const entity_t *entity)
4179 assert(entity->kind == ENTITY_PARAMETER);
4181 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4182 * list in a function declarator that is part of a
4183 * definition of that function shall not have
4184 * incomplete type. */
4185 type_t *type = skip_typeref(entity->declaration.type);
4186 if (is_type_incomplete(type)) {
4187 errorf(&entity->base.source_position,
4188 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4189 entity->declaration.type);
4194 * Parses function type parameters (and optionally creates variable_t entities
4195 * for them in a scope)
4197 static void parse_parameters(function_type_t *type, scope_t *scope)
4200 add_anchor_token(')');
4201 int saved_comma_state = save_and_reset_anchor_state(',');
4203 if (token.type == T_IDENTIFIER &&
4204 !is_typedef_symbol(token.v.symbol)) {
4205 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4206 if (la1_type == ',' || la1_type == ')') {
4207 type->kr_style_parameters = true;
4208 type->unspecified_parameters = true;
4209 parse_identifier_list(scope);
4210 goto parameters_finished;
4214 if (token.type == ')') {
4215 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4216 if (!(c_mode & _CXX))
4217 type->unspecified_parameters = true;
4218 goto parameters_finished;
4221 function_parameter_t *parameter;
4222 function_parameter_t *last_parameter = NULL;
4225 switch (token.type) {
4228 type->variadic = true;
4229 goto parameters_finished;
4232 case T___extension__:
4235 entity_t *entity = parse_parameter();
4236 if (entity->kind == ENTITY_TYPEDEF) {
4237 errorf(&entity->base.source_position,
4238 "typedef not allowed as function parameter");
4241 assert(is_declaration(entity));
4243 /* func(void) is not a parameter */
4244 if (last_parameter == NULL
4245 && token.type == ')'
4246 && entity->base.symbol == NULL
4247 && skip_typeref(entity->declaration.type) == type_void) {
4248 goto parameters_finished;
4250 semantic_parameter_incomplete(entity);
4252 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4253 memset(parameter, 0, sizeof(parameter[0]));
4254 parameter->type = entity->declaration.type;
4256 if (scope != NULL) {
4257 append_entity(scope, entity);
4260 if (last_parameter != NULL) {
4261 last_parameter->next = parameter;
4263 type->parameters = parameter;
4265 last_parameter = parameter;
4270 goto parameters_finished;
4272 if (token.type != ',') {
4273 goto parameters_finished;
4279 parameters_finished:
4280 rem_anchor_token(')');
4281 expect(')', end_error);
4284 restore_anchor_state(',', saved_comma_state);
4287 typedef enum construct_type_kind_t {
4290 CONSTRUCT_REFERENCE,
4293 } construct_type_kind_t;
4295 typedef struct construct_type_t construct_type_t;
4296 struct construct_type_t {
4297 construct_type_kind_t kind;
4298 construct_type_t *next;
4301 typedef struct parsed_pointer_t parsed_pointer_t;
4302 struct parsed_pointer_t {
4303 construct_type_t construct_type;
4304 type_qualifiers_t type_qualifiers;
4305 variable_t *base_variable; /**< MS __based extension. */
4308 typedef struct parsed_reference_t parsed_reference_t;
4309 struct parsed_reference_t {
4310 construct_type_t construct_type;
4313 typedef struct construct_function_type_t construct_function_type_t;
4314 struct construct_function_type_t {
4315 construct_type_t construct_type;
4316 type_t *function_type;
4319 typedef struct parsed_array_t parsed_array_t;
4320 struct parsed_array_t {
4321 construct_type_t construct_type;
4322 type_qualifiers_t type_qualifiers;
4328 typedef struct construct_base_type_t construct_base_type_t;
4329 struct construct_base_type_t {
4330 construct_type_t construct_type;
4334 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4338 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4339 memset(pointer, 0, sizeof(pointer[0]));
4340 pointer->construct_type.kind = CONSTRUCT_POINTER;
4341 pointer->type_qualifiers = parse_type_qualifiers();
4342 pointer->base_variable = base_variable;
4344 return &pointer->construct_type;
4347 static construct_type_t *parse_reference_declarator(void)
4351 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4352 memset(reference, 0, sizeof(reference[0]));
4353 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4355 return (construct_type_t*)reference;
4358 static construct_type_t *parse_array_declarator(void)
4361 add_anchor_token(']');
4363 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4364 memset(array, 0, sizeof(array[0]));
4365 array->construct_type.kind = CONSTRUCT_ARRAY;
4367 if (token.type == T_static) {
4368 array->is_static = true;
4372 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4373 if (type_qualifiers != 0) {
4374 if (token.type == T_static) {
4375 array->is_static = true;
4379 array->type_qualifiers = type_qualifiers;
4381 if (token.type == '*' && look_ahead(1)->type == ']') {
4382 array->is_variable = true;
4384 } else if (token.type != ']') {
4385 expression_t *const size = parse_assignment_expression();
4387 mark_vars_read(size, NULL);
4390 rem_anchor_token(']');
4391 expect(']', end_error);
4394 return &array->construct_type;
4397 static construct_type_t *parse_function_declarator(scope_t *scope,
4398 decl_modifiers_t modifiers)
4400 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4401 function_type_t *ftype = &type->function;
4403 ftype->linkage = current_linkage;
4405 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4406 case DM_NONE: break;
4407 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4408 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4409 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4410 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4413 errorf(HERE, "multiple calling conventions in declaration");
4417 parse_parameters(ftype, scope);
4419 construct_function_type_t *construct_function_type =
4420 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4421 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4422 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4423 construct_function_type->function_type = type;
4425 return &construct_function_type->construct_type;
4428 typedef struct parse_declarator_env_t {
4429 decl_modifiers_t modifiers;
4431 source_position_t source_position;
4433 } parse_declarator_env_t;
4435 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4436 bool may_be_abstract)
4438 /* construct a single linked list of construct_type_t's which describe
4439 * how to construct the final declarator type */
4440 construct_type_t *first = NULL;
4441 construct_type_t *last = NULL;
4442 gnu_attribute_t *attributes = NULL;
4444 decl_modifiers_t modifiers = parse_attributes(&attributes);
4446 /* MS __based extension */
4447 based_spec_t base_spec;
4448 base_spec.base_variable = NULL;
4451 construct_type_t *type;
4452 switch (token.type) {
4454 if (!(c_mode & _CXX))
4455 errorf(HERE, "references are only available for C++");
4456 if (base_spec.base_variable != NULL && warning.other) {
4457 warningf(&base_spec.source_position,
4458 "__based does not precede a pointer operator, ignored");
4460 type = parse_reference_declarator();
4462 base_spec.base_variable = NULL;
4466 type = parse_pointer_declarator(base_spec.base_variable);
4468 base_spec.base_variable = NULL;
4473 expect('(', end_error);
4474 add_anchor_token(')');
4475 parse_microsoft_based(&base_spec);
4476 rem_anchor_token(')');
4477 expect(')', end_error);
4481 goto ptr_operator_end;
4492 /* TODO: find out if this is correct */
4493 modifiers |= parse_attributes(&attributes);
4496 if (base_spec.base_variable != NULL && warning.other) {
4497 warningf(&base_spec.source_position,
4498 "__based does not precede a pointer operator, ignored");
4502 modifiers |= env->modifiers;
4503 env->modifiers = modifiers;
4506 construct_type_t *inner_types = NULL;
4508 switch (token.type) {
4511 errorf(HERE, "no identifier expected in typename");
4513 env->symbol = token.v.symbol;
4514 env->source_position = token.source_position;
4519 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4520 * interpreted as ``function with no parameter specification'', rather
4521 * than redundant parentheses around the omitted identifier. */
4522 if (look_ahead(1)->type != ')') {
4524 add_anchor_token(')');
4525 inner_types = parse_inner_declarator(env, may_be_abstract);
4526 if (inner_types != NULL) {
4527 /* All later declarators only modify the return type */
4530 rem_anchor_token(')');
4531 expect(')', end_error);
4535 if (may_be_abstract)
4537 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4542 construct_type_t *p = last;
4545 construct_type_t *type;
4546 switch (token.type) {
4548 scope_t *scope = NULL;
4550 scope = &env->parameters;
4552 type = parse_function_declarator(scope, modifiers);
4556 type = parse_array_declarator();
4559 goto declarator_finished;
4562 /* insert in the middle of the list (behind p) */
4564 type->next = p->next;
4575 declarator_finished:
4576 /* append inner_types at the end of the list, we don't to set last anymore
4577 * as it's not needed anymore */
4579 assert(first == NULL);
4580 first = inner_types;
4582 last->next = inner_types;
4590 static void parse_declaration_attributes(entity_t *entity)
4592 gnu_attribute_t *attributes = NULL;
4593 decl_modifiers_t modifiers = parse_attributes(&attributes);
4599 if (entity->kind == ENTITY_TYPEDEF) {
4600 modifiers |= entity->typedefe.modifiers;
4601 type = entity->typedefe.type;
4603 assert(is_declaration(entity));
4604 modifiers |= entity->declaration.modifiers;
4605 type = entity->declaration.type;
4610 /* handle these strange/stupid mode attributes */
4611 gnu_attribute_t *attribute = attributes;
4612 for ( ; attribute != NULL; attribute = attribute->next) {
4613 if (attribute->invalid)
4616 if (attribute->kind == GNU_AK_MODE) {
4617 type = handle_mode_attribute(attribute, type);
4618 } else if (attribute->kind == GNU_AK_ALIGNED) {
4619 int alignment = 32; /* TODO: fill in maximum usefull alignment for target machine */
4620 if (attribute->has_arguments)
4621 alignment = attribute->u.argument;
4623 if (entity->kind == ENTITY_TYPEDEF) {
4624 type_t *copy = duplicate_type(type);
4625 copy->base.alignment = attribute->u.argument;
4626 type = identify_new_type(copy);
4627 } else if(entity->kind == ENTITY_VARIABLE) {
4628 entity->variable.alignment = alignment;
4629 } else if(entity->kind == ENTITY_COMPOUND_MEMBER) {
4630 entity->compound_member.alignment = alignment;
4635 type_modifiers_t type_modifiers = type->base.modifiers;
4636 if (modifiers & DM_TRANSPARENT_UNION)
4637 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4639 if (type->base.modifiers != type_modifiers) {
4640 type_t *copy = duplicate_type(type);
4641 copy->base.modifiers = type_modifiers;
4642 type = identify_new_type(copy);
4645 if (entity->kind == ENTITY_TYPEDEF) {
4646 entity->typedefe.type = type;
4647 entity->typedefe.modifiers = modifiers;
4649 entity->declaration.type = type;
4650 entity->declaration.modifiers = modifiers;
4654 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4656 construct_type_t *iter = construct_list;
4657 for (; iter != NULL; iter = iter->next) {
4658 switch (iter->kind) {
4659 case CONSTRUCT_INVALID:
4660 internal_errorf(HERE, "invalid type construction found");
4661 case CONSTRUCT_FUNCTION: {
4662 construct_function_type_t *construct_function_type
4663 = (construct_function_type_t*) iter;
4665 type_t *function_type = construct_function_type->function_type;
4667 function_type->function.return_type = type;
4669 type_t *skipped_return_type = skip_typeref(type);
4671 if (is_type_function(skipped_return_type)) {
4672 errorf(HERE, "function returning function is not allowed");
4673 } else if (is_type_array(skipped_return_type)) {
4674 errorf(HERE, "function returning array is not allowed");
4676 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4678 "type qualifiers in return type of function type are meaningless");
4682 type = function_type;
4686 case CONSTRUCT_POINTER: {
4687 if (is_type_reference(skip_typeref(type)))
4688 errorf(HERE, "cannot declare a pointer to reference");
4690 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4691 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4695 case CONSTRUCT_REFERENCE:
4696 if (is_type_reference(skip_typeref(type)))
4697 errorf(HERE, "cannot declare a reference to reference");
4699 type = make_reference_type(type);
4702 case CONSTRUCT_ARRAY: {
4703 if (is_type_reference(skip_typeref(type)))
4704 errorf(HERE, "cannot declare an array of references");
4706 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4707 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4709 expression_t *size_expression = parsed_array->size;
4710 if (size_expression != NULL) {
4712 = create_implicit_cast(size_expression, type_size_t);
4715 array_type->base.qualifiers = parsed_array->type_qualifiers;
4716 array_type->array.element_type = type;
4717 array_type->array.is_static = parsed_array->is_static;
4718 array_type->array.is_variable = parsed_array->is_variable;
4719 array_type->array.size_expression = size_expression;
4721 if (size_expression != NULL) {
4722 if (is_constant_expression(size_expression)) {
4723 array_type->array.size_constant = true;
4724 array_type->array.size
4725 = fold_constant(size_expression);
4727 array_type->array.is_vla = true;
4731 type_t *skipped_type = skip_typeref(type);
4733 if (is_type_incomplete(skipped_type)) {
4734 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4735 } else if (is_type_function(skipped_type)) {
4736 errorf(HERE, "array of functions is not allowed");
4743 /* The function type was constructed earlier. Freeing it here will
4744 * destroy other types. */
4745 if (iter->kind == CONSTRUCT_FUNCTION) {
4746 type = typehash_insert(type);
4748 type = identify_new_type(type);
4755 static type_t *automatic_type_conversion(type_t *orig_type);
4757 static type_t *semantic_parameter(const source_position_t *pos,
4759 const declaration_specifiers_t *specifiers,
4762 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4763 * shall be adjusted to ``qualified pointer to type'',
4765 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4766 * type'' shall be adjusted to ``pointer to function
4767 * returning type'', as in 6.3.2.1. */
4768 type = automatic_type_conversion(type);
4770 if (specifiers->is_inline && is_type_valid(type)) {
4771 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4774 /* §6.9.1:6 The declarations in the declaration list shall contain
4775 * no storage-class specifier other than register and no
4776 * initializations. */
4777 if (specifiers->thread_local || (
4778 specifiers->storage_class != STORAGE_CLASS_NONE &&
4779 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4781 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4784 /* delay test for incomplete type, because we might have (void)
4785 * which is legal but incomplete... */
4790 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4791 declarator_flags_t flags)
4793 parse_declarator_env_t env;
4794 memset(&env, 0, sizeof(env));
4795 env.modifiers = specifiers->modifiers;
4797 construct_type_t *construct_type =
4798 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4800 construct_declarator_type(construct_type, specifiers->type);
4801 type_t *type = skip_typeref(orig_type);
4803 if (construct_type != NULL) {
4804 obstack_free(&temp_obst, construct_type);
4808 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4809 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4810 entity->base.symbol = env.symbol;
4811 entity->base.source_position = env.source_position;
4812 entity->typedefe.type = orig_type;
4814 if (anonymous_entity != NULL) {
4815 if (is_type_compound(type)) {
4816 assert(anonymous_entity->compound.alias == NULL);
4817 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4818 anonymous_entity->kind == ENTITY_UNION);
4819 anonymous_entity->compound.alias = entity;
4820 anonymous_entity = NULL;
4821 } else if (is_type_enum(type)) {
4822 assert(anonymous_entity->enume.alias == NULL);
4823 assert(anonymous_entity->kind == ENTITY_ENUM);
4824 anonymous_entity->enume.alias = entity;
4825 anonymous_entity = NULL;
4829 /* create a declaration type entity */
4830 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4831 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4833 if (env.symbol != NULL) {
4834 if (specifiers->is_inline && is_type_valid(type)) {
4835 errorf(&env.source_position,
4836 "compound member '%Y' declared 'inline'", env.symbol);
4839 if (specifiers->thread_local ||
4840 specifiers->storage_class != STORAGE_CLASS_NONE) {
4841 errorf(&env.source_position,
4842 "compound member '%Y' must have no storage class",
4846 } else if (flags & DECL_IS_PARAMETER) {
4847 orig_type = semantic_parameter(&env.source_position, orig_type,
4848 specifiers, env.symbol);
4850 entity = allocate_entity_zero(ENTITY_PARAMETER);
4851 } else if (is_type_function(type)) {
4852 entity = allocate_entity_zero(ENTITY_FUNCTION);
4854 entity->function.is_inline = specifiers->is_inline;
4855 entity->function.parameters = env.parameters;
4857 if (env.symbol != NULL) {
4858 if (specifiers->thread_local || (
4859 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4860 specifiers->storage_class != STORAGE_CLASS_NONE &&
4861 specifiers->storage_class != STORAGE_CLASS_STATIC
4863 errorf(&env.source_position,
4864 "invalid storage class for function '%Y'", env.symbol);
4868 entity = allocate_entity_zero(ENTITY_VARIABLE);
4870 entity->variable.get_property_sym = specifiers->get_property_sym;
4871 entity->variable.put_property_sym = specifiers->put_property_sym;
4873 entity->variable.thread_local = specifiers->thread_local;
4875 if (env.symbol != NULL) {
4876 if (specifiers->is_inline && is_type_valid(type)) {
4877 errorf(&env.source_position,
4878 "variable '%Y' declared 'inline'", env.symbol);
4881 bool invalid_storage_class = false;
4882 if (current_scope == file_scope) {
4883 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4884 specifiers->storage_class != STORAGE_CLASS_NONE &&
4885 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4886 invalid_storage_class = true;
4889 if (specifiers->thread_local &&
4890 specifiers->storage_class == STORAGE_CLASS_NONE) {
4891 invalid_storage_class = true;
4894 if (invalid_storage_class) {
4895 errorf(&env.source_position,
4896 "invalid storage class for variable '%Y'", env.symbol);
4901 if (env.symbol != NULL) {
4902 entity->base.symbol = env.symbol;
4903 entity->base.source_position = env.source_position;
4905 entity->base.source_position = specifiers->source_position;
4907 entity->base.namespc = NAMESPACE_NORMAL;
4908 entity->declaration.type = orig_type;
4909 entity->declaration.modifiers = env.modifiers;
4910 entity->declaration.deprecated_string = specifiers->deprecated_string;
4912 storage_class_t storage_class = specifiers->storage_class;
4913 entity->declaration.declared_storage_class = storage_class;
4915 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4916 storage_class = STORAGE_CLASS_AUTO;
4917 entity->declaration.storage_class = storage_class;
4920 parse_declaration_attributes(entity);
4925 static type_t *parse_abstract_declarator(type_t *base_type)
4927 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4929 type_t *result = construct_declarator_type(construct_type, base_type);
4930 if (construct_type != NULL) {
4931 obstack_free(&temp_obst, construct_type);
4938 * Check if the declaration of main is suspicious. main should be a
4939 * function with external linkage, returning int, taking either zero
4940 * arguments, two, or three arguments of appropriate types, ie.
4942 * int main([ int argc, char **argv [, char **env ] ]).
4944 * @param decl the declaration to check
4945 * @param type the function type of the declaration
4947 static void check_type_of_main(const entity_t *entity)
4949 const source_position_t *pos = &entity->base.source_position;
4950 if (entity->kind != ENTITY_FUNCTION) {
4951 warningf(pos, "'main' is not a function");
4955 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4956 warningf(pos, "'main' is normally a non-static function");
4959 type_t *type = skip_typeref(entity->declaration.type);
4960 assert(is_type_function(type));
4962 function_type_t *func_type = &type->function;
4963 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4964 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4965 func_type->return_type);
4967 const function_parameter_t *parm = func_type->parameters;
4969 type_t *const first_type = parm->type;
4970 if (!types_compatible(skip_typeref(first_type), type_int)) {
4972 "first argument of 'main' should be 'int', but is '%T'",
4977 type_t *const second_type = parm->type;
4978 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4979 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4983 type_t *const third_type = parm->type;
4984 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4985 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4989 goto warn_arg_count;
4993 warningf(pos, "'main' takes only zero, two or three arguments");
4999 * Check if a symbol is the equal to "main".
5001 static bool is_sym_main(const symbol_t *const sym)
5003 return strcmp(sym->string, "main") == 0;
5006 static void error_redefined_as_different_kind(const source_position_t *pos,
5007 const entity_t *old, entity_kind_t new_kind)
5009 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
5010 get_entity_kind_name(old->kind), old->base.symbol,
5011 get_entity_kind_name(new_kind), &old->base.source_position);
5015 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
5016 * for various problems that occur for multiple definitions
5018 static entity_t *record_entity(entity_t *entity, const bool is_definition)
5020 const symbol_t *const symbol = entity->base.symbol;
5021 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
5022 const source_position_t *pos = &entity->base.source_position;
5024 /* can happen in error cases */
5028 entity_t *previous_entity = get_entity(symbol, namespc);
5029 /* pushing the same entity twice will break the stack structure */
5030 assert(previous_entity != entity);
5032 if (entity->kind == ENTITY_FUNCTION) {
5033 type_t *const orig_type = entity->declaration.type;
5034 type_t *const type = skip_typeref(orig_type);
5036 assert(is_type_function(type));
5037 if (type->function.unspecified_parameters &&
5038 warning.strict_prototypes &&
5039 previous_entity == NULL) {
5040 warningf(pos, "function declaration '%#T' is not a prototype",
5044 if (warning.main && current_scope == file_scope
5045 && is_sym_main(symbol)) {
5046 check_type_of_main(entity);
5050 if (is_declaration(entity) &&
5051 warning.nested_externs &&
5052 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5053 current_scope != file_scope) {
5054 warningf(pos, "nested extern declaration of '%#T'",
5055 entity->declaration.type, symbol);
5058 if (previous_entity != NULL &&
5059 previous_entity->base.parent_scope == ¤t_function->parameters &&
5060 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5061 assert(previous_entity->kind == ENTITY_PARAMETER);
5063 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5064 entity->declaration.type, symbol,
5065 previous_entity->declaration.type, symbol,
5066 &previous_entity->base.source_position);
5070 if (previous_entity != NULL &&
5071 previous_entity->base.parent_scope == current_scope) {
5072 if (previous_entity->kind != entity->kind) {
5073 error_redefined_as_different_kind(pos, previous_entity,
5077 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5078 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5079 symbol, &previous_entity->base.source_position);
5082 if (previous_entity->kind == ENTITY_TYPEDEF) {
5083 /* TODO: C++ allows this for exactly the same type */
5084 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5085 symbol, &previous_entity->base.source_position);
5089 /* at this point we should have only VARIABLES or FUNCTIONS */
5090 assert(is_declaration(previous_entity) && is_declaration(entity));
5092 declaration_t *const prev_decl = &previous_entity->declaration;
5093 declaration_t *const decl = &entity->declaration;
5095 /* can happen for K&R style declarations */
5096 if (prev_decl->type == NULL &&
5097 previous_entity->kind == ENTITY_PARAMETER &&
5098 entity->kind == ENTITY_PARAMETER) {
5099 prev_decl->type = decl->type;
5100 prev_decl->storage_class = decl->storage_class;
5101 prev_decl->declared_storage_class = decl->declared_storage_class;
5102 prev_decl->modifiers = decl->modifiers;
5103 prev_decl->deprecated_string = decl->deprecated_string;
5104 return previous_entity;
5107 type_t *const orig_type = decl->type;
5108 assert(orig_type != NULL);
5109 type_t *const type = skip_typeref(orig_type);
5110 type_t * prev_type = skip_typeref(prev_decl->type);
5112 if (!types_compatible(type, prev_type)) {
5114 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5115 orig_type, symbol, prev_decl->type, symbol,
5116 &previous_entity->base.source_position);
5118 unsigned old_storage_class = prev_decl->storage_class;
5119 if (warning.redundant_decls &&
5122 !(prev_decl->modifiers & DM_USED) &&
5123 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5124 warningf(&previous_entity->base.source_position,
5125 "unnecessary static forward declaration for '%#T'",
5126 prev_decl->type, symbol);
5129 unsigned new_storage_class = decl->storage_class;
5130 if (is_type_incomplete(prev_type)) {
5131 prev_decl->type = type;
5135 /* pretend no storage class means extern for function
5136 * declarations (except if the previous declaration is neither
5137 * none nor extern) */
5138 if (entity->kind == ENTITY_FUNCTION) {
5139 if (prev_type->function.unspecified_parameters) {
5140 prev_decl->type = type;
5144 switch (old_storage_class) {
5145 case STORAGE_CLASS_NONE:
5146 old_storage_class = STORAGE_CLASS_EXTERN;
5149 case STORAGE_CLASS_EXTERN:
5150 if (is_definition) {
5151 if (warning.missing_prototypes &&
5152 prev_type->function.unspecified_parameters &&
5153 !is_sym_main(symbol)) {
5154 warningf(pos, "no previous prototype for '%#T'",
5157 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5158 new_storage_class = STORAGE_CLASS_EXTERN;
5167 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5168 new_storage_class == STORAGE_CLASS_EXTERN) {
5169 warn_redundant_declaration:
5170 if (!is_definition &&
5171 warning.redundant_decls &&
5172 is_type_valid(prev_type) &&
5173 strcmp(previous_entity->base.source_position.input_name,
5174 "<builtin>") != 0) {
5176 "redundant declaration for '%Y' (declared %P)",
5177 symbol, &previous_entity->base.source_position);
5179 } else if (current_function == NULL) {
5180 if (old_storage_class != STORAGE_CLASS_STATIC &&
5181 new_storage_class == STORAGE_CLASS_STATIC) {
5183 "static declaration of '%Y' follows non-static declaration (declared %P)",
5184 symbol, &previous_entity->base.source_position);
5185 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5186 prev_decl->storage_class = STORAGE_CLASS_NONE;
5187 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5189 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5191 goto error_redeclaration;
5192 goto warn_redundant_declaration;
5194 } else if (is_type_valid(prev_type)) {
5195 if (old_storage_class == new_storage_class) {
5196 error_redeclaration:
5197 errorf(pos, "redeclaration of '%Y' (declared %P)",
5198 symbol, &previous_entity->base.source_position);
5201 "redeclaration of '%Y' with different linkage (declared %P)",
5202 symbol, &previous_entity->base.source_position);
5207 prev_decl->modifiers |= decl->modifiers;
5208 if (entity->kind == ENTITY_FUNCTION) {
5209 previous_entity->function.is_inline |= entity->function.is_inline;
5211 return previous_entity;
5214 if (entity->kind == ENTITY_FUNCTION) {
5215 if (is_definition &&
5216 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5217 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5218 warningf(pos, "no previous prototype for '%#T'",
5219 entity->declaration.type, symbol);
5220 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5221 warningf(pos, "no previous declaration for '%#T'",
5222 entity->declaration.type, symbol);
5225 } else if (warning.missing_declarations &&
5226 entity->kind == ENTITY_VARIABLE &&
5227 current_scope == file_scope) {
5228 declaration_t *declaration = &entity->declaration;
5229 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5230 warningf(pos, "no previous declaration for '%#T'",
5231 declaration->type, symbol);
5236 assert(entity->base.parent_scope == NULL);
5237 assert(current_scope != NULL);
5239 entity->base.parent_scope = current_scope;
5240 entity->base.namespc = NAMESPACE_NORMAL;
5241 environment_push(entity);
5242 append_entity(current_scope, entity);
5247 static void parser_error_multiple_definition(entity_t *entity,
5248 const source_position_t *source_position)
5250 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5251 entity->base.symbol, &entity->base.source_position);
5254 static bool is_declaration_specifier(const token_t *token,
5255 bool only_specifiers_qualifiers)
5257 switch (token->type) {
5262 return is_typedef_symbol(token->v.symbol);
5264 case T___extension__:
5266 return !only_specifiers_qualifiers;
5273 static void parse_init_declarator_rest(entity_t *entity)
5275 assert(is_declaration(entity));
5276 declaration_t *const declaration = &entity->declaration;
5280 type_t *orig_type = declaration->type;
5281 type_t *type = skip_typeref(orig_type);
5283 if (entity->kind == ENTITY_VARIABLE
5284 && entity->variable.initializer != NULL) {
5285 parser_error_multiple_definition(entity, HERE);
5288 bool must_be_constant = false;
5289 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5290 entity->base.parent_scope == file_scope) {
5291 must_be_constant = true;
5294 if (is_type_function(type)) {
5295 errorf(&entity->base.source_position,
5296 "function '%#T' is initialized like a variable",
5297 orig_type, entity->base.symbol);
5298 orig_type = type_error_type;
5301 parse_initializer_env_t env;
5302 env.type = orig_type;
5303 env.must_be_constant = must_be_constant;
5304 env.entity = entity;
5305 current_init_decl = entity;
5307 initializer_t *initializer = parse_initializer(&env);
5308 current_init_decl = NULL;
5310 if (entity->kind == ENTITY_VARIABLE) {
5311 /* § 6.7.5:22 array initializers for arrays with unknown size
5312 * determine the array type size */
5313 declaration->type = env.type;
5314 entity->variable.initializer = initializer;
5318 /* parse rest of a declaration without any declarator */
5319 static void parse_anonymous_declaration_rest(
5320 const declaration_specifiers_t *specifiers)
5323 anonymous_entity = NULL;
5325 if (warning.other) {
5326 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5327 specifiers->thread_local) {
5328 warningf(&specifiers->source_position,
5329 "useless storage class in empty declaration");
5332 type_t *type = specifiers->type;
5333 switch (type->kind) {
5334 case TYPE_COMPOUND_STRUCT:
5335 case TYPE_COMPOUND_UNION: {
5336 if (type->compound.compound->base.symbol == NULL) {
5337 warningf(&specifiers->source_position,
5338 "unnamed struct/union that defines no instances");
5347 warningf(&specifiers->source_position, "empty declaration");
5353 static void check_variable_type_complete(entity_t *ent)
5355 if (ent->kind != ENTITY_VARIABLE)
5358 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5359 * type for the object shall be complete [...] */
5360 declaration_t *decl = &ent->declaration;
5361 if (decl->storage_class != STORAGE_CLASS_NONE)
5364 type_t *const orig_type = decl->type;
5365 type_t *const type = skip_typeref(orig_type);
5366 if (!is_type_incomplete(type))
5369 /* GCC allows global arrays without size and assigns them a length of one,
5370 * if no different declaration follows */
5371 if (is_type_array(type) &&
5373 ent->base.parent_scope == file_scope) {
5374 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5378 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5379 orig_type, ent->base.symbol);
5383 static void parse_declaration_rest(entity_t *ndeclaration,
5384 const declaration_specifiers_t *specifiers,
5385 parsed_declaration_func finished_declaration,
5386 declarator_flags_t flags)
5388 add_anchor_token(';');
5389 add_anchor_token(',');
5391 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5393 if (token.type == '=') {
5394 parse_init_declarator_rest(entity);
5395 } else if (entity->kind == ENTITY_VARIABLE) {
5396 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5397 * [...] where the extern specifier is explicitly used. */
5398 declaration_t *decl = &entity->declaration;
5399 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5400 type_t *type = decl->type;
5401 if (is_type_reference(skip_typeref(type))) {
5402 errorf(&entity->base.source_position,
5403 "reference '%#T' must be initialized",
5404 type, entity->base.symbol);
5409 check_variable_type_complete(entity);
5411 if (token.type != ',')
5415 add_anchor_token('=');
5416 ndeclaration = parse_declarator(specifiers, flags);
5417 rem_anchor_token('=');
5419 expect(';', end_error);
5422 anonymous_entity = NULL;
5423 rem_anchor_token(';');
5424 rem_anchor_token(',');
5427 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5429 symbol_t *symbol = entity->base.symbol;
5430 if (symbol == NULL) {
5431 errorf(HERE, "anonymous declaration not valid as function parameter");
5435 assert(entity->base.namespc == NAMESPACE_NORMAL);
5436 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5437 if (previous_entity == NULL
5438 || previous_entity->base.parent_scope != current_scope) {
5439 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5444 if (is_definition) {
5445 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5448 return record_entity(entity, false);
5451 static void parse_declaration(parsed_declaration_func finished_declaration,
5452 declarator_flags_t flags)
5454 declaration_specifiers_t specifiers;
5455 memset(&specifiers, 0, sizeof(specifiers));
5457 add_anchor_token(';');
5458 parse_declaration_specifiers(&specifiers);
5459 rem_anchor_token(';');
5461 if (token.type == ';') {
5462 parse_anonymous_declaration_rest(&specifiers);
5464 entity_t *entity = parse_declarator(&specifiers, flags);
5465 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5469 static type_t *get_default_promoted_type(type_t *orig_type)
5471 type_t *result = orig_type;
5473 type_t *type = skip_typeref(orig_type);
5474 if (is_type_integer(type)) {
5475 result = promote_integer(type);
5476 } else if (type == type_float) {
5477 result = type_double;
5483 static void parse_kr_declaration_list(entity_t *entity)
5485 if (entity->kind != ENTITY_FUNCTION)
5488 type_t *type = skip_typeref(entity->declaration.type);
5489 assert(is_type_function(type));
5490 if (!type->function.kr_style_parameters)
5494 add_anchor_token('{');
5496 /* push function parameters */
5497 size_t const top = environment_top();
5498 scope_t *old_scope = scope_push(&entity->function.parameters);
5500 entity_t *parameter = entity->function.parameters.entities;
5501 for ( ; parameter != NULL; parameter = parameter->base.next) {
5502 assert(parameter->base.parent_scope == NULL);
5503 parameter->base.parent_scope = current_scope;
5504 environment_push(parameter);
5507 /* parse declaration list */
5509 switch (token.type) {
5511 case T___extension__:
5512 /* This covers symbols, which are no type, too, and results in
5513 * better error messages. The typical cases are misspelled type
5514 * names and missing includes. */
5516 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5524 /* pop function parameters */
5525 assert(current_scope == &entity->function.parameters);
5526 scope_pop(old_scope);
5527 environment_pop_to(top);
5529 /* update function type */
5530 type_t *new_type = duplicate_type(type);
5532 function_parameter_t *parameters = NULL;
5533 function_parameter_t *last_parameter = NULL;
5535 parameter = entity->function.parameters.entities;
5536 for (; parameter != NULL; parameter = parameter->base.next) {
5537 type_t *parameter_type = parameter->declaration.type;
5538 if (parameter_type == NULL) {
5540 errorf(HERE, "no type specified for function parameter '%Y'",
5541 parameter->base.symbol);
5543 if (warning.implicit_int) {
5544 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5545 parameter->base.symbol);
5547 parameter_type = type_int;
5548 parameter->declaration.type = parameter_type;
5552 semantic_parameter_incomplete(parameter);
5553 parameter_type = parameter->declaration.type;
5556 * we need the default promoted types for the function type
5558 parameter_type = get_default_promoted_type(parameter_type);
5560 function_parameter_t *function_parameter
5561 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5562 memset(function_parameter, 0, sizeof(function_parameter[0]));
5564 function_parameter->type = parameter_type;
5565 if (last_parameter != NULL) {
5566 last_parameter->next = function_parameter;
5568 parameters = function_parameter;
5570 last_parameter = function_parameter;
5573 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5575 new_type->function.parameters = parameters;
5576 new_type->function.unspecified_parameters = true;
5578 new_type = identify_new_type(new_type);
5580 entity->declaration.type = new_type;
5582 rem_anchor_token('{');
5585 static bool first_err = true;
5588 * When called with first_err set, prints the name of the current function,
5591 static void print_in_function(void)
5595 diagnosticf("%s: In function '%Y':\n",
5596 current_function->base.base.source_position.input_name,
5597 current_function->base.base.symbol);
5602 * Check if all labels are defined in the current function.
5603 * Check if all labels are used in the current function.
5605 static void check_labels(void)
5607 for (const goto_statement_t *goto_statement = goto_first;
5608 goto_statement != NULL;
5609 goto_statement = goto_statement->next) {
5610 /* skip computed gotos */
5611 if (goto_statement->expression != NULL)
5614 label_t *label = goto_statement->label;
5617 if (label->base.source_position.input_name == NULL) {
5618 print_in_function();
5619 errorf(&goto_statement->base.source_position,
5620 "label '%Y' used but not defined", label->base.symbol);
5624 if (warning.unused_label) {
5625 for (const label_statement_t *label_statement = label_first;
5626 label_statement != NULL;
5627 label_statement = label_statement->next) {
5628 label_t *label = label_statement->label;
5630 if (! label->used) {
5631 print_in_function();
5632 warningf(&label_statement->base.source_position,
5633 "label '%Y' defined but not used", label->base.symbol);
5639 static void warn_unused_entity(entity_t *entity, entity_t *last)
5641 entity_t const *const end = last != NULL ? last->base.next : NULL;
5642 for (; entity != end; entity = entity->base.next) {
5643 if (!is_declaration(entity))
5646 declaration_t *declaration = &entity->declaration;
5647 if (declaration->implicit)
5650 if (!declaration->used) {
5651 print_in_function();
5652 const char *what = get_entity_kind_name(entity->kind);
5653 warningf(&entity->base.source_position, "%s '%Y' is unused",
5654 what, entity->base.symbol);
5655 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5656 print_in_function();
5657 const char *what = get_entity_kind_name(entity->kind);
5658 warningf(&entity->base.source_position, "%s '%Y' is never read",
5659 what, entity->base.symbol);
5664 static void check_unused_variables(statement_t *const stmt, void *const env)
5668 switch (stmt->kind) {
5669 case STATEMENT_DECLARATION: {
5670 declaration_statement_t const *const decls = &stmt->declaration;
5671 warn_unused_entity(decls->declarations_begin,
5672 decls->declarations_end);
5677 warn_unused_entity(stmt->fors.scope.entities, NULL);
5686 * Check declarations of current_function for unused entities.
5688 static void check_declarations(void)
5690 if (warning.unused_parameter) {
5691 const scope_t *scope = ¤t_function->parameters;
5693 /* do not issue unused warnings for main */
5694 if (!is_sym_main(current_function->base.base.symbol)) {
5695 warn_unused_entity(scope->entities, NULL);
5698 if (warning.unused_variable) {
5699 walk_statements(current_function->statement, check_unused_variables,
5704 static int determine_truth(expression_t const* const cond)
5707 !is_constant_expression(cond) ? 0 :
5708 fold_constant(cond) != 0 ? 1 :
5712 static void check_reachable(statement_t *);
5713 static bool reaches_end;
5715 static bool expression_returns(expression_t const *const expr)
5717 switch (expr->kind) {
5719 expression_t const *const func = expr->call.function;
5720 if (func->kind == EXPR_REFERENCE) {
5721 entity_t *entity = func->reference.entity;
5722 if (entity->kind == ENTITY_FUNCTION
5723 && entity->declaration.modifiers & DM_NORETURN)
5727 if (!expression_returns(func))
5730 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5731 if (!expression_returns(arg->expression))
5738 case EXPR_REFERENCE:
5739 case EXPR_REFERENCE_ENUM_VALUE:
5741 case EXPR_CHARACTER_CONSTANT:
5742 case EXPR_WIDE_CHARACTER_CONSTANT:
5743 case EXPR_STRING_LITERAL:
5744 case EXPR_WIDE_STRING_LITERAL:
5745 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5746 case EXPR_LABEL_ADDRESS:
5747 case EXPR_CLASSIFY_TYPE:
5748 case EXPR_SIZEOF: // TODO handle obscure VLA case
5751 case EXPR_BUILTIN_SYMBOL:
5752 case EXPR_BUILTIN_CONSTANT_P:
5753 case EXPR_BUILTIN_PREFETCH:
5758 case EXPR_STATEMENT: {
5759 bool old_reaches_end = reaches_end;
5760 reaches_end = false;
5761 check_reachable(expr->statement.statement);
5762 bool returns = reaches_end;
5763 reaches_end = old_reaches_end;
5767 case EXPR_CONDITIONAL:
5768 // TODO handle constant expression
5770 if (!expression_returns(expr->conditional.condition))
5773 if (expr->conditional.true_expression != NULL
5774 && expression_returns(expr->conditional.true_expression))
5777 return expression_returns(expr->conditional.false_expression);
5780 return expression_returns(expr->select.compound);
5782 case EXPR_ARRAY_ACCESS:
5784 expression_returns(expr->array_access.array_ref) &&
5785 expression_returns(expr->array_access.index);
5788 return expression_returns(expr->va_starte.ap);
5791 return expression_returns(expr->va_arge.ap);
5793 EXPR_UNARY_CASES_MANDATORY
5794 return expression_returns(expr->unary.value);
5796 case EXPR_UNARY_THROW:
5800 // TODO handle constant lhs of && and ||
5802 expression_returns(expr->binary.left) &&
5803 expression_returns(expr->binary.right);
5809 panic("unhandled expression");
5812 static bool initializer_returns(initializer_t const *const init)
5814 switch (init->kind) {
5815 case INITIALIZER_VALUE:
5816 return expression_returns(init->value.value);
5818 case INITIALIZER_LIST: {
5819 initializer_t * const* i = init->list.initializers;
5820 initializer_t * const* const end = i + init->list.len;
5821 bool returns = true;
5822 for (; i != end; ++i) {
5823 if (!initializer_returns(*i))
5829 case INITIALIZER_STRING:
5830 case INITIALIZER_WIDE_STRING:
5831 case INITIALIZER_DESIGNATOR: // designators have no payload
5834 panic("unhandled initializer");
5837 static bool noreturn_candidate;
5839 static void check_reachable(statement_t *const stmt)
5841 if (stmt->base.reachable)
5843 if (stmt->kind != STATEMENT_DO_WHILE)
5844 stmt->base.reachable = true;
5846 statement_t *last = stmt;
5848 switch (stmt->kind) {
5849 case STATEMENT_INVALID:
5850 case STATEMENT_EMPTY:
5852 next = stmt->base.next;
5855 case STATEMENT_DECLARATION: {
5856 declaration_statement_t const *const decl = &stmt->declaration;
5857 entity_t const * ent = decl->declarations_begin;
5858 entity_t const *const last = decl->declarations_end;
5860 for (;; ent = ent->base.next) {
5861 if (ent->kind == ENTITY_VARIABLE &&
5862 ent->variable.initializer != NULL &&
5863 !initializer_returns(ent->variable.initializer)) {
5870 next = stmt->base.next;
5874 case STATEMENT_COMPOUND:
5875 next = stmt->compound.statements;
5877 next = stmt->base.next;
5880 case STATEMENT_RETURN: {
5881 expression_t const *const val = stmt->returns.value;
5882 if (val == NULL || expression_returns(val))
5883 noreturn_candidate = false;
5887 case STATEMENT_IF: {
5888 if_statement_t const *const ifs = &stmt->ifs;
5889 expression_t const *const cond = ifs->condition;
5891 if (!expression_returns(cond))
5894 int const val = determine_truth(cond);
5897 check_reachable(ifs->true_statement);
5902 if (ifs->false_statement != NULL) {
5903 check_reachable(ifs->false_statement);
5907 next = stmt->base.next;
5911 case STATEMENT_SWITCH: {
5912 switch_statement_t const *const switchs = &stmt->switchs;
5913 expression_t const *const expr = switchs->expression;
5915 if (!expression_returns(expr))
5918 if (is_constant_expression(expr)) {
5919 long const val = fold_constant(expr);
5920 case_label_statement_t * defaults = NULL;
5921 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5922 if (i->expression == NULL) {
5927 if (i->first_case <= val && val <= i->last_case) {
5928 check_reachable((statement_t*)i);
5933 if (defaults != NULL) {
5934 check_reachable((statement_t*)defaults);
5938 bool has_default = false;
5939 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5940 if (i->expression == NULL)
5943 check_reachable((statement_t*)i);
5950 next = stmt->base.next;
5954 case STATEMENT_EXPRESSION: {
5955 /* Check for noreturn function call */
5956 expression_t const *const expr = stmt->expression.expression;
5957 if (!expression_returns(expr))
5960 next = stmt->base.next;
5964 case STATEMENT_CONTINUE: {
5965 statement_t *parent = stmt;
5967 parent = parent->base.parent;
5968 if (parent == NULL) /* continue not within loop */
5972 switch (parent->kind) {
5973 case STATEMENT_WHILE: goto continue_while;
5974 case STATEMENT_DO_WHILE: goto continue_do_while;
5975 case STATEMENT_FOR: goto continue_for;
5982 case STATEMENT_BREAK: {
5983 statement_t *parent = stmt;
5985 parent = parent->base.parent;
5986 if (parent == NULL) /* break not within loop/switch */
5989 switch (parent->kind) {
5990 case STATEMENT_SWITCH:
5991 case STATEMENT_WHILE:
5992 case STATEMENT_DO_WHILE:
5995 next = parent->base.next;
5996 goto found_break_parent;
6005 case STATEMENT_GOTO:
6006 if (stmt->gotos.expression) {
6007 if (!expression_returns(stmt->gotos.expression))
6010 statement_t *parent = stmt->base.parent;
6011 if (parent == NULL) /* top level goto */
6015 next = stmt->gotos.label->statement;
6016 if (next == NULL) /* missing label */
6021 case STATEMENT_LABEL:
6022 next = stmt->label.statement;
6025 case STATEMENT_CASE_LABEL:
6026 next = stmt->case_label.statement;
6029 case STATEMENT_WHILE: {
6030 while_statement_t const *const whiles = &stmt->whiles;
6031 expression_t const *const cond = whiles->condition;
6033 if (!expression_returns(cond))
6036 int const val = determine_truth(cond);
6039 check_reachable(whiles->body);
6044 next = stmt->base.next;
6048 case STATEMENT_DO_WHILE:
6049 next = stmt->do_while.body;
6052 case STATEMENT_FOR: {
6053 for_statement_t *const fors = &stmt->fors;
6055 if (fors->condition_reachable)
6057 fors->condition_reachable = true;
6059 expression_t const *const cond = fors->condition;
6064 } else if (expression_returns(cond)) {
6065 val = determine_truth(cond);
6071 check_reachable(fors->body);
6076 next = stmt->base.next;
6080 case STATEMENT_MS_TRY: {
6081 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6082 check_reachable(ms_try->try_statement);
6083 next = ms_try->final_statement;
6087 case STATEMENT_LEAVE: {
6088 statement_t *parent = stmt;
6090 parent = parent->base.parent;
6091 if (parent == NULL) /* __leave not within __try */
6094 if (parent->kind == STATEMENT_MS_TRY) {
6096 next = parent->ms_try.final_statement;
6104 panic("invalid statement kind");
6107 while (next == NULL) {
6108 next = last->base.parent;
6110 noreturn_candidate = false;
6112 type_t *const type = current_function->base.type;
6113 assert(is_type_function(type));
6114 type_t *const ret = skip_typeref(type->function.return_type);
6115 if (warning.return_type &&
6116 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6117 is_type_valid(ret) &&
6118 !is_sym_main(current_function->base.base.symbol)) {
6119 warningf(&stmt->base.source_position,
6120 "control reaches end of non-void function");
6125 switch (next->kind) {
6126 case STATEMENT_INVALID:
6127 case STATEMENT_EMPTY:
6128 case STATEMENT_DECLARATION:
6129 case STATEMENT_EXPRESSION:
6131 case STATEMENT_RETURN:
6132 case STATEMENT_CONTINUE:
6133 case STATEMENT_BREAK:
6134 case STATEMENT_GOTO:
6135 case STATEMENT_LEAVE:
6136 panic("invalid control flow in function");
6138 case STATEMENT_COMPOUND:
6139 if (next->compound.stmt_expr) {
6145 case STATEMENT_SWITCH:
6146 case STATEMENT_LABEL:
6147 case STATEMENT_CASE_LABEL:
6149 next = next->base.next;
6152 case STATEMENT_WHILE: {
6154 if (next->base.reachable)
6156 next->base.reachable = true;
6158 while_statement_t const *const whiles = &next->whiles;
6159 expression_t const *const cond = whiles->condition;
6161 if (!expression_returns(cond))
6164 int const val = determine_truth(cond);
6167 check_reachable(whiles->body);
6173 next = next->base.next;
6177 case STATEMENT_DO_WHILE: {
6179 if (next->base.reachable)
6181 next->base.reachable = true;
6183 do_while_statement_t const *const dw = &next->do_while;
6184 expression_t const *const cond = dw->condition;
6186 if (!expression_returns(cond))
6189 int const val = determine_truth(cond);
6192 check_reachable(dw->body);
6198 next = next->base.next;
6202 case STATEMENT_FOR: {
6204 for_statement_t *const fors = &next->fors;
6206 fors->step_reachable = true;
6208 if (fors->condition_reachable)
6210 fors->condition_reachable = true;
6212 expression_t const *const cond = fors->condition;
6217 } else if (expression_returns(cond)) {
6218 val = determine_truth(cond);
6224 check_reachable(fors->body);
6230 next = next->base.next;
6234 case STATEMENT_MS_TRY:
6236 next = next->ms_try.final_statement;
6241 check_reachable(next);
6244 static void check_unreachable(statement_t* const stmt, void *const env)
6248 switch (stmt->kind) {
6249 case STATEMENT_DO_WHILE:
6250 if (!stmt->base.reachable) {
6251 expression_t const *const cond = stmt->do_while.condition;
6252 if (determine_truth(cond) >= 0) {
6253 warningf(&cond->base.source_position,
6254 "condition of do-while-loop is unreachable");
6259 case STATEMENT_FOR: {
6260 for_statement_t const* const fors = &stmt->fors;
6262 // if init and step are unreachable, cond is unreachable, too
6263 if (!stmt->base.reachable && !fors->step_reachable) {
6264 warningf(&stmt->base.source_position, "statement is unreachable");
6266 if (!stmt->base.reachable && fors->initialisation != NULL) {
6267 warningf(&fors->initialisation->base.source_position,
6268 "initialisation of for-statement is unreachable");
6271 if (!fors->condition_reachable && fors->condition != NULL) {
6272 warningf(&fors->condition->base.source_position,
6273 "condition of for-statement is unreachable");
6276 if (!fors->step_reachable && fors->step != NULL) {
6277 warningf(&fors->step->base.source_position,
6278 "step of for-statement is unreachable");
6284 case STATEMENT_COMPOUND:
6285 if (stmt->compound.statements != NULL)
6287 goto warn_unreachable;
6289 case STATEMENT_DECLARATION: {
6290 /* Only warn if there is at least one declarator with an initializer.
6291 * This typically occurs in switch statements. */
6292 declaration_statement_t const *const decl = &stmt->declaration;
6293 entity_t const * ent = decl->declarations_begin;
6294 entity_t const *const last = decl->declarations_end;
6296 for (;; ent = ent->base.next) {
6297 if (ent->kind == ENTITY_VARIABLE &&
6298 ent->variable.initializer != NULL) {
6299 goto warn_unreachable;
6309 if (!stmt->base.reachable)
6310 warningf(&stmt->base.source_position, "statement is unreachable");
6315 static void parse_external_declaration(void)
6317 /* function-definitions and declarations both start with declaration
6319 declaration_specifiers_t specifiers;
6320 memset(&specifiers, 0, sizeof(specifiers));
6322 add_anchor_token(';');
6323 parse_declaration_specifiers(&specifiers);
6324 rem_anchor_token(';');
6326 /* must be a declaration */
6327 if (token.type == ';') {
6328 parse_anonymous_declaration_rest(&specifiers);
6332 add_anchor_token(',');
6333 add_anchor_token('=');
6334 add_anchor_token(';');
6335 add_anchor_token('{');
6337 /* declarator is common to both function-definitions and declarations */
6338 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6340 rem_anchor_token('{');
6341 rem_anchor_token(';');
6342 rem_anchor_token('=');
6343 rem_anchor_token(',');
6345 /* must be a declaration */
6346 switch (token.type) {
6350 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6355 /* must be a function definition */
6356 parse_kr_declaration_list(ndeclaration);
6358 if (token.type != '{') {
6359 parse_error_expected("while parsing function definition", '{', NULL);
6360 eat_until_matching_token(';');
6364 assert(is_declaration(ndeclaration));
6365 type_t *type = skip_typeref(ndeclaration->declaration.type);
6367 if (!is_type_function(type)) {
6368 if (is_type_valid(type)) {
6369 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6370 type, ndeclaration->base.symbol);
6376 if (warning.aggregate_return &&
6377 is_type_compound(skip_typeref(type->function.return_type))) {
6378 warningf(HERE, "function '%Y' returns an aggregate",
6379 ndeclaration->base.symbol);
6381 if (warning.traditional && !type->function.unspecified_parameters) {
6382 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6383 ndeclaration->base.symbol);
6385 if (warning.old_style_definition && type->function.unspecified_parameters) {
6386 warningf(HERE, "old-style function definition '%Y'",
6387 ndeclaration->base.symbol);
6390 /* § 6.7.5.3:14 a function definition with () means no
6391 * parameters (and not unspecified parameters) */
6392 if (type->function.unspecified_parameters &&
6393 type->function.parameters == NULL &&
6394 !type->function.kr_style_parameters) {
6395 type_t *copy = duplicate_type(type);
6396 copy->function.unspecified_parameters = false;
6397 type = identify_new_type(copy);
6399 ndeclaration->declaration.type = type;
6402 entity_t *const entity = record_entity(ndeclaration, true);
6403 assert(entity->kind == ENTITY_FUNCTION);
6404 assert(ndeclaration->kind == ENTITY_FUNCTION);
6406 function_t *function = &entity->function;
6407 if (ndeclaration != entity) {
6408 function->parameters = ndeclaration->function.parameters;
6410 assert(is_declaration(entity));
6411 type = skip_typeref(entity->declaration.type);
6413 /* push function parameters and switch scope */
6414 size_t const top = environment_top();
6415 scope_t *old_scope = scope_push(&function->parameters);
6417 entity_t *parameter = function->parameters.entities;
6418 for (; parameter != NULL; parameter = parameter->base.next) {
6419 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6420 parameter->base.parent_scope = current_scope;
6422 assert(parameter->base.parent_scope == NULL
6423 || parameter->base.parent_scope == current_scope);
6424 parameter->base.parent_scope = current_scope;
6425 if (parameter->base.symbol == NULL) {
6426 errorf(¶meter->base.source_position, "parameter name omitted");
6429 environment_push(parameter);
6432 if (function->statement != NULL) {
6433 parser_error_multiple_definition(entity, HERE);
6436 /* parse function body */
6437 int label_stack_top = label_top();
6438 function_t *old_current_function = current_function;
6439 current_function = function;
6440 current_parent = NULL;
6443 goto_anchor = &goto_first;
6445 label_anchor = &label_first;
6447 statement_t *const body = parse_compound_statement(false);
6448 function->statement = body;
6451 check_declarations();
6452 if (warning.return_type ||
6453 warning.unreachable_code ||
6454 (warning.missing_noreturn
6455 && !(function->base.modifiers & DM_NORETURN))) {
6456 noreturn_candidate = true;
6457 check_reachable(body);
6458 if (warning.unreachable_code)
6459 walk_statements(body, check_unreachable, NULL);
6460 if (warning.missing_noreturn &&
6461 noreturn_candidate &&
6462 !(function->base.modifiers & DM_NORETURN)) {
6463 warningf(&body->base.source_position,
6464 "function '%#T' is candidate for attribute 'noreturn'",
6465 type, entity->base.symbol);
6469 assert(current_parent == NULL);
6470 assert(current_function == function);
6471 current_function = old_current_function;
6472 label_pop_to(label_stack_top);
6475 assert(current_scope == &function->parameters);
6476 scope_pop(old_scope);
6477 environment_pop_to(top);
6480 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6481 source_position_t *source_position,
6482 const symbol_t *symbol)
6484 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6486 type->bitfield.base_type = base_type;
6487 type->bitfield.size_expression = size;
6490 type_t *skipped_type = skip_typeref(base_type);
6491 if (!is_type_integer(skipped_type)) {
6492 errorf(HERE, "bitfield base type '%T' is not an integer type",
6496 bit_size = skipped_type->base.size * 8;
6499 if (is_constant_expression(size)) {
6500 long v = fold_constant(size);
6503 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6504 } else if (v == 0) {
6505 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6506 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6507 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6509 type->bitfield.bit_size = v;
6516 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6518 entity_t *iter = compound->members.entities;
6519 for (; iter != NULL; iter = iter->base.next) {
6520 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6523 if (iter->base.symbol == symbol) {
6525 } else if (iter->base.symbol == NULL) {
6526 type_t *type = skip_typeref(iter->declaration.type);
6527 if (is_type_compound(type)) {
6529 = find_compound_entry(type->compound.compound, symbol);
6540 static void parse_compound_declarators(compound_t *compound,
6541 const declaration_specifiers_t *specifiers)
6546 if (token.type == ':') {
6547 source_position_t source_position = *HERE;
6550 type_t *base_type = specifiers->type;
6551 expression_t *size = parse_constant_expression();
6553 type_t *type = make_bitfield_type(base_type, size,
6554 &source_position, sym_anonymous);
6556 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6557 entity->base.namespc = NAMESPACE_NORMAL;
6558 entity->base.source_position = source_position;
6559 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6560 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6561 entity->declaration.modifiers = specifiers->modifiers;
6562 entity->declaration.type = type;
6563 append_entity(&compound->members, entity);
6565 entity = parse_declarator(specifiers,
6566 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6567 if (entity->kind == ENTITY_TYPEDEF) {
6568 errorf(&entity->base.source_position,
6569 "typedef not allowed as compound member");
6571 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6573 /* make sure we don't define a symbol multiple times */
6574 symbol_t *symbol = entity->base.symbol;
6575 if (symbol != NULL) {
6576 entity_t *prev = find_compound_entry(compound, symbol);
6578 errorf(&entity->base.source_position,
6579 "multiple declarations of symbol '%Y' (declared %P)",
6580 symbol, &prev->base.source_position);
6584 if (token.type == ':') {
6585 source_position_t source_position = *HERE;
6587 expression_t *size = parse_constant_expression();
6589 type_t *type = entity->declaration.type;
6590 type_t *bitfield_type = make_bitfield_type(type, size,
6591 &source_position, entity->base.symbol);
6592 entity->declaration.type = bitfield_type;
6594 type_t *orig_type = entity->declaration.type;
6595 type_t *type = skip_typeref(orig_type);
6596 if (is_type_function(type)) {
6597 errorf(&entity->base.source_position,
6598 "compound member '%Y' must not have function type '%T'",
6599 entity->base.symbol, orig_type);
6600 } else if (is_type_incomplete(type)) {
6601 /* §6.7.2.1:16 flexible array member */
6602 if (is_type_array(type) &&
6603 token.type == ';' &&
6604 look_ahead(1)->type == '}') {
6605 compound->has_flexible_member = true;
6607 errorf(&entity->base.source_position,
6608 "compound member '%Y' has incomplete type '%T'",
6609 entity->base.symbol, orig_type);
6614 append_entity(&compound->members, entity);
6618 if (token.type != ',')
6622 expect(';', end_error);
6625 anonymous_entity = NULL;
6628 static void parse_compound_type_entries(compound_t *compound)
6631 add_anchor_token('}');
6633 while (token.type != '}') {
6634 if (token.type == T_EOF) {
6635 errorf(HERE, "EOF while parsing struct");
6638 declaration_specifiers_t specifiers;
6639 memset(&specifiers, 0, sizeof(specifiers));
6640 parse_declaration_specifiers(&specifiers);
6642 parse_compound_declarators(compound, &specifiers);
6644 rem_anchor_token('}');
6648 compound->complete = true;
6651 static type_t *parse_typename(void)
6653 declaration_specifiers_t specifiers;
6654 memset(&specifiers, 0, sizeof(specifiers));
6655 parse_declaration_specifiers(&specifiers);
6656 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6657 specifiers.thread_local) {
6658 /* TODO: improve error message, user does probably not know what a
6659 * storage class is...
6661 errorf(HERE, "typename may not have a storage class");
6664 type_t *result = parse_abstract_declarator(specifiers.type);
6672 typedef expression_t* (*parse_expression_function)(void);
6673 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6675 typedef struct expression_parser_function_t expression_parser_function_t;
6676 struct expression_parser_function_t {
6677 parse_expression_function parser;
6678 precedence_t infix_precedence;
6679 parse_expression_infix_function infix_parser;
6682 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6685 * Prints an error message if an expression was expected but not read
6687 static expression_t *expected_expression_error(void)
6689 /* skip the error message if the error token was read */
6690 if (token.type != T_ERROR) {
6691 errorf(HERE, "expected expression, got token %K", &token);
6695 return create_invalid_expression();
6699 * Parse a string constant.
6701 static expression_t *parse_string_const(void)
6704 if (token.type == T_STRING_LITERAL) {
6705 string_t res = token.v.string;
6707 while (token.type == T_STRING_LITERAL) {
6708 res = concat_strings(&res, &token.v.string);
6711 if (token.type != T_WIDE_STRING_LITERAL) {
6712 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6713 /* note: that we use type_char_ptr here, which is already the
6714 * automatic converted type. revert_automatic_type_conversion
6715 * will construct the array type */
6716 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6717 cnst->string.value = res;
6721 wres = concat_string_wide_string(&res, &token.v.wide_string);
6723 wres = token.v.wide_string;
6728 switch (token.type) {
6729 case T_WIDE_STRING_LITERAL:
6730 wres = concat_wide_strings(&wres, &token.v.wide_string);
6733 case T_STRING_LITERAL:
6734 wres = concat_wide_string_string(&wres, &token.v.string);
6738 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6739 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6740 cnst->wide_string.value = wres;
6749 * Parse a boolean constant.
6751 static expression_t *parse_bool_const(bool value)
6753 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6754 cnst->base.type = type_bool;
6755 cnst->conste.v.int_value = value;
6763 * Parse an integer constant.
6765 static expression_t *parse_int_const(void)
6767 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6768 cnst->base.type = token.datatype;
6769 cnst->conste.v.int_value = token.v.intvalue;
6777 * Parse a character constant.
6779 static expression_t *parse_character_constant(void)
6781 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6782 cnst->base.type = token.datatype;
6783 cnst->conste.v.character = token.v.string;
6785 if (cnst->conste.v.character.size != 1) {
6787 errorf(HERE, "more than 1 character in character constant");
6788 } else if (warning.multichar) {
6789 warningf(HERE, "multi-character character constant");
6798 * Parse a wide character constant.
6800 static expression_t *parse_wide_character_constant(void)
6802 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6803 cnst->base.type = token.datatype;
6804 cnst->conste.v.wide_character = token.v.wide_string;
6806 if (cnst->conste.v.wide_character.size != 1) {
6808 errorf(HERE, "more than 1 character in character constant");
6809 } else if (warning.multichar) {
6810 warningf(HERE, "multi-character character constant");
6819 * Parse a float constant.
6821 static expression_t *parse_float_const(void)
6823 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6824 cnst->base.type = token.datatype;
6825 cnst->conste.v.float_value = token.v.floatvalue;
6832 static entity_t *create_implicit_function(symbol_t *symbol,
6833 const source_position_t *source_position)
6835 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6836 ntype->function.return_type = type_int;
6837 ntype->function.unspecified_parameters = true;
6838 ntype->function.linkage = LINKAGE_C;
6839 type_t *type = identify_new_type(ntype);
6841 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6842 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6843 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6844 entity->declaration.type = type;
6845 entity->declaration.implicit = true;
6846 entity->base.symbol = symbol;
6847 entity->base.source_position = *source_position;
6849 bool strict_prototypes_old = warning.strict_prototypes;
6850 warning.strict_prototypes = false;
6851 record_entity(entity, false);
6852 warning.strict_prototypes = strict_prototypes_old;
6858 * Creates a return_type (func)(argument_type) function type if not
6861 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6862 type_t *argument_type2)
6864 function_parameter_t *parameter2
6865 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6866 memset(parameter2, 0, sizeof(parameter2[0]));
6867 parameter2->type = argument_type2;
6869 function_parameter_t *parameter1
6870 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6871 memset(parameter1, 0, sizeof(parameter1[0]));
6872 parameter1->type = argument_type1;
6873 parameter1->next = parameter2;
6875 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6876 type->function.return_type = return_type;
6877 type->function.parameters = parameter1;
6879 return identify_new_type(type);
6883 * Creates a return_type (func)(argument_type) function type if not
6886 * @param return_type the return type
6887 * @param argument_type the argument type
6889 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6891 function_parameter_t *parameter
6892 = obstack_alloc(type_obst, sizeof(parameter[0]));
6893 memset(parameter, 0, sizeof(parameter[0]));
6894 parameter->type = argument_type;
6896 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6897 type->function.return_type = return_type;
6898 type->function.parameters = parameter;
6900 return identify_new_type(type);
6903 static type_t *make_function_0_type(type_t *return_type)
6905 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6906 type->function.return_type = return_type;
6907 type->function.parameters = NULL;
6909 return identify_new_type(type);
6913 * Creates a function type for some function like builtins.
6915 * @param symbol the symbol describing the builtin
6917 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6919 switch (symbol->ID) {
6920 case T___builtin_alloca:
6921 return make_function_1_type(type_void_ptr, type_size_t);
6922 case T___builtin_huge_val:
6923 return make_function_0_type(type_double);
6924 case T___builtin_inf:
6925 return make_function_0_type(type_double);
6926 case T___builtin_inff:
6927 return make_function_0_type(type_float);
6928 case T___builtin_infl:
6929 return make_function_0_type(type_long_double);
6930 case T___builtin_nan:
6931 return make_function_1_type(type_double, type_char_ptr);
6932 case T___builtin_nanf:
6933 return make_function_1_type(type_float, type_char_ptr);
6934 case T___builtin_nanl:
6935 return make_function_1_type(type_long_double, type_char_ptr);
6936 case T___builtin_va_end:
6937 return make_function_1_type(type_void, type_valist);
6938 case T___builtin_expect:
6939 return make_function_2_type(type_long, type_long, type_long);
6941 internal_errorf(HERE, "not implemented builtin identifier found");
6946 * Performs automatic type cast as described in § 6.3.2.1.
6948 * @param orig_type the original type
6950 static type_t *automatic_type_conversion(type_t *orig_type)
6952 type_t *type = skip_typeref(orig_type);
6953 if (is_type_array(type)) {
6954 array_type_t *array_type = &type->array;
6955 type_t *element_type = array_type->element_type;
6956 unsigned qualifiers = array_type->base.qualifiers;
6958 return make_pointer_type(element_type, qualifiers);
6961 if (is_type_function(type)) {
6962 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6969 * reverts the automatic casts of array to pointer types and function
6970 * to function-pointer types as defined § 6.3.2.1
6972 type_t *revert_automatic_type_conversion(const expression_t *expression)
6974 switch (expression->kind) {
6975 case EXPR_REFERENCE: {
6976 entity_t *entity = expression->reference.entity;
6977 if (is_declaration(entity)) {
6978 return entity->declaration.type;
6979 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6980 return entity->enum_value.enum_type;
6982 panic("no declaration or enum in reference");
6987 entity_t *entity = expression->select.compound_entry;
6988 assert(is_declaration(entity));
6989 type_t *type = entity->declaration.type;
6990 return get_qualified_type(type,
6991 expression->base.type->base.qualifiers);
6994 case EXPR_UNARY_DEREFERENCE: {
6995 const expression_t *const value = expression->unary.value;
6996 type_t *const type = skip_typeref(value->base.type);
6997 if (!is_type_pointer(type))
6998 return type_error_type;
6999 return type->pointer.points_to;
7002 case EXPR_BUILTIN_SYMBOL:
7003 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
7005 case EXPR_ARRAY_ACCESS: {
7006 const expression_t *array_ref = expression->array_access.array_ref;
7007 type_t *type_left = skip_typeref(array_ref->base.type);
7008 if (!is_type_pointer(type_left))
7009 return type_error_type;
7010 return type_left->pointer.points_to;
7013 case EXPR_STRING_LITERAL: {
7014 size_t size = expression->string.value.size;
7015 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7018 case EXPR_WIDE_STRING_LITERAL: {
7019 size_t size = expression->wide_string.value.size;
7020 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7023 case EXPR_COMPOUND_LITERAL:
7024 return expression->compound_literal.type;
7027 return expression->base.type;
7031 static expression_t *parse_reference(void)
7033 symbol_t *const symbol = token.v.symbol;
7035 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7037 if (entity == NULL) {
7038 if (!strict_mode && look_ahead(1)->type == '(') {
7039 /* an implicitly declared function */
7040 if (warning.error_implicit_function_declaration) {
7041 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7042 } else if (warning.implicit_function_declaration) {
7043 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7046 entity = create_implicit_function(symbol, HERE);
7048 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7049 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7055 if (is_declaration(entity)) {
7056 orig_type = entity->declaration.type;
7057 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7058 orig_type = entity->enum_value.enum_type;
7059 } else if (entity->kind == ENTITY_TYPEDEF) {
7060 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7063 return create_invalid_expression();
7065 panic("expected declaration or enum value in reference");
7068 /* we always do the auto-type conversions; the & and sizeof parser contains
7069 * code to revert this! */
7070 type_t *type = automatic_type_conversion(orig_type);
7072 expression_kind_t kind = EXPR_REFERENCE;
7073 if (entity->kind == ENTITY_ENUM_VALUE)
7074 kind = EXPR_REFERENCE_ENUM_VALUE;
7076 expression_t *expression = allocate_expression_zero(kind);
7077 expression->reference.entity = entity;
7078 expression->base.type = type;
7080 /* this declaration is used */
7081 if (is_declaration(entity)) {
7082 entity->declaration.used = true;
7085 if (entity->base.parent_scope != file_scope
7086 && entity->base.parent_scope->depth < current_function->parameters.depth
7087 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7088 if (entity->kind == ENTITY_VARIABLE) {
7089 /* access of a variable from an outer function */
7090 entity->variable.address_taken = true;
7091 } else if (entity->kind == ENTITY_PARAMETER) {
7092 entity->parameter.address_taken = true;
7094 current_function->need_closure = true;
7097 /* check for deprecated functions */
7098 if (warning.deprecated_declarations
7099 && is_declaration(entity)
7100 && entity->declaration.modifiers & DM_DEPRECATED) {
7101 declaration_t *declaration = &entity->declaration;
7103 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7104 "function" : "variable";
7106 if (declaration->deprecated_string != NULL) {
7107 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7108 prefix, entity->base.symbol, &entity->base.source_position,
7109 declaration->deprecated_string);
7111 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7112 entity->base.symbol, &entity->base.source_position);
7116 if (warning.init_self && entity == current_init_decl && !in_type_prop
7117 && entity->kind == ENTITY_VARIABLE) {
7118 current_init_decl = NULL;
7119 warningf(HERE, "variable '%#T' is initialized by itself",
7120 entity->declaration.type, entity->base.symbol);
7127 static bool semantic_cast(expression_t *cast)
7129 expression_t *expression = cast->unary.value;
7130 type_t *orig_dest_type = cast->base.type;
7131 type_t *orig_type_right = expression->base.type;
7132 type_t const *dst_type = skip_typeref(orig_dest_type);
7133 type_t const *src_type = skip_typeref(orig_type_right);
7134 source_position_t const *pos = &cast->base.source_position;
7136 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7137 if (dst_type == type_void)
7140 /* only integer and pointer can be casted to pointer */
7141 if (is_type_pointer(dst_type) &&
7142 !is_type_pointer(src_type) &&
7143 !is_type_integer(src_type) &&
7144 is_type_valid(src_type)) {
7145 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7149 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7150 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7154 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7155 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7159 if (warning.cast_qual &&
7160 is_type_pointer(src_type) &&
7161 is_type_pointer(dst_type)) {
7162 type_t *src = skip_typeref(src_type->pointer.points_to);
7163 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7164 unsigned missing_qualifiers =
7165 src->base.qualifiers & ~dst->base.qualifiers;
7166 if (missing_qualifiers != 0) {
7168 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7169 missing_qualifiers, orig_type_right);
7175 static expression_t *parse_compound_literal(type_t *type)
7177 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7179 parse_initializer_env_t env;
7182 env.must_be_constant = false;
7183 initializer_t *initializer = parse_initializer(&env);
7186 expression->compound_literal.initializer = initializer;
7187 expression->compound_literal.type = type;
7188 expression->base.type = automatic_type_conversion(type);
7194 * Parse a cast expression.
7196 static expression_t *parse_cast(void)
7198 add_anchor_token(')');
7200 source_position_t source_position = token.source_position;
7202 type_t *type = parse_typename();
7204 rem_anchor_token(')');
7205 expect(')', end_error);
7207 if (token.type == '{') {
7208 return parse_compound_literal(type);
7211 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7212 cast->base.source_position = source_position;
7214 expression_t *value = parse_sub_expression(PREC_CAST);
7215 cast->base.type = type;
7216 cast->unary.value = value;
7218 if (! semantic_cast(cast)) {
7219 /* TODO: record the error in the AST. else it is impossible to detect it */
7224 return create_invalid_expression();
7228 * Parse a statement expression.
7230 static expression_t *parse_statement_expression(void)
7232 add_anchor_token(')');
7234 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7236 statement_t *statement = parse_compound_statement(true);
7237 statement->compound.stmt_expr = true;
7238 expression->statement.statement = statement;
7240 /* find last statement and use its type */
7241 type_t *type = type_void;
7242 const statement_t *stmt = statement->compound.statements;
7244 while (stmt->base.next != NULL)
7245 stmt = stmt->base.next;
7247 if (stmt->kind == STATEMENT_EXPRESSION) {
7248 type = stmt->expression.expression->base.type;
7250 } else if (warning.other) {
7251 warningf(&expression->base.source_position, "empty statement expression ({})");
7253 expression->base.type = type;
7255 rem_anchor_token(')');
7256 expect(')', end_error);
7263 * Parse a parenthesized expression.
7265 static expression_t *parse_parenthesized_expression(void)
7269 switch (token.type) {
7271 /* gcc extension: a statement expression */
7272 return parse_statement_expression();
7276 return parse_cast();
7278 if (is_typedef_symbol(token.v.symbol)) {
7279 return parse_cast();
7283 add_anchor_token(')');
7284 expression_t *result = parse_expression();
7285 result->base.parenthesized = true;
7286 rem_anchor_token(')');
7287 expect(')', end_error);
7293 static expression_t *parse_function_keyword(void)
7297 if (current_function == NULL) {
7298 errorf(HERE, "'__func__' used outside of a function");
7301 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7302 expression->base.type = type_char_ptr;
7303 expression->funcname.kind = FUNCNAME_FUNCTION;
7310 static expression_t *parse_pretty_function_keyword(void)
7312 if (current_function == NULL) {
7313 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7316 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7317 expression->base.type = type_char_ptr;
7318 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7320 eat(T___PRETTY_FUNCTION__);
7325 static expression_t *parse_funcsig_keyword(void)
7327 if (current_function == NULL) {
7328 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7331 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7332 expression->base.type = type_char_ptr;
7333 expression->funcname.kind = FUNCNAME_FUNCSIG;
7340 static expression_t *parse_funcdname_keyword(void)
7342 if (current_function == NULL) {
7343 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7346 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7347 expression->base.type = type_char_ptr;
7348 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7350 eat(T___FUNCDNAME__);
7355 static designator_t *parse_designator(void)
7357 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7358 result->source_position = *HERE;
7360 if (token.type != T_IDENTIFIER) {
7361 parse_error_expected("while parsing member designator",
7362 T_IDENTIFIER, NULL);
7365 result->symbol = token.v.symbol;
7368 designator_t *last_designator = result;
7370 if (token.type == '.') {
7372 if (token.type != T_IDENTIFIER) {
7373 parse_error_expected("while parsing member designator",
7374 T_IDENTIFIER, NULL);
7377 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7378 designator->source_position = *HERE;
7379 designator->symbol = token.v.symbol;
7382 last_designator->next = designator;
7383 last_designator = designator;
7386 if (token.type == '[') {
7388 add_anchor_token(']');
7389 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7390 designator->source_position = *HERE;
7391 designator->array_index = parse_expression();
7392 rem_anchor_token(']');
7393 expect(']', end_error);
7394 if (designator->array_index == NULL) {
7398 last_designator->next = designator;
7399 last_designator = designator;
7411 * Parse the __builtin_offsetof() expression.
7413 static expression_t *parse_offsetof(void)
7415 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7416 expression->base.type = type_size_t;
7418 eat(T___builtin_offsetof);
7420 expect('(', end_error);
7421 add_anchor_token(',');
7422 type_t *type = parse_typename();
7423 rem_anchor_token(',');
7424 expect(',', end_error);
7425 add_anchor_token(')');
7426 designator_t *designator = parse_designator();
7427 rem_anchor_token(')');
7428 expect(')', end_error);
7430 expression->offsetofe.type = type;
7431 expression->offsetofe.designator = designator;
7434 memset(&path, 0, sizeof(path));
7435 path.top_type = type;
7436 path.path = NEW_ARR_F(type_path_entry_t, 0);
7438 descend_into_subtype(&path);
7440 if (!walk_designator(&path, designator, true)) {
7441 return create_invalid_expression();
7444 DEL_ARR_F(path.path);
7448 return create_invalid_expression();
7452 * Parses a _builtin_va_start() expression.
7454 static expression_t *parse_va_start(void)
7456 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7458 eat(T___builtin_va_start);
7460 expect('(', end_error);
7461 add_anchor_token(',');
7462 expression->va_starte.ap = parse_assignment_expression();
7463 rem_anchor_token(',');
7464 expect(',', end_error);
7465 expression_t *const expr = parse_assignment_expression();
7466 if (expr->kind == EXPR_REFERENCE) {
7467 entity_t *const entity = expr->reference.entity;
7468 if (entity->base.parent_scope != ¤t_function->parameters
7469 || entity->base.next != NULL
7470 || entity->kind != ENTITY_PARAMETER) {
7471 errorf(&expr->base.source_position,
7472 "second argument of 'va_start' must be last parameter of the current function");
7474 expression->va_starte.parameter = &entity->variable;
7476 expect(')', end_error);
7479 expect(')', end_error);
7481 return create_invalid_expression();
7485 * Parses a _builtin_va_arg() expression.
7487 static expression_t *parse_va_arg(void)
7489 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7491 eat(T___builtin_va_arg);
7493 expect('(', end_error);
7494 expression->va_arge.ap = parse_assignment_expression();
7495 expect(',', end_error);
7496 expression->base.type = parse_typename();
7497 expect(')', end_error);
7501 return create_invalid_expression();
7504 static expression_t *parse_builtin_symbol(void)
7506 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7508 symbol_t *symbol = token.v.symbol;
7510 expression->builtin_symbol.symbol = symbol;
7513 type_t *type = get_builtin_symbol_type(symbol);
7514 type = automatic_type_conversion(type);
7516 expression->base.type = type;
7521 * Parses a __builtin_constant() expression.
7523 static expression_t *parse_builtin_constant(void)
7525 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7527 eat(T___builtin_constant_p);
7529 expect('(', end_error);
7530 add_anchor_token(')');
7531 expression->builtin_constant.value = parse_assignment_expression();
7532 rem_anchor_token(')');
7533 expect(')', end_error);
7534 expression->base.type = type_int;
7538 return create_invalid_expression();
7542 * Parses a __builtin_prefetch() expression.
7544 static expression_t *parse_builtin_prefetch(void)
7546 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7548 eat(T___builtin_prefetch);
7550 expect('(', end_error);
7551 add_anchor_token(')');
7552 expression->builtin_prefetch.adr = parse_assignment_expression();
7553 if (token.type == ',') {
7555 expression->builtin_prefetch.rw = parse_assignment_expression();
7557 if (token.type == ',') {
7559 expression->builtin_prefetch.locality = parse_assignment_expression();
7561 rem_anchor_token(')');
7562 expect(')', end_error);
7563 expression->base.type = type_void;
7567 return create_invalid_expression();
7571 * Parses a __builtin_is_*() compare expression.
7573 static expression_t *parse_compare_builtin(void)
7575 expression_t *expression;
7577 switch (token.type) {
7578 case T___builtin_isgreater:
7579 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7581 case T___builtin_isgreaterequal:
7582 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7584 case T___builtin_isless:
7585 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7587 case T___builtin_islessequal:
7588 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7590 case T___builtin_islessgreater:
7591 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7593 case T___builtin_isunordered:
7594 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7597 internal_errorf(HERE, "invalid compare builtin found");
7599 expression->base.source_position = *HERE;
7602 expect('(', end_error);
7603 expression->binary.left = parse_assignment_expression();
7604 expect(',', end_error);
7605 expression->binary.right = parse_assignment_expression();
7606 expect(')', end_error);
7608 type_t *const orig_type_left = expression->binary.left->base.type;
7609 type_t *const orig_type_right = expression->binary.right->base.type;
7611 type_t *const type_left = skip_typeref(orig_type_left);
7612 type_t *const type_right = skip_typeref(orig_type_right);
7613 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7614 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7615 type_error_incompatible("invalid operands in comparison",
7616 &expression->base.source_position, orig_type_left, orig_type_right);
7619 semantic_comparison(&expression->binary);
7624 return create_invalid_expression();
7629 * Parses a __builtin_expect(, end_error) expression.
7631 static expression_t *parse_builtin_expect(void, end_error)
7633 expression_t *expression
7634 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7636 eat(T___builtin_expect);
7638 expect('(', end_error);
7639 expression->binary.left = parse_assignment_expression();
7640 expect(',', end_error);
7641 expression->binary.right = parse_constant_expression();
7642 expect(')', end_error);
7644 expression->base.type = expression->binary.left->base.type;
7648 return create_invalid_expression();
7653 * Parses a MS assume() expression.
7655 static expression_t *parse_assume(void)
7657 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7661 expect('(', end_error);
7662 add_anchor_token(')');
7663 expression->unary.value = parse_assignment_expression();
7664 rem_anchor_token(')');
7665 expect(')', end_error);
7667 expression->base.type = type_void;
7670 return create_invalid_expression();
7674 * Return the declaration for a given label symbol or create a new one.
7676 * @param symbol the symbol of the label
7678 static label_t *get_label(symbol_t *symbol)
7681 assert(current_function != NULL);
7683 label = get_entity(symbol, NAMESPACE_LABEL);
7684 /* if we found a local label, we already created the declaration */
7685 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7686 if (label->base.parent_scope != current_scope) {
7687 assert(label->base.parent_scope->depth < current_scope->depth);
7688 current_function->goto_to_outer = true;
7690 return &label->label;
7693 label = get_entity(symbol, NAMESPACE_LABEL);
7694 /* if we found a label in the same function, then we already created the
7697 && label->base.parent_scope == ¤t_function->parameters) {
7698 return &label->label;
7701 /* otherwise we need to create a new one */
7702 label = allocate_entity_zero(ENTITY_LABEL);
7703 label->base.namespc = NAMESPACE_LABEL;
7704 label->base.symbol = symbol;
7708 return &label->label;
7712 * Parses a GNU && label address expression.
7714 static expression_t *parse_label_address(void)
7716 source_position_t source_position = token.source_position;
7718 if (token.type != T_IDENTIFIER) {
7719 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7722 symbol_t *symbol = token.v.symbol;
7725 label_t *label = get_label(symbol);
7727 label->address_taken = true;
7729 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7730 expression->base.source_position = source_position;
7732 /* label address is threaten as a void pointer */
7733 expression->base.type = type_void_ptr;
7734 expression->label_address.label = label;
7737 return create_invalid_expression();
7741 * Parse a microsoft __noop expression.
7743 static expression_t *parse_noop_expression(void)
7745 /* the result is a (int)0 */
7746 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7747 cnst->base.type = type_int;
7748 cnst->conste.v.int_value = 0;
7749 cnst->conste.is_ms_noop = true;
7753 if (token.type == '(') {
7754 /* parse arguments */
7756 add_anchor_token(')');
7757 add_anchor_token(',');
7759 if (token.type != ')') {
7761 (void)parse_assignment_expression();
7762 if (token.type != ',')
7768 rem_anchor_token(',');
7769 rem_anchor_token(')');
7770 expect(')', end_error);
7777 * Parses a primary expression.
7779 static expression_t *parse_primary_expression(void)
7781 switch (token.type) {
7782 case T_false: return parse_bool_const(false);
7783 case T_true: return parse_bool_const(true);
7784 case T_INTEGER: return parse_int_const();
7785 case T_CHARACTER_CONSTANT: return parse_character_constant();
7786 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7787 case T_FLOATINGPOINT: return parse_float_const();
7788 case T_STRING_LITERAL:
7789 case T_WIDE_STRING_LITERAL: return parse_string_const();
7790 case T_IDENTIFIER: return parse_reference();
7791 case T___FUNCTION__:
7792 case T___func__: return parse_function_keyword();
7793 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7794 case T___FUNCSIG__: return parse_funcsig_keyword();
7795 case T___FUNCDNAME__: return parse_funcdname_keyword();
7796 case T___builtin_offsetof: return parse_offsetof();
7797 case T___builtin_va_start: return parse_va_start();
7798 case T___builtin_va_arg: return parse_va_arg();
7799 case T___builtin_expect:
7800 case T___builtin_alloca:
7801 case T___builtin_inf:
7802 case T___builtin_inff:
7803 case T___builtin_infl:
7804 case T___builtin_nan:
7805 case T___builtin_nanf:
7806 case T___builtin_nanl:
7807 case T___builtin_huge_val:
7808 case T___builtin_va_end: return parse_builtin_symbol();
7809 case T___builtin_isgreater:
7810 case T___builtin_isgreaterequal:
7811 case T___builtin_isless:
7812 case T___builtin_islessequal:
7813 case T___builtin_islessgreater:
7814 case T___builtin_isunordered: return parse_compare_builtin();
7815 case T___builtin_constant_p: return parse_builtin_constant();
7816 case T___builtin_prefetch: return parse_builtin_prefetch();
7817 case T__assume: return parse_assume();
7820 return parse_label_address();
7823 case '(': return parse_parenthesized_expression();
7824 case T___noop: return parse_noop_expression();
7827 errorf(HERE, "unexpected token %K, expected an expression", &token);
7828 return create_invalid_expression();
7832 * Check if the expression has the character type and issue a warning then.
7834 static void check_for_char_index_type(const expression_t *expression)
7836 type_t *const type = expression->base.type;
7837 const type_t *const base_type = skip_typeref(type);
7839 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7840 warning.char_subscripts) {
7841 warningf(&expression->base.source_position,
7842 "array subscript has type '%T'", type);
7846 static expression_t *parse_array_expression(expression_t *left)
7848 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7851 add_anchor_token(']');
7853 expression_t *inside = parse_expression();
7855 type_t *const orig_type_left = left->base.type;
7856 type_t *const orig_type_inside = inside->base.type;
7858 type_t *const type_left = skip_typeref(orig_type_left);
7859 type_t *const type_inside = skip_typeref(orig_type_inside);
7861 type_t *return_type;
7862 array_access_expression_t *array_access = &expression->array_access;
7863 if (is_type_pointer(type_left)) {
7864 return_type = type_left->pointer.points_to;
7865 array_access->array_ref = left;
7866 array_access->index = inside;
7867 check_for_char_index_type(inside);
7868 } else if (is_type_pointer(type_inside)) {
7869 return_type = type_inside->pointer.points_to;
7870 array_access->array_ref = inside;
7871 array_access->index = left;
7872 array_access->flipped = true;
7873 check_for_char_index_type(left);
7875 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7877 "array access on object with non-pointer types '%T', '%T'",
7878 orig_type_left, orig_type_inside);
7880 return_type = type_error_type;
7881 array_access->array_ref = left;
7882 array_access->index = inside;
7885 expression->base.type = automatic_type_conversion(return_type);
7887 rem_anchor_token(']');
7888 expect(']', end_error);
7893 static expression_t *parse_typeprop(expression_kind_t const kind)
7895 expression_t *tp_expression = allocate_expression_zero(kind);
7896 tp_expression->base.type = type_size_t;
7898 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7900 /* we only refer to a type property, mark this case */
7901 bool old = in_type_prop;
7902 in_type_prop = true;
7905 expression_t *expression;
7906 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7908 add_anchor_token(')');
7909 orig_type = parse_typename();
7910 rem_anchor_token(')');
7911 expect(')', end_error);
7913 if (token.type == '{') {
7914 /* It was not sizeof(type) after all. It is sizeof of an expression
7915 * starting with a compound literal */
7916 expression = parse_compound_literal(orig_type);
7917 goto typeprop_expression;
7920 expression = parse_sub_expression(PREC_UNARY);
7922 typeprop_expression:
7923 tp_expression->typeprop.tp_expression = expression;
7925 orig_type = revert_automatic_type_conversion(expression);
7926 expression->base.type = orig_type;
7929 tp_expression->typeprop.type = orig_type;
7930 type_t const* const type = skip_typeref(orig_type);
7931 char const* const wrong_type =
7932 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7933 is_type_incomplete(type) ? "incomplete" :
7934 type->kind == TYPE_FUNCTION ? "function designator" :
7935 type->kind == TYPE_BITFIELD ? "bitfield" :
7937 if (wrong_type != NULL) {
7938 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7939 errorf(&tp_expression->base.source_position,
7940 "operand of %s expression must not be of %s type '%T'",
7941 what, wrong_type, orig_type);
7946 return tp_expression;
7949 static expression_t *parse_sizeof(void)
7951 return parse_typeprop(EXPR_SIZEOF);
7954 static expression_t *parse_alignof(void)
7956 return parse_typeprop(EXPR_ALIGNOF);
7959 static expression_t *parse_select_expression(expression_t *compound)
7961 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7962 select->select.compound = compound;
7964 assert(token.type == '.' || token.type == T_MINUSGREATER);
7965 bool is_pointer = (token.type == T_MINUSGREATER);
7968 if (token.type != T_IDENTIFIER) {
7969 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7972 symbol_t *symbol = token.v.symbol;
7975 type_t *const orig_type = compound->base.type;
7976 type_t *const type = skip_typeref(orig_type);
7979 bool saw_error = false;
7980 if (is_type_pointer(type)) {
7983 "request for member '%Y' in something not a struct or union, but '%T'",
7987 type_left = skip_typeref(type->pointer.points_to);
7989 if (is_pointer && is_type_valid(type)) {
7990 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7997 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7998 type_left->kind == TYPE_COMPOUND_UNION) {
7999 compound_t *compound = type_left->compound.compound;
8001 if (!compound->complete) {
8002 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
8004 goto create_error_entry;
8007 entry = find_compound_entry(compound, symbol);
8008 if (entry == NULL) {
8009 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
8010 goto create_error_entry;
8013 if (is_type_valid(type_left) && !saw_error) {
8015 "request for member '%Y' in something not a struct or union, but '%T'",
8019 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8022 assert(is_declaration(entry));
8023 select->select.compound_entry = entry;
8025 type_t *entry_type = entry->declaration.type;
8027 = get_qualified_type(entry_type, type_left->base.qualifiers);
8029 /* we always do the auto-type conversions; the & and sizeof parser contains
8030 * code to revert this! */
8031 select->base.type = automatic_type_conversion(res_type);
8033 type_t *skipped = skip_typeref(res_type);
8034 if (skipped->kind == TYPE_BITFIELD) {
8035 select->base.type = skipped->bitfield.base_type;
8041 static void check_call_argument(const function_parameter_t *parameter,
8042 call_argument_t *argument, unsigned pos)
8044 type_t *expected_type = parameter->type;
8045 type_t *expected_type_skip = skip_typeref(expected_type);
8046 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8047 expression_t *arg_expr = argument->expression;
8048 type_t *arg_type = skip_typeref(arg_expr->base.type);
8050 /* handle transparent union gnu extension */
8051 if (is_type_union(expected_type_skip)
8052 && (expected_type_skip->base.modifiers
8053 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8054 compound_t *union_decl = expected_type_skip->compound.compound;
8055 type_t *best_type = NULL;
8056 entity_t *entry = union_decl->members.entities;
8057 for ( ; entry != NULL; entry = entry->base.next) {
8058 assert(is_declaration(entry));
8059 type_t *decl_type = entry->declaration.type;
8060 error = semantic_assign(decl_type, arg_expr);
8061 if (error == ASSIGN_ERROR_INCOMPATIBLE
8062 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8065 if (error == ASSIGN_SUCCESS) {
8066 best_type = decl_type;
8067 } else if (best_type == NULL) {
8068 best_type = decl_type;
8072 if (best_type != NULL) {
8073 expected_type = best_type;
8077 error = semantic_assign(expected_type, arg_expr);
8078 argument->expression = create_implicit_cast(argument->expression,
8081 if (error != ASSIGN_SUCCESS) {
8082 /* report exact scope in error messages (like "in argument 3") */
8084 snprintf(buf, sizeof(buf), "call argument %u", pos);
8085 report_assign_error(error, expected_type, arg_expr, buf,
8086 &arg_expr->base.source_position);
8087 } else if (warning.traditional || warning.conversion) {
8088 type_t *const promoted_type = get_default_promoted_type(arg_type);
8089 if (!types_compatible(expected_type_skip, promoted_type) &&
8090 !types_compatible(expected_type_skip, type_void_ptr) &&
8091 !types_compatible(type_void_ptr, promoted_type)) {
8092 /* Deliberately show the skipped types in this warning */
8093 warningf(&arg_expr->base.source_position,
8094 "passing call argument %u as '%T' rather than '%T' due to prototype",
8095 pos, expected_type_skip, promoted_type);
8101 * Parse a call expression, ie. expression '( ... )'.
8103 * @param expression the function address
8105 static expression_t *parse_call_expression(expression_t *expression)
8107 expression_t *result = allocate_expression_zero(EXPR_CALL);
8108 call_expression_t *call = &result->call;
8109 call->function = expression;
8111 type_t *const orig_type = expression->base.type;
8112 type_t *const type = skip_typeref(orig_type);
8114 function_type_t *function_type = NULL;
8115 if (is_type_pointer(type)) {
8116 type_t *const to_type = skip_typeref(type->pointer.points_to);
8118 if (is_type_function(to_type)) {
8119 function_type = &to_type->function;
8120 call->base.type = function_type->return_type;
8124 if (function_type == NULL && is_type_valid(type)) {
8125 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8128 /* parse arguments */
8130 add_anchor_token(')');
8131 add_anchor_token(',');
8133 if (token.type != ')') {
8134 call_argument_t *last_argument = NULL;
8137 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8139 argument->expression = parse_assignment_expression();
8140 if (last_argument == NULL) {
8141 call->arguments = argument;
8143 last_argument->next = argument;
8145 last_argument = argument;
8147 if (token.type != ',')
8152 rem_anchor_token(',');
8153 rem_anchor_token(')');
8154 expect(')', end_error);
8156 if (function_type == NULL)
8159 function_parameter_t *parameter = function_type->parameters;
8160 call_argument_t *argument = call->arguments;
8161 if (!function_type->unspecified_parameters) {
8162 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8163 parameter = parameter->next, argument = argument->next) {
8164 check_call_argument(parameter, argument, ++pos);
8167 if (parameter != NULL) {
8168 errorf(HERE, "too few arguments to function '%E'", expression);
8169 } else if (argument != NULL && !function_type->variadic) {
8170 errorf(HERE, "too many arguments to function '%E'", expression);
8174 /* do default promotion */
8175 for (; argument != NULL; argument = argument->next) {
8176 type_t *type = argument->expression->base.type;
8178 type = get_default_promoted_type(type);
8180 argument->expression
8181 = create_implicit_cast(argument->expression, type);
8184 check_format(&result->call);
8186 if (warning.aggregate_return &&
8187 is_type_compound(skip_typeref(function_type->return_type))) {
8188 warningf(&result->base.source_position,
8189 "function call has aggregate value");
8196 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8198 static bool same_compound_type(const type_t *type1, const type_t *type2)
8201 is_type_compound(type1) &&
8202 type1->kind == type2->kind &&
8203 type1->compound.compound == type2->compound.compound;
8206 static expression_t const *get_reference_address(expression_t const *expr)
8208 bool regular_take_address = true;
8210 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8211 expr = expr->unary.value;
8213 regular_take_address = false;
8216 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8219 expr = expr->unary.value;
8222 if (expr->kind != EXPR_REFERENCE)
8225 /* special case for functions which are automatically converted to a
8226 * pointer to function without an extra TAKE_ADDRESS operation */
8227 if (!regular_take_address &&
8228 expr->reference.entity->kind != ENTITY_FUNCTION) {
8235 static void warn_reference_address_as_bool(expression_t const* expr)
8237 if (!warning.address)
8240 expr = get_reference_address(expr);
8242 warningf(&expr->base.source_position,
8243 "the address of '%Y' will always evaluate as 'true'",
8244 expr->reference.entity->base.symbol);
8248 static void warn_assignment_in_condition(const expression_t *const expr)
8250 if (!warning.parentheses)
8252 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8254 if (expr->base.parenthesized)
8256 warningf(&expr->base.source_position,
8257 "suggest parentheses around assignment used as truth value");
8260 static void semantic_condition(expression_t const *const expr,
8261 char const *const context)
8263 type_t *const type = skip_typeref(expr->base.type);
8264 if (is_type_scalar(type)) {
8265 warn_reference_address_as_bool(expr);
8266 warn_assignment_in_condition(expr);
8267 } else if (is_type_valid(type)) {
8268 errorf(&expr->base.source_position,
8269 "%s must have scalar type", context);
8274 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8276 * @param expression the conditional expression
8278 static expression_t *parse_conditional_expression(expression_t *expression)
8280 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8282 conditional_expression_t *conditional = &result->conditional;
8283 conditional->condition = expression;
8286 add_anchor_token(':');
8288 /* §6.5.15:2 The first operand shall have scalar type. */
8289 semantic_condition(expression, "condition of conditional operator");
8291 expression_t *true_expression = expression;
8292 bool gnu_cond = false;
8293 if (GNU_MODE && token.type == ':') {
8296 true_expression = parse_expression();
8298 rem_anchor_token(':');
8299 expect(':', end_error);
8301 expression_t *false_expression =
8302 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8304 type_t *const orig_true_type = true_expression->base.type;
8305 type_t *const orig_false_type = false_expression->base.type;
8306 type_t *const true_type = skip_typeref(orig_true_type);
8307 type_t *const false_type = skip_typeref(orig_false_type);
8310 type_t *result_type;
8311 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8312 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8313 /* ISO/IEC 14882:1998(E) §5.16:2 */
8314 if (true_expression->kind == EXPR_UNARY_THROW) {
8315 result_type = false_type;
8316 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8317 result_type = true_type;
8319 if (warning.other && (
8320 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8321 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8323 warningf(&conditional->base.source_position,
8324 "ISO C forbids conditional expression with only one void side");
8326 result_type = type_void;
8328 } else if (is_type_arithmetic(true_type)
8329 && is_type_arithmetic(false_type)) {
8330 result_type = semantic_arithmetic(true_type, false_type);
8332 true_expression = create_implicit_cast(true_expression, result_type);
8333 false_expression = create_implicit_cast(false_expression, result_type);
8335 conditional->true_expression = true_expression;
8336 conditional->false_expression = false_expression;
8337 conditional->base.type = result_type;
8338 } else if (same_compound_type(true_type, false_type)) {
8339 /* just take 1 of the 2 types */
8340 result_type = true_type;
8341 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8342 type_t *pointer_type;
8344 expression_t *other_expression;
8345 if (is_type_pointer(true_type) &&
8346 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8347 pointer_type = true_type;
8348 other_type = false_type;
8349 other_expression = false_expression;
8351 pointer_type = false_type;
8352 other_type = true_type;
8353 other_expression = true_expression;
8356 if (is_null_pointer_constant(other_expression)) {
8357 result_type = pointer_type;
8358 } else if (is_type_pointer(other_type)) {
8359 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8360 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8363 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8364 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8366 } else if (types_compatible(get_unqualified_type(to1),
8367 get_unqualified_type(to2))) {
8370 if (warning.other) {
8371 warningf(&conditional->base.source_position,
8372 "pointer types '%T' and '%T' in conditional expression are incompatible",
8373 true_type, false_type);
8378 type_t *const type =
8379 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8380 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8381 } else if (is_type_integer(other_type)) {
8382 if (warning.other) {
8383 warningf(&conditional->base.source_position,
8384 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8386 result_type = pointer_type;
8388 if (is_type_valid(other_type)) {
8389 type_error_incompatible("while parsing conditional",
8390 &expression->base.source_position, true_type, false_type);
8392 result_type = type_error_type;
8395 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8396 type_error_incompatible("while parsing conditional",
8397 &conditional->base.source_position, true_type,
8400 result_type = type_error_type;
8403 conditional->true_expression
8404 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8405 conditional->false_expression
8406 = create_implicit_cast(false_expression, result_type);
8407 conditional->base.type = result_type;
8412 * Parse an extension expression.
8414 static expression_t *parse_extension(void)
8416 eat(T___extension__);
8418 bool old_gcc_extension = in_gcc_extension;
8419 in_gcc_extension = true;
8420 expression_t *expression = parse_sub_expression(PREC_UNARY);
8421 in_gcc_extension = old_gcc_extension;
8426 * Parse a __builtin_classify_type() expression.
8428 static expression_t *parse_builtin_classify_type(void)
8430 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8431 result->base.type = type_int;
8433 eat(T___builtin_classify_type);
8435 expect('(', end_error);
8436 add_anchor_token(')');
8437 expression_t *expression = parse_expression();
8438 rem_anchor_token(')');
8439 expect(')', end_error);
8440 result->classify_type.type_expression = expression;
8444 return create_invalid_expression();
8448 * Parse a delete expression
8449 * ISO/IEC 14882:1998(E) §5.3.5
8451 static expression_t *parse_delete(void)
8453 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8454 result->base.type = type_void;
8458 if (token.type == '[') {
8460 result->kind = EXPR_UNARY_DELETE_ARRAY;
8461 expect(']', end_error);
8465 expression_t *const value = parse_sub_expression(PREC_CAST);
8466 result->unary.value = value;
8468 type_t *const type = skip_typeref(value->base.type);
8469 if (!is_type_pointer(type)) {
8470 if (is_type_valid(type)) {
8471 errorf(&value->base.source_position,
8472 "operand of delete must have pointer type");
8474 } else if (warning.other &&
8475 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8476 warningf(&value->base.source_position,
8477 "deleting 'void*' is undefined");
8484 * Parse a throw expression
8485 * ISO/IEC 14882:1998(E) §15:1
8487 static expression_t *parse_throw(void)
8489 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8490 result->base.type = type_void;
8494 expression_t *value = NULL;
8495 switch (token.type) {
8497 value = parse_assignment_expression();
8498 /* ISO/IEC 14882:1998(E) §15.1:3 */
8499 type_t *const orig_type = value->base.type;
8500 type_t *const type = skip_typeref(orig_type);
8501 if (is_type_incomplete(type)) {
8502 errorf(&value->base.source_position,
8503 "cannot throw object of incomplete type '%T'", orig_type);
8504 } else if (is_type_pointer(type)) {
8505 type_t *const points_to = skip_typeref(type->pointer.points_to);
8506 if (is_type_incomplete(points_to) &&
8507 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8508 errorf(&value->base.source_position,
8509 "cannot throw pointer to incomplete type '%T'", orig_type);
8517 result->unary.value = value;
8522 static bool check_pointer_arithmetic(const source_position_t *source_position,
8523 type_t *pointer_type,
8524 type_t *orig_pointer_type)
8526 type_t *points_to = pointer_type->pointer.points_to;
8527 points_to = skip_typeref(points_to);
8529 if (is_type_incomplete(points_to)) {
8530 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8531 errorf(source_position,
8532 "arithmetic with pointer to incomplete type '%T' not allowed",
8535 } else if (warning.pointer_arith) {
8536 warningf(source_position,
8537 "pointer of type '%T' used in arithmetic",
8540 } else if (is_type_function(points_to)) {
8542 errorf(source_position,
8543 "arithmetic with pointer to function type '%T' not allowed",
8546 } else if (warning.pointer_arith) {
8547 warningf(source_position,
8548 "pointer to a function '%T' used in arithmetic",
8555 static bool is_lvalue(const expression_t *expression)
8557 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8558 switch (expression->kind) {
8559 case EXPR_ARRAY_ACCESS:
8560 case EXPR_COMPOUND_LITERAL:
8561 case EXPR_REFERENCE:
8563 case EXPR_UNARY_DEREFERENCE:
8567 type_t *type = skip_typeref(expression->base.type);
8569 /* ISO/IEC 14882:1998(E) §3.10:3 */
8570 is_type_reference(type) ||
8571 /* Claim it is an lvalue, if the type is invalid. There was a parse
8572 * error before, which maybe prevented properly recognizing it as
8574 !is_type_valid(type);
8579 static void semantic_incdec(unary_expression_t *expression)
8581 type_t *const orig_type = expression->value->base.type;
8582 type_t *const type = skip_typeref(orig_type);
8583 if (is_type_pointer(type)) {
8584 if (!check_pointer_arithmetic(&expression->base.source_position,
8588 } else if (!is_type_real(type) && is_type_valid(type)) {
8589 /* TODO: improve error message */
8590 errorf(&expression->base.source_position,
8591 "operation needs an arithmetic or pointer type");
8594 if (!is_lvalue(expression->value)) {
8595 /* TODO: improve error message */
8596 errorf(&expression->base.source_position, "lvalue required as operand");
8598 expression->base.type = orig_type;
8601 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8603 type_t *const orig_type = expression->value->base.type;
8604 type_t *const type = skip_typeref(orig_type);
8605 if (!is_type_arithmetic(type)) {
8606 if (is_type_valid(type)) {
8607 /* TODO: improve error message */
8608 errorf(&expression->base.source_position,
8609 "operation needs an arithmetic type");
8614 expression->base.type = orig_type;
8617 static void semantic_unexpr_plus(unary_expression_t *expression)
8619 semantic_unexpr_arithmetic(expression);
8620 if (warning.traditional)
8621 warningf(&expression->base.source_position,
8622 "traditional C rejects the unary plus operator");
8625 static void semantic_not(unary_expression_t *expression)
8627 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8628 semantic_condition(expression->value, "operand of !");
8629 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8632 static void semantic_unexpr_integer(unary_expression_t *expression)
8634 type_t *const orig_type = expression->value->base.type;
8635 type_t *const type = skip_typeref(orig_type);
8636 if (!is_type_integer(type)) {
8637 if (is_type_valid(type)) {
8638 errorf(&expression->base.source_position,
8639 "operand of ~ must be of integer type");
8644 expression->base.type = orig_type;
8647 static void semantic_dereference(unary_expression_t *expression)
8649 type_t *const orig_type = expression->value->base.type;
8650 type_t *const type = skip_typeref(orig_type);
8651 if (!is_type_pointer(type)) {
8652 if (is_type_valid(type)) {
8653 errorf(&expression->base.source_position,
8654 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8659 type_t *result_type = type->pointer.points_to;
8660 result_type = automatic_type_conversion(result_type);
8661 expression->base.type = result_type;
8665 * Record that an address is taken (expression represents an lvalue).
8667 * @param expression the expression
8668 * @param may_be_register if true, the expression might be an register
8670 static void set_address_taken(expression_t *expression, bool may_be_register)
8672 if (expression->kind != EXPR_REFERENCE)
8675 entity_t *const entity = expression->reference.entity;
8677 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8680 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8681 && !may_be_register) {
8682 errorf(&expression->base.source_position,
8683 "address of register %s '%Y' requested",
8684 get_entity_kind_name(entity->kind), entity->base.symbol);
8687 if (entity->kind == ENTITY_VARIABLE) {
8688 entity->variable.address_taken = true;
8690 assert(entity->kind == ENTITY_PARAMETER);
8691 entity->parameter.address_taken = true;
8696 * Check the semantic of the address taken expression.
8698 static void semantic_take_addr(unary_expression_t *expression)
8700 expression_t *value = expression->value;
8701 value->base.type = revert_automatic_type_conversion(value);
8703 type_t *orig_type = value->base.type;
8704 type_t *type = skip_typeref(orig_type);
8705 if (!is_type_valid(type))
8709 if (!is_lvalue(value)) {
8710 errorf(&expression->base.source_position, "'&' requires an lvalue");
8712 if (type->kind == TYPE_BITFIELD) {
8713 errorf(&expression->base.source_position,
8714 "'&' not allowed on object with bitfield type '%T'",
8718 set_address_taken(value, false);
8720 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8723 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8724 static expression_t *parse_##unexpression_type(void) \
8726 expression_t *unary_expression \
8727 = allocate_expression_zero(unexpression_type); \
8729 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8731 sfunc(&unary_expression->unary); \
8733 return unary_expression; \
8736 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8737 semantic_unexpr_arithmetic)
8738 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8739 semantic_unexpr_plus)
8740 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8742 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8743 semantic_dereference)
8744 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8746 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8747 semantic_unexpr_integer)
8748 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8750 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8753 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8755 static expression_t *parse_##unexpression_type(expression_t *left) \
8757 expression_t *unary_expression \
8758 = allocate_expression_zero(unexpression_type); \
8760 unary_expression->unary.value = left; \
8762 sfunc(&unary_expression->unary); \
8764 return unary_expression; \
8767 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8768 EXPR_UNARY_POSTFIX_INCREMENT,
8770 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8771 EXPR_UNARY_POSTFIX_DECREMENT,
8774 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8776 /* TODO: handle complex + imaginary types */
8778 type_left = get_unqualified_type(type_left);
8779 type_right = get_unqualified_type(type_right);
8781 /* § 6.3.1.8 Usual arithmetic conversions */
8782 if (type_left == type_long_double || type_right == type_long_double) {
8783 return type_long_double;
8784 } else if (type_left == type_double || type_right == type_double) {
8786 } else if (type_left == type_float || type_right == type_float) {
8790 type_left = promote_integer(type_left);
8791 type_right = promote_integer(type_right);
8793 if (type_left == type_right)
8796 bool const signed_left = is_type_signed(type_left);
8797 bool const signed_right = is_type_signed(type_right);
8798 int const rank_left = get_rank(type_left);
8799 int const rank_right = get_rank(type_right);
8801 if (signed_left == signed_right)
8802 return rank_left >= rank_right ? type_left : type_right;
8811 u_rank = rank_right;
8812 u_type = type_right;
8814 s_rank = rank_right;
8815 s_type = type_right;
8820 if (u_rank >= s_rank)
8823 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8825 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8826 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8830 case ATOMIC_TYPE_INT: return type_unsigned_int;
8831 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8832 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8834 default: panic("invalid atomic type");
8839 * Check the semantic restrictions for a binary expression.
8841 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8843 expression_t *const left = expression->left;
8844 expression_t *const right = expression->right;
8845 type_t *const orig_type_left = left->base.type;
8846 type_t *const orig_type_right = right->base.type;
8847 type_t *const type_left = skip_typeref(orig_type_left);
8848 type_t *const type_right = skip_typeref(orig_type_right);
8850 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8851 /* TODO: improve error message */
8852 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8853 errorf(&expression->base.source_position,
8854 "operation needs arithmetic types");
8859 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8860 expression->left = create_implicit_cast(left, arithmetic_type);
8861 expression->right = create_implicit_cast(right, arithmetic_type);
8862 expression->base.type = arithmetic_type;
8865 static void warn_div_by_zero(binary_expression_t const *const expression)
8867 if (!warning.div_by_zero ||
8868 !is_type_integer(expression->base.type))
8871 expression_t const *const right = expression->right;
8872 /* The type of the right operand can be different for /= */
8873 if (is_type_integer(right->base.type) &&
8874 is_constant_expression(right) &&
8875 fold_constant(right) == 0) {
8876 warningf(&expression->base.source_position, "division by zero");
8881 * Check the semantic restrictions for a div/mod expression.
8883 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8884 semantic_binexpr_arithmetic(expression);
8885 warn_div_by_zero(expression);
8888 static void warn_addsub_in_shift(const expression_t *const expr)
8890 if (expr->base.parenthesized)
8894 switch (expr->kind) {
8895 case EXPR_BINARY_ADD: op = '+'; break;
8896 case EXPR_BINARY_SUB: op = '-'; break;
8900 warningf(&expr->base.source_position,
8901 "suggest parentheses around '%c' inside shift", op);
8904 static void semantic_shift_op(binary_expression_t *expression)
8906 expression_t *const left = expression->left;
8907 expression_t *const right = expression->right;
8908 type_t *const orig_type_left = left->base.type;
8909 type_t *const orig_type_right = right->base.type;
8910 type_t * type_left = skip_typeref(orig_type_left);
8911 type_t * type_right = skip_typeref(orig_type_right);
8913 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8914 /* TODO: improve error message */
8915 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8916 errorf(&expression->base.source_position,
8917 "operands of shift operation must have integer types");
8922 if (warning.parentheses) {
8923 warn_addsub_in_shift(left);
8924 warn_addsub_in_shift(right);
8927 type_left = promote_integer(type_left);
8928 type_right = promote_integer(type_right);
8930 expression->left = create_implicit_cast(left, type_left);
8931 expression->right = create_implicit_cast(right, type_right);
8932 expression->base.type = type_left;
8935 static void semantic_add(binary_expression_t *expression)
8937 expression_t *const left = expression->left;
8938 expression_t *const right = expression->right;
8939 type_t *const orig_type_left = left->base.type;
8940 type_t *const orig_type_right = right->base.type;
8941 type_t *const type_left = skip_typeref(orig_type_left);
8942 type_t *const type_right = skip_typeref(orig_type_right);
8945 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8946 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8947 expression->left = create_implicit_cast(left, arithmetic_type);
8948 expression->right = create_implicit_cast(right, arithmetic_type);
8949 expression->base.type = arithmetic_type;
8950 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8951 check_pointer_arithmetic(&expression->base.source_position,
8952 type_left, orig_type_left);
8953 expression->base.type = type_left;
8954 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8955 check_pointer_arithmetic(&expression->base.source_position,
8956 type_right, orig_type_right);
8957 expression->base.type = type_right;
8958 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8959 errorf(&expression->base.source_position,
8960 "invalid operands to binary + ('%T', '%T')",
8961 orig_type_left, orig_type_right);
8965 static void semantic_sub(binary_expression_t *expression)
8967 expression_t *const left = expression->left;
8968 expression_t *const right = expression->right;
8969 type_t *const orig_type_left = left->base.type;
8970 type_t *const orig_type_right = right->base.type;
8971 type_t *const type_left = skip_typeref(orig_type_left);
8972 type_t *const type_right = skip_typeref(orig_type_right);
8973 source_position_t const *const pos = &expression->base.source_position;
8976 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8977 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8978 expression->left = create_implicit_cast(left, arithmetic_type);
8979 expression->right = create_implicit_cast(right, arithmetic_type);
8980 expression->base.type = arithmetic_type;
8981 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8982 check_pointer_arithmetic(&expression->base.source_position,
8983 type_left, orig_type_left);
8984 expression->base.type = type_left;
8985 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8986 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8987 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8988 if (!types_compatible(unqual_left, unqual_right)) {
8990 "subtracting pointers to incompatible types '%T' and '%T'",
8991 orig_type_left, orig_type_right);
8992 } else if (!is_type_object(unqual_left)) {
8993 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8994 errorf(pos, "subtracting pointers to non-object types '%T'",
8996 } else if (warning.other) {
8997 warningf(pos, "subtracting pointers to void");
9000 expression->base.type = type_ptrdiff_t;
9001 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9002 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
9003 orig_type_left, orig_type_right);
9007 static void warn_string_literal_address(expression_t const* expr)
9009 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
9010 expr = expr->unary.value;
9011 if (expr->kind != EXPR_UNARY_DEREFERENCE)
9013 expr = expr->unary.value;
9016 if (expr->kind == EXPR_STRING_LITERAL ||
9017 expr->kind == EXPR_WIDE_STRING_LITERAL) {
9018 warningf(&expr->base.source_position,
9019 "comparison with string literal results in unspecified behaviour");
9023 static void warn_comparison_in_comparison(const expression_t *const expr)
9025 if (expr->base.parenthesized)
9027 switch (expr->base.kind) {
9028 case EXPR_BINARY_LESS:
9029 case EXPR_BINARY_GREATER:
9030 case EXPR_BINARY_LESSEQUAL:
9031 case EXPR_BINARY_GREATEREQUAL:
9032 case EXPR_BINARY_NOTEQUAL:
9033 case EXPR_BINARY_EQUAL:
9034 warningf(&expr->base.source_position,
9035 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9042 static bool maybe_negative(expression_t const *const expr)
9045 !is_constant_expression(expr) ||
9046 fold_constant(expr) < 0;
9050 * Check the semantics of comparison expressions.
9052 * @param expression The expression to check.
9054 static void semantic_comparison(binary_expression_t *expression)
9056 expression_t *left = expression->left;
9057 expression_t *right = expression->right;
9059 if (warning.address) {
9060 warn_string_literal_address(left);
9061 warn_string_literal_address(right);
9063 expression_t const* const func_left = get_reference_address(left);
9064 if (func_left != NULL && is_null_pointer_constant(right)) {
9065 warningf(&expression->base.source_position,
9066 "the address of '%Y' will never be NULL",
9067 func_left->reference.entity->base.symbol);
9070 expression_t const* const func_right = get_reference_address(right);
9071 if (func_right != NULL && is_null_pointer_constant(right)) {
9072 warningf(&expression->base.source_position,
9073 "the address of '%Y' will never be NULL",
9074 func_right->reference.entity->base.symbol);
9078 if (warning.parentheses) {
9079 warn_comparison_in_comparison(left);
9080 warn_comparison_in_comparison(right);
9083 type_t *orig_type_left = left->base.type;
9084 type_t *orig_type_right = right->base.type;
9085 type_t *type_left = skip_typeref(orig_type_left);
9086 type_t *type_right = skip_typeref(orig_type_right);
9088 /* TODO non-arithmetic types */
9089 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9090 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9092 /* test for signed vs unsigned compares */
9093 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9094 bool const signed_left = is_type_signed(type_left);
9095 bool const signed_right = is_type_signed(type_right);
9096 if (signed_left != signed_right) {
9097 /* FIXME long long needs better const folding magic */
9098 /* TODO check whether constant value can be represented by other type */
9099 if ((signed_left && maybe_negative(left)) ||
9100 (signed_right && maybe_negative(right))) {
9101 warningf(&expression->base.source_position,
9102 "comparison between signed and unsigned");
9107 expression->left = create_implicit_cast(left, arithmetic_type);
9108 expression->right = create_implicit_cast(right, arithmetic_type);
9109 expression->base.type = arithmetic_type;
9110 if (warning.float_equal &&
9111 (expression->base.kind == EXPR_BINARY_EQUAL ||
9112 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9113 is_type_float(arithmetic_type)) {
9114 warningf(&expression->base.source_position,
9115 "comparing floating point with == or != is unsafe");
9117 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9118 /* TODO check compatibility */
9119 } else if (is_type_pointer(type_left)) {
9120 expression->right = create_implicit_cast(right, type_left);
9121 } else if (is_type_pointer(type_right)) {
9122 expression->left = create_implicit_cast(left, type_right);
9123 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9124 type_error_incompatible("invalid operands in comparison",
9125 &expression->base.source_position,
9126 type_left, type_right);
9128 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9132 * Checks if a compound type has constant fields.
9134 static bool has_const_fields(const compound_type_t *type)
9136 compound_t *compound = type->compound;
9137 entity_t *entry = compound->members.entities;
9139 for (; entry != NULL; entry = entry->base.next) {
9140 if (!is_declaration(entry))
9143 const type_t *decl_type = skip_typeref(entry->declaration.type);
9144 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9151 static bool is_valid_assignment_lhs(expression_t const* const left)
9153 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9154 type_t *const type_left = skip_typeref(orig_type_left);
9156 if (!is_lvalue(left)) {
9157 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9162 if (left->kind == EXPR_REFERENCE
9163 && left->reference.entity->kind == ENTITY_FUNCTION) {
9164 errorf(HERE, "cannot assign to function '%E'", left);
9168 if (is_type_array(type_left)) {
9169 errorf(HERE, "cannot assign to array '%E'", left);
9172 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9173 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9177 if (is_type_incomplete(type_left)) {
9178 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9179 left, orig_type_left);
9182 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9183 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9184 left, orig_type_left);
9191 static void semantic_arithmetic_assign(binary_expression_t *expression)
9193 expression_t *left = expression->left;
9194 expression_t *right = expression->right;
9195 type_t *orig_type_left = left->base.type;
9196 type_t *orig_type_right = right->base.type;
9198 if (!is_valid_assignment_lhs(left))
9201 type_t *type_left = skip_typeref(orig_type_left);
9202 type_t *type_right = skip_typeref(orig_type_right);
9204 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9205 /* TODO: improve error message */
9206 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9207 errorf(&expression->base.source_position,
9208 "operation needs arithmetic types");
9213 /* combined instructions are tricky. We can't create an implicit cast on
9214 * the left side, because we need the uncasted form for the store.
9215 * The ast2firm pass has to know that left_type must be right_type
9216 * for the arithmetic operation and create a cast by itself */
9217 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9218 expression->right = create_implicit_cast(right, arithmetic_type);
9219 expression->base.type = type_left;
9222 static void semantic_divmod_assign(binary_expression_t *expression)
9224 semantic_arithmetic_assign(expression);
9225 warn_div_by_zero(expression);
9228 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9230 expression_t *const left = expression->left;
9231 expression_t *const right = expression->right;
9232 type_t *const orig_type_left = left->base.type;
9233 type_t *const orig_type_right = right->base.type;
9234 type_t *const type_left = skip_typeref(orig_type_left);
9235 type_t *const type_right = skip_typeref(orig_type_right);
9237 if (!is_valid_assignment_lhs(left))
9240 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9241 /* combined instructions are tricky. We can't create an implicit cast on
9242 * the left side, because we need the uncasted form for the store.
9243 * The ast2firm pass has to know that left_type must be right_type
9244 * for the arithmetic operation and create a cast by itself */
9245 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9246 expression->right = create_implicit_cast(right, arithmetic_type);
9247 expression->base.type = type_left;
9248 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9249 check_pointer_arithmetic(&expression->base.source_position,
9250 type_left, orig_type_left);
9251 expression->base.type = type_left;
9252 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9253 errorf(&expression->base.source_position,
9254 "incompatible types '%T' and '%T' in assignment",
9255 orig_type_left, orig_type_right);
9259 static void warn_logical_and_within_or(const expression_t *const expr)
9261 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9263 if (expr->base.parenthesized)
9265 warningf(&expr->base.source_position,
9266 "suggest parentheses around && within ||");
9270 * Check the semantic restrictions of a logical expression.
9272 static void semantic_logical_op(binary_expression_t *expression)
9274 /* §6.5.13:2 Each of the operands shall have scalar type.
9275 * §6.5.14:2 Each of the operands shall have scalar type. */
9276 semantic_condition(expression->left, "left operand of logical operator");
9277 semantic_condition(expression->right, "right operand of logical operator");
9278 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9279 warning.parentheses) {
9280 warn_logical_and_within_or(expression->left);
9281 warn_logical_and_within_or(expression->right);
9283 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9287 * Check the semantic restrictions of a binary assign expression.
9289 static void semantic_binexpr_assign(binary_expression_t *expression)
9291 expression_t *left = expression->left;
9292 type_t *orig_type_left = left->base.type;
9294 if (!is_valid_assignment_lhs(left))
9297 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9298 report_assign_error(error, orig_type_left, expression->right,
9299 "assignment", &left->base.source_position);
9300 expression->right = create_implicit_cast(expression->right, orig_type_left);
9301 expression->base.type = orig_type_left;
9305 * Determine if the outermost operation (or parts thereof) of the given
9306 * expression has no effect in order to generate a warning about this fact.
9307 * Therefore in some cases this only examines some of the operands of the
9308 * expression (see comments in the function and examples below).
9310 * f() + 23; // warning, because + has no effect
9311 * x || f(); // no warning, because x controls execution of f()
9312 * x ? y : f(); // warning, because y has no effect
9313 * (void)x; // no warning to be able to suppress the warning
9314 * This function can NOT be used for an "expression has definitely no effect"-
9316 static bool expression_has_effect(const expression_t *const expr)
9318 switch (expr->kind) {
9319 case EXPR_UNKNOWN: break;
9320 case EXPR_INVALID: return true; /* do NOT warn */
9321 case EXPR_REFERENCE: return false;
9322 case EXPR_REFERENCE_ENUM_VALUE: return false;
9323 /* suppress the warning for microsoft __noop operations */
9324 case EXPR_CONST: return expr->conste.is_ms_noop;
9325 case EXPR_CHARACTER_CONSTANT: return false;
9326 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9327 case EXPR_STRING_LITERAL: return false;
9328 case EXPR_WIDE_STRING_LITERAL: return false;
9329 case EXPR_LABEL_ADDRESS: return false;
9332 const call_expression_t *const call = &expr->call;
9333 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9336 switch (call->function->builtin_symbol.symbol->ID) {
9337 case T___builtin_va_end: return true;
9338 default: return false;
9342 /* Generate the warning if either the left or right hand side of a
9343 * conditional expression has no effect */
9344 case EXPR_CONDITIONAL: {
9345 const conditional_expression_t *const cond = &expr->conditional;
9347 expression_has_effect(cond->true_expression) &&
9348 expression_has_effect(cond->false_expression);
9351 case EXPR_SELECT: return false;
9352 case EXPR_ARRAY_ACCESS: return false;
9353 case EXPR_SIZEOF: return false;
9354 case EXPR_CLASSIFY_TYPE: return false;
9355 case EXPR_ALIGNOF: return false;
9357 case EXPR_FUNCNAME: return false;
9358 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9359 case EXPR_BUILTIN_CONSTANT_P: return false;
9360 case EXPR_BUILTIN_PREFETCH: return true;
9361 case EXPR_OFFSETOF: return false;
9362 case EXPR_VA_START: return true;
9363 case EXPR_VA_ARG: return true;
9364 case EXPR_STATEMENT: return true; // TODO
9365 case EXPR_COMPOUND_LITERAL: return false;
9367 case EXPR_UNARY_NEGATE: return false;
9368 case EXPR_UNARY_PLUS: return false;
9369 case EXPR_UNARY_BITWISE_NEGATE: return false;
9370 case EXPR_UNARY_NOT: return false;
9371 case EXPR_UNARY_DEREFERENCE: return false;
9372 case EXPR_UNARY_TAKE_ADDRESS: return false;
9373 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9374 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9375 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9376 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9378 /* Treat void casts as if they have an effect in order to being able to
9379 * suppress the warning */
9380 case EXPR_UNARY_CAST: {
9381 type_t *const type = skip_typeref(expr->base.type);
9382 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9385 case EXPR_UNARY_CAST_IMPLICIT: return true;
9386 case EXPR_UNARY_ASSUME: return true;
9387 case EXPR_UNARY_DELETE: return true;
9388 case EXPR_UNARY_DELETE_ARRAY: return true;
9389 case EXPR_UNARY_THROW: return true;
9391 case EXPR_BINARY_ADD: return false;
9392 case EXPR_BINARY_SUB: return false;
9393 case EXPR_BINARY_MUL: return false;
9394 case EXPR_BINARY_DIV: return false;
9395 case EXPR_BINARY_MOD: return false;
9396 case EXPR_BINARY_EQUAL: return false;
9397 case EXPR_BINARY_NOTEQUAL: return false;
9398 case EXPR_BINARY_LESS: return false;
9399 case EXPR_BINARY_LESSEQUAL: return false;
9400 case EXPR_BINARY_GREATER: return false;
9401 case EXPR_BINARY_GREATEREQUAL: return false;
9402 case EXPR_BINARY_BITWISE_AND: return false;
9403 case EXPR_BINARY_BITWISE_OR: return false;
9404 case EXPR_BINARY_BITWISE_XOR: return false;
9405 case EXPR_BINARY_SHIFTLEFT: return false;
9406 case EXPR_BINARY_SHIFTRIGHT: return false;
9407 case EXPR_BINARY_ASSIGN: return true;
9408 case EXPR_BINARY_MUL_ASSIGN: return true;
9409 case EXPR_BINARY_DIV_ASSIGN: return true;
9410 case EXPR_BINARY_MOD_ASSIGN: return true;
9411 case EXPR_BINARY_ADD_ASSIGN: return true;
9412 case EXPR_BINARY_SUB_ASSIGN: return true;
9413 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9414 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9415 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9416 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9417 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9419 /* Only examine the right hand side of && and ||, because the left hand
9420 * side already has the effect of controlling the execution of the right
9422 case EXPR_BINARY_LOGICAL_AND:
9423 case EXPR_BINARY_LOGICAL_OR:
9424 /* Only examine the right hand side of a comma expression, because the left
9425 * hand side has a separate warning */
9426 case EXPR_BINARY_COMMA:
9427 return expression_has_effect(expr->binary.right);
9429 case EXPR_BINARY_ISGREATER: return false;
9430 case EXPR_BINARY_ISGREATEREQUAL: return false;
9431 case EXPR_BINARY_ISLESS: return false;
9432 case EXPR_BINARY_ISLESSEQUAL: return false;
9433 case EXPR_BINARY_ISLESSGREATER: return false;
9434 case EXPR_BINARY_ISUNORDERED: return false;
9437 internal_errorf(HERE, "unexpected expression");
9440 static void semantic_comma(binary_expression_t *expression)
9442 if (warning.unused_value) {
9443 const expression_t *const left = expression->left;
9444 if (!expression_has_effect(left)) {
9445 warningf(&left->base.source_position,
9446 "left-hand operand of comma expression has no effect");
9449 expression->base.type = expression->right->base.type;
9453 * @param prec_r precedence of the right operand
9455 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9456 static expression_t *parse_##binexpression_type(expression_t *left) \
9458 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9459 binexpr->binary.left = left; \
9462 expression_t *right = parse_sub_expression(prec_r); \
9464 binexpr->binary.right = right; \
9465 sfunc(&binexpr->binary); \
9470 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9471 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9472 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9473 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9474 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9475 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9476 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9477 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9478 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9479 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9480 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9481 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9482 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9483 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9484 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9485 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9486 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9487 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9488 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9489 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9490 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9491 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9492 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9493 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9494 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9495 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9496 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9497 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9498 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9499 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9502 static expression_t *parse_sub_expression(precedence_t precedence)
9504 if (token.type < 0) {
9505 return expected_expression_error();
9508 expression_parser_function_t *parser
9509 = &expression_parsers[token.type];
9510 source_position_t source_position = token.source_position;
9513 if (parser->parser != NULL) {
9514 left = parser->parser();
9516 left = parse_primary_expression();
9518 assert(left != NULL);
9519 left->base.source_position = source_position;
9522 if (token.type < 0) {
9523 return expected_expression_error();
9526 parser = &expression_parsers[token.type];
9527 if (parser->infix_parser == NULL)
9529 if (parser->infix_precedence < precedence)
9532 left = parser->infix_parser(left);
9534 assert(left != NULL);
9535 assert(left->kind != EXPR_UNKNOWN);
9536 left->base.source_position = source_position;
9543 * Parse an expression.
9545 static expression_t *parse_expression(void)
9547 return parse_sub_expression(PREC_EXPRESSION);
9551 * Register a parser for a prefix-like operator.
9553 * @param parser the parser function
9554 * @param token_type the token type of the prefix token
9556 static void register_expression_parser(parse_expression_function parser,
9559 expression_parser_function_t *entry = &expression_parsers[token_type];
9561 if (entry->parser != NULL) {
9562 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9563 panic("trying to register multiple expression parsers for a token");
9565 entry->parser = parser;
9569 * Register a parser for an infix operator with given precedence.
9571 * @param parser the parser function
9572 * @param token_type the token type of the infix operator
9573 * @param precedence the precedence of the operator
9575 static void register_infix_parser(parse_expression_infix_function parser,
9576 int token_type, precedence_t precedence)
9578 expression_parser_function_t *entry = &expression_parsers[token_type];
9580 if (entry->infix_parser != NULL) {
9581 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9582 panic("trying to register multiple infix expression parsers for a "
9585 entry->infix_parser = parser;
9586 entry->infix_precedence = precedence;
9590 * Initialize the expression parsers.
9592 static void init_expression_parsers(void)
9594 memset(&expression_parsers, 0, sizeof(expression_parsers));
9596 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9597 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9598 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9599 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9600 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9601 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9602 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9603 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9604 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9605 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9606 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9607 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9608 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9609 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9610 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9611 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9612 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9613 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9614 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9615 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9616 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9617 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9618 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9619 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9620 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9621 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9622 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9623 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9624 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9625 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9626 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9627 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9628 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9629 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9630 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9631 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9632 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9634 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9635 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9636 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9637 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9638 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9639 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9640 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9641 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9642 register_expression_parser(parse_sizeof, T_sizeof);
9643 register_expression_parser(parse_alignof, T___alignof__);
9644 register_expression_parser(parse_extension, T___extension__);
9645 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9646 register_expression_parser(parse_delete, T_delete);
9647 register_expression_parser(parse_throw, T_throw);
9651 * Parse a asm statement arguments specification.
9653 static asm_argument_t *parse_asm_arguments(bool is_out)
9655 asm_argument_t *result = NULL;
9656 asm_argument_t **anchor = &result;
9658 while (token.type == T_STRING_LITERAL || token.type == '[') {
9659 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9660 memset(argument, 0, sizeof(argument[0]));
9662 if (token.type == '[') {
9664 if (token.type != T_IDENTIFIER) {
9665 parse_error_expected("while parsing asm argument",
9666 T_IDENTIFIER, NULL);
9669 argument->symbol = token.v.symbol;
9671 expect(']', end_error);
9674 argument->constraints = parse_string_literals();
9675 expect('(', end_error);
9676 add_anchor_token(')');
9677 expression_t *expression = parse_expression();
9678 rem_anchor_token(')');
9680 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9681 * change size or type representation (e.g. int -> long is ok, but
9682 * int -> float is not) */
9683 if (expression->kind == EXPR_UNARY_CAST) {
9684 type_t *const type = expression->base.type;
9685 type_kind_t const kind = type->kind;
9686 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9689 if (kind == TYPE_ATOMIC) {
9690 atomic_type_kind_t const akind = type->atomic.akind;
9691 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9692 size = get_atomic_type_size(akind);
9694 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9695 size = get_atomic_type_size(get_intptr_kind());
9699 expression_t *const value = expression->unary.value;
9700 type_t *const value_type = value->base.type;
9701 type_kind_t const value_kind = value_type->kind;
9703 unsigned value_flags;
9704 unsigned value_size;
9705 if (value_kind == TYPE_ATOMIC) {
9706 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9707 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9708 value_size = get_atomic_type_size(value_akind);
9709 } else if (value_kind == TYPE_POINTER) {
9710 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9711 value_size = get_atomic_type_size(get_intptr_kind());
9716 if (value_flags != flags || value_size != size)
9720 } while (expression->kind == EXPR_UNARY_CAST);
9724 if (!is_lvalue(expression)) {
9725 errorf(&expression->base.source_position,
9726 "asm output argument is not an lvalue");
9729 if (argument->constraints.begin[0] == '+')
9730 mark_vars_read(expression, NULL);
9732 mark_vars_read(expression, NULL);
9734 argument->expression = expression;
9735 expect(')', end_error);
9737 set_address_taken(expression, true);
9740 anchor = &argument->next;
9742 if (token.type != ',')
9753 * Parse a asm statement clobber specification.
9755 static asm_clobber_t *parse_asm_clobbers(void)
9757 asm_clobber_t *result = NULL;
9758 asm_clobber_t *last = NULL;
9760 while (token.type == T_STRING_LITERAL) {
9761 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9762 clobber->clobber = parse_string_literals();
9765 last->next = clobber;
9771 if (token.type != ',')
9780 * Parse an asm statement.
9782 static statement_t *parse_asm_statement(void)
9784 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9785 asm_statement_t *asm_statement = &statement->asms;
9789 if (token.type == T_volatile) {
9791 asm_statement->is_volatile = true;
9794 expect('(', end_error);
9795 add_anchor_token(')');
9796 add_anchor_token(':');
9797 asm_statement->asm_text = parse_string_literals();
9799 if (token.type != ':') {
9800 rem_anchor_token(':');
9805 asm_statement->outputs = parse_asm_arguments(true);
9806 if (token.type != ':') {
9807 rem_anchor_token(':');
9812 asm_statement->inputs = parse_asm_arguments(false);
9813 if (token.type != ':') {
9814 rem_anchor_token(':');
9817 rem_anchor_token(':');
9820 asm_statement->clobbers = parse_asm_clobbers();
9823 rem_anchor_token(')');
9824 expect(')', end_error);
9825 expect(';', end_error);
9827 if (asm_statement->outputs == NULL) {
9828 /* GCC: An 'asm' instruction without any output operands will be treated
9829 * identically to a volatile 'asm' instruction. */
9830 asm_statement->is_volatile = true;
9835 return create_invalid_statement();
9839 * Parse a case statement.
9841 static statement_t *parse_case_statement(void)
9843 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9844 source_position_t *const pos = &statement->base.source_position;
9848 expression_t *const expression = parse_expression();
9849 statement->case_label.expression = expression;
9850 if (!is_constant_expression(expression)) {
9851 /* This check does not prevent the error message in all cases of an
9852 * prior error while parsing the expression. At least it catches the
9853 * common case of a mistyped enum entry. */
9854 if (is_type_valid(skip_typeref(expression->base.type))) {
9855 errorf(pos, "case label does not reduce to an integer constant");
9857 statement->case_label.is_bad = true;
9859 long const val = fold_constant(expression);
9860 statement->case_label.first_case = val;
9861 statement->case_label.last_case = val;
9865 if (token.type == T_DOTDOTDOT) {
9867 expression_t *const end_range = parse_expression();
9868 statement->case_label.end_range = end_range;
9869 if (!is_constant_expression(end_range)) {
9870 /* This check does not prevent the error message in all cases of an
9871 * prior error while parsing the expression. At least it catches the
9872 * common case of a mistyped enum entry. */
9873 if (is_type_valid(skip_typeref(end_range->base.type))) {
9874 errorf(pos, "case range does not reduce to an integer constant");
9876 statement->case_label.is_bad = true;
9878 long const val = fold_constant(end_range);
9879 statement->case_label.last_case = val;
9881 if (warning.other && val < statement->case_label.first_case) {
9882 statement->case_label.is_empty_range = true;
9883 warningf(pos, "empty range specified");
9889 PUSH_PARENT(statement);
9891 expect(':', end_error);
9894 if (current_switch != NULL) {
9895 if (! statement->case_label.is_bad) {
9896 /* Check for duplicate case values */
9897 case_label_statement_t *c = &statement->case_label;
9898 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9899 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9902 if (c->last_case < l->first_case || c->first_case > l->last_case)
9905 errorf(pos, "duplicate case value (previously used %P)",
9906 &l->base.source_position);
9910 /* link all cases into the switch statement */
9911 if (current_switch->last_case == NULL) {
9912 current_switch->first_case = &statement->case_label;
9914 current_switch->last_case->next = &statement->case_label;
9916 current_switch->last_case = &statement->case_label;
9918 errorf(pos, "case label not within a switch statement");
9921 statement_t *const inner_stmt = parse_statement();
9922 statement->case_label.statement = inner_stmt;
9923 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9924 errorf(&inner_stmt->base.source_position, "declaration after case label");
9932 * Parse a default statement.
9934 static statement_t *parse_default_statement(void)
9936 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9940 PUSH_PARENT(statement);
9942 expect(':', end_error);
9943 if (current_switch != NULL) {
9944 const case_label_statement_t *def_label = current_switch->default_label;
9945 if (def_label != NULL) {
9946 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9947 &def_label->base.source_position);
9949 current_switch->default_label = &statement->case_label;
9951 /* link all cases into the switch statement */
9952 if (current_switch->last_case == NULL) {
9953 current_switch->first_case = &statement->case_label;
9955 current_switch->last_case->next = &statement->case_label;
9957 current_switch->last_case = &statement->case_label;
9960 errorf(&statement->base.source_position,
9961 "'default' label not within a switch statement");
9964 statement_t *const inner_stmt = parse_statement();
9965 statement->case_label.statement = inner_stmt;
9966 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9967 errorf(&inner_stmt->base.source_position, "declaration after default label");
9974 return create_invalid_statement();
9978 * Parse a label statement.
9980 static statement_t *parse_label_statement(void)
9982 assert(token.type == T_IDENTIFIER);
9983 symbol_t *symbol = token.v.symbol;
9984 label_t *label = get_label(symbol);
9986 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9987 statement->label.label = label;
9991 PUSH_PARENT(statement);
9993 /* if statement is already set then the label is defined twice,
9994 * otherwise it was just mentioned in a goto/local label declaration so far
9996 if (label->statement != NULL) {
9997 errorf(HERE, "duplicate label '%Y' (declared %P)",
9998 symbol, &label->base.source_position);
10000 label->base.source_position = token.source_position;
10001 label->statement = statement;
10006 if (token.type == '}') {
10007 /* TODO only warn? */
10008 if (warning.other && false) {
10009 warningf(HERE, "label at end of compound statement");
10010 statement->label.statement = create_empty_statement();
10012 errorf(HERE, "label at end of compound statement");
10013 statement->label.statement = create_invalid_statement();
10015 } else if (token.type == ';') {
10016 /* Eat an empty statement here, to avoid the warning about an empty
10017 * statement after a label. label:; is commonly used to have a label
10018 * before a closing brace. */
10019 statement->label.statement = create_empty_statement();
10022 statement_t *const inner_stmt = parse_statement();
10023 statement->label.statement = inner_stmt;
10024 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10025 errorf(&inner_stmt->base.source_position, "declaration after label");
10029 /* remember the labels in a list for later checking */
10030 *label_anchor = &statement->label;
10031 label_anchor = &statement->label.next;
10038 * Parse an if statement.
10040 static statement_t *parse_if(void)
10042 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10046 PUSH_PARENT(statement);
10048 add_anchor_token('{');
10050 expect('(', end_error);
10051 add_anchor_token(')');
10052 expression_t *const expr = parse_expression();
10053 statement->ifs.condition = expr;
10054 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10056 semantic_condition(expr, "condition of 'if'-statment");
10057 mark_vars_read(expr, NULL);
10058 rem_anchor_token(')');
10059 expect(')', end_error);
10062 rem_anchor_token('{');
10064 add_anchor_token(T_else);
10065 statement_t *const true_stmt = parse_statement();
10066 statement->ifs.true_statement = true_stmt;
10067 rem_anchor_token(T_else);
10069 if (token.type == T_else) {
10071 statement->ifs.false_statement = parse_statement();
10072 } else if (warning.parentheses &&
10073 true_stmt->kind == STATEMENT_IF &&
10074 true_stmt->ifs.false_statement != NULL) {
10075 warningf(&true_stmt->base.source_position,
10076 "suggest explicit braces to avoid ambiguous 'else'");
10084 * Check that all enums are handled in a switch.
10086 * @param statement the switch statement to check
10088 static void check_enum_cases(const switch_statement_t *statement) {
10089 const type_t *type = skip_typeref(statement->expression->base.type);
10090 if (! is_type_enum(type))
10092 const enum_type_t *enumt = &type->enumt;
10094 /* if we have a default, no warnings */
10095 if (statement->default_label != NULL)
10098 /* FIXME: calculation of value should be done while parsing */
10099 /* TODO: quadratic algorithm here. Change to an n log n one */
10100 long last_value = -1;
10101 const entity_t *entry = enumt->enume->base.next;
10102 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10103 entry = entry->base.next) {
10104 const expression_t *expression = entry->enum_value.value;
10105 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10106 bool found = false;
10107 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10108 if (l->expression == NULL)
10110 if (l->first_case <= value && value <= l->last_case) {
10116 warningf(&statement->base.source_position,
10117 "enumeration value '%Y' not handled in switch",
10118 entry->base.symbol);
10120 last_value = value;
10125 * Parse a switch statement.
10127 static statement_t *parse_switch(void)
10129 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10133 PUSH_PARENT(statement);
10135 expect('(', end_error);
10136 add_anchor_token(')');
10137 expression_t *const expr = parse_expression();
10138 mark_vars_read(expr, NULL);
10139 type_t * type = skip_typeref(expr->base.type);
10140 if (is_type_integer(type)) {
10141 type = promote_integer(type);
10142 if (warning.traditional) {
10143 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10144 warningf(&expr->base.source_position,
10145 "'%T' switch expression not converted to '%T' in ISO C",
10149 } else if (is_type_valid(type)) {
10150 errorf(&expr->base.source_position,
10151 "switch quantity is not an integer, but '%T'", type);
10152 type = type_error_type;
10154 statement->switchs.expression = create_implicit_cast(expr, type);
10155 expect(')', end_error);
10156 rem_anchor_token(')');
10158 switch_statement_t *rem = current_switch;
10159 current_switch = &statement->switchs;
10160 statement->switchs.body = parse_statement();
10161 current_switch = rem;
10163 if (warning.switch_default &&
10164 statement->switchs.default_label == NULL) {
10165 warningf(&statement->base.source_position, "switch has no default case");
10167 if (warning.switch_enum)
10168 check_enum_cases(&statement->switchs);
10174 return create_invalid_statement();
10177 static statement_t *parse_loop_body(statement_t *const loop)
10179 statement_t *const rem = current_loop;
10180 current_loop = loop;
10182 statement_t *const body = parse_statement();
10184 current_loop = rem;
10189 * Parse a while statement.
10191 static statement_t *parse_while(void)
10193 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10197 PUSH_PARENT(statement);
10199 expect('(', end_error);
10200 add_anchor_token(')');
10201 expression_t *const cond = parse_expression();
10202 statement->whiles.condition = cond;
10203 /* §6.8.5:2 The controlling expression of an iteration statement shall
10204 * have scalar type. */
10205 semantic_condition(cond, "condition of 'while'-statement");
10206 mark_vars_read(cond, NULL);
10207 rem_anchor_token(')');
10208 expect(')', end_error);
10210 statement->whiles.body = parse_loop_body(statement);
10216 return create_invalid_statement();
10220 * Parse a do statement.
10222 static statement_t *parse_do(void)
10224 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10228 PUSH_PARENT(statement);
10230 add_anchor_token(T_while);
10231 statement->do_while.body = parse_loop_body(statement);
10232 rem_anchor_token(T_while);
10234 expect(T_while, end_error);
10235 expect('(', end_error);
10236 add_anchor_token(')');
10237 expression_t *const cond = parse_expression();
10238 statement->do_while.condition = cond;
10239 /* §6.8.5:2 The controlling expression of an iteration statement shall
10240 * have scalar type. */
10241 semantic_condition(cond, "condition of 'do-while'-statement");
10242 mark_vars_read(cond, NULL);
10243 rem_anchor_token(')');
10244 expect(')', end_error);
10245 expect(';', end_error);
10251 return create_invalid_statement();
10255 * Parse a for statement.
10257 static statement_t *parse_for(void)
10259 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10263 expect('(', end_error1);
10264 add_anchor_token(')');
10266 PUSH_PARENT(statement);
10268 size_t const top = environment_top();
10269 scope_t *old_scope = scope_push(&statement->fors.scope);
10271 if (token.type == ';') {
10273 } else if (is_declaration_specifier(&token, false)) {
10274 parse_declaration(record_entity, DECL_FLAGS_NONE);
10276 add_anchor_token(';');
10277 expression_t *const init = parse_expression();
10278 statement->fors.initialisation = init;
10279 mark_vars_read(init, ENT_ANY);
10280 if (warning.unused_value && !expression_has_effect(init)) {
10281 warningf(&init->base.source_position,
10282 "initialisation of 'for'-statement has no effect");
10284 rem_anchor_token(';');
10285 expect(';', end_error2);
10288 if (token.type != ';') {
10289 add_anchor_token(';');
10290 expression_t *const cond = parse_expression();
10291 statement->fors.condition = cond;
10292 /* §6.8.5:2 The controlling expression of an iteration statement
10293 * shall have scalar type. */
10294 semantic_condition(cond, "condition of 'for'-statement");
10295 mark_vars_read(cond, NULL);
10296 rem_anchor_token(';');
10298 expect(';', end_error2);
10299 if (token.type != ')') {
10300 expression_t *const step = parse_expression();
10301 statement->fors.step = step;
10302 mark_vars_read(step, ENT_ANY);
10303 if (warning.unused_value && !expression_has_effect(step)) {
10304 warningf(&step->base.source_position,
10305 "step of 'for'-statement has no effect");
10308 expect(')', end_error2);
10309 rem_anchor_token(')');
10310 statement->fors.body = parse_loop_body(statement);
10312 assert(current_scope == &statement->fors.scope);
10313 scope_pop(old_scope);
10314 environment_pop_to(top);
10321 rem_anchor_token(')');
10322 assert(current_scope == &statement->fors.scope);
10323 scope_pop(old_scope);
10324 environment_pop_to(top);
10328 return create_invalid_statement();
10332 * Parse a goto statement.
10334 static statement_t *parse_goto(void)
10336 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10339 if (GNU_MODE && token.type == '*') {
10341 expression_t *expression = parse_expression();
10342 mark_vars_read(expression, NULL);
10344 /* Argh: although documentation says the expression must be of type void*,
10345 * gcc accepts anything that can be casted into void* without error */
10346 type_t *type = expression->base.type;
10348 if (type != type_error_type) {
10349 if (!is_type_pointer(type) && !is_type_integer(type)) {
10350 errorf(&expression->base.source_position,
10351 "cannot convert to a pointer type");
10352 } else if (warning.other && type != type_void_ptr) {
10353 warningf(&expression->base.source_position,
10354 "type of computed goto expression should be 'void*' not '%T'", type);
10356 expression = create_implicit_cast(expression, type_void_ptr);
10359 statement->gotos.expression = expression;
10361 if (token.type != T_IDENTIFIER) {
10363 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10365 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10366 eat_until_anchor();
10369 symbol_t *symbol = token.v.symbol;
10372 statement->gotos.label = get_label(symbol);
10375 /* remember the goto's in a list for later checking */
10376 *goto_anchor = &statement->gotos;
10377 goto_anchor = &statement->gotos.next;
10379 expect(';', end_error);
10383 return create_invalid_statement();
10387 * Parse a continue statement.
10389 static statement_t *parse_continue(void)
10391 if (current_loop == NULL) {
10392 errorf(HERE, "continue statement not within loop");
10395 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10398 expect(';', end_error);
10405 * Parse a break statement.
10407 static statement_t *parse_break(void)
10409 if (current_switch == NULL && current_loop == NULL) {
10410 errorf(HERE, "break statement not within loop or switch");
10413 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10416 expect(';', end_error);
10423 * Parse a __leave statement.
10425 static statement_t *parse_leave_statement(void)
10427 if (current_try == NULL) {
10428 errorf(HERE, "__leave statement not within __try");
10431 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10434 expect(';', end_error);
10441 * Check if a given entity represents a local variable.
10443 static bool is_local_variable(const entity_t *entity)
10445 if (entity->kind != ENTITY_VARIABLE)
10448 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10449 case STORAGE_CLASS_AUTO:
10450 case STORAGE_CLASS_REGISTER: {
10451 const type_t *type = skip_typeref(entity->declaration.type);
10452 if (is_type_function(type)) {
10464 * Check if a given expression represents a local variable.
10466 static bool expression_is_local_variable(const expression_t *expression)
10468 if (expression->base.kind != EXPR_REFERENCE) {
10471 const entity_t *entity = expression->reference.entity;
10472 return is_local_variable(entity);
10476 * Check if a given expression represents a local variable and
10477 * return its declaration then, else return NULL.
10479 entity_t *expression_is_variable(const expression_t *expression)
10481 if (expression->base.kind != EXPR_REFERENCE) {
10484 entity_t *entity = expression->reference.entity;
10485 if (entity->kind != ENTITY_VARIABLE)
10492 * Parse a return statement.
10494 static statement_t *parse_return(void)
10498 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10500 expression_t *return_value = NULL;
10501 if (token.type != ';') {
10502 return_value = parse_expression();
10503 mark_vars_read(return_value, NULL);
10506 const type_t *const func_type = skip_typeref(current_function->base.type);
10507 assert(is_type_function(func_type));
10508 type_t *const return_type = skip_typeref(func_type->function.return_type);
10510 source_position_t const *const pos = &statement->base.source_position;
10511 if (return_value != NULL) {
10512 type_t *return_value_type = skip_typeref(return_value->base.type);
10514 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10515 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10516 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10517 /* Only warn in C mode, because GCC does the same */
10518 if (c_mode & _CXX || strict_mode) {
10520 "'return' with a value, in function returning 'void'");
10521 } else if (warning.other) {
10523 "'return' with a value, in function returning 'void'");
10525 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10526 /* Only warn in C mode, because GCC does the same */
10529 "'return' with expression in function return 'void'");
10530 } else if (warning.other) {
10532 "'return' with expression in function return 'void'");
10536 assign_error_t error = semantic_assign(return_type, return_value);
10537 report_assign_error(error, return_type, return_value, "'return'",
10540 return_value = create_implicit_cast(return_value, return_type);
10541 /* check for returning address of a local var */
10542 if (warning.other && return_value != NULL
10543 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10544 const expression_t *expression = return_value->unary.value;
10545 if (expression_is_local_variable(expression)) {
10546 warningf(pos, "function returns address of local variable");
10549 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10550 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10551 if (c_mode & _CXX || strict_mode) {
10553 "'return' without value, in function returning non-void");
10556 "'return' without value, in function returning non-void");
10559 statement->returns.value = return_value;
10561 expect(';', end_error);
10568 * Parse a declaration statement.
10570 static statement_t *parse_declaration_statement(void)
10572 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10574 entity_t *before = current_scope->last_entity;
10576 parse_external_declaration();
10578 parse_declaration(record_entity, DECL_FLAGS_NONE);
10581 if (before == NULL) {
10582 statement->declaration.declarations_begin = current_scope->entities;
10584 statement->declaration.declarations_begin = before->base.next;
10586 statement->declaration.declarations_end = current_scope->last_entity;
10592 * Parse an expression statement, ie. expr ';'.
10594 static statement_t *parse_expression_statement(void)
10596 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10598 expression_t *const expr = parse_expression();
10599 statement->expression.expression = expr;
10600 mark_vars_read(expr, ENT_ANY);
10602 expect(';', end_error);
10609 * Parse a microsoft __try { } __finally { } or
10610 * __try{ } __except() { }
10612 static statement_t *parse_ms_try_statment(void)
10614 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10617 PUSH_PARENT(statement);
10619 ms_try_statement_t *rem = current_try;
10620 current_try = &statement->ms_try;
10621 statement->ms_try.try_statement = parse_compound_statement(false);
10626 if (token.type == T___except) {
10628 expect('(', end_error);
10629 add_anchor_token(')');
10630 expression_t *const expr = parse_expression();
10631 mark_vars_read(expr, NULL);
10632 type_t * type = skip_typeref(expr->base.type);
10633 if (is_type_integer(type)) {
10634 type = promote_integer(type);
10635 } else if (is_type_valid(type)) {
10636 errorf(&expr->base.source_position,
10637 "__expect expression is not an integer, but '%T'", type);
10638 type = type_error_type;
10640 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10641 rem_anchor_token(')');
10642 expect(')', end_error);
10643 statement->ms_try.final_statement = parse_compound_statement(false);
10644 } else if (token.type == T__finally) {
10646 statement->ms_try.final_statement = parse_compound_statement(false);
10648 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10649 return create_invalid_statement();
10653 return create_invalid_statement();
10656 static statement_t *parse_empty_statement(void)
10658 if (warning.empty_statement) {
10659 warningf(HERE, "statement is empty");
10661 statement_t *const statement = create_empty_statement();
10666 static statement_t *parse_local_label_declaration(void)
10668 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10672 entity_t *begin = NULL, *end = NULL;
10675 if (token.type != T_IDENTIFIER) {
10676 parse_error_expected("while parsing local label declaration",
10677 T_IDENTIFIER, NULL);
10680 symbol_t *symbol = token.v.symbol;
10681 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10682 if (entity != NULL && entity->base.parent_scope == current_scope) {
10683 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10684 symbol, &entity->base.source_position);
10686 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10688 entity->base.parent_scope = current_scope;
10689 entity->base.namespc = NAMESPACE_LABEL;
10690 entity->base.source_position = token.source_position;
10691 entity->base.symbol = symbol;
10694 end->base.next = entity;
10699 environment_push(entity);
10703 if (token.type != ',')
10709 statement->declaration.declarations_begin = begin;
10710 statement->declaration.declarations_end = end;
10714 static void parse_namespace_definition(void)
10718 entity_t *entity = NULL;
10719 symbol_t *symbol = NULL;
10721 if (token.type == T_IDENTIFIER) {
10722 symbol = token.v.symbol;
10725 entity = get_entity(symbol, NAMESPACE_NORMAL);
10726 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10727 && entity->base.parent_scope == current_scope) {
10728 error_redefined_as_different_kind(&token.source_position,
10729 entity, ENTITY_NAMESPACE);
10734 if (entity == NULL) {
10735 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10736 entity->base.symbol = symbol;
10737 entity->base.source_position = token.source_position;
10738 entity->base.namespc = NAMESPACE_NORMAL;
10739 entity->base.parent_scope = current_scope;
10742 if (token.type == '=') {
10743 /* TODO: parse namespace alias */
10744 panic("namespace alias definition not supported yet");
10747 environment_push(entity);
10748 append_entity(current_scope, entity);
10750 size_t const top = environment_top();
10751 scope_t *old_scope = scope_push(&entity->namespacee.members);
10753 expect('{', end_error);
10755 expect('}', end_error);
10758 assert(current_scope == &entity->namespacee.members);
10759 scope_pop(old_scope);
10760 environment_pop_to(top);
10764 * Parse a statement.
10765 * There's also parse_statement() which additionally checks for
10766 * "statement has no effect" warnings
10768 static statement_t *intern_parse_statement(void)
10770 statement_t *statement = NULL;
10772 /* declaration or statement */
10773 add_anchor_token(';');
10774 switch (token.type) {
10775 case T_IDENTIFIER: {
10776 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10777 if (la1_type == ':') {
10778 statement = parse_label_statement();
10779 } else if (is_typedef_symbol(token.v.symbol)) {
10780 statement = parse_declaration_statement();
10782 /* it's an identifier, the grammar says this must be an
10783 * expression statement. However it is common that users mistype
10784 * declaration types, so we guess a bit here to improve robustness
10785 * for incorrect programs */
10786 switch (la1_type) {
10789 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10790 goto expression_statment;
10795 statement = parse_declaration_statement();
10799 expression_statment:
10800 statement = parse_expression_statement();
10807 case T___extension__:
10808 /* This can be a prefix to a declaration or an expression statement.
10809 * We simply eat it now and parse the rest with tail recursion. */
10812 } while (token.type == T___extension__);
10813 bool old_gcc_extension = in_gcc_extension;
10814 in_gcc_extension = true;
10815 statement = intern_parse_statement();
10816 in_gcc_extension = old_gcc_extension;
10820 statement = parse_declaration_statement();
10824 statement = parse_local_label_declaration();
10827 case ';': statement = parse_empty_statement(); break;
10828 case '{': statement = parse_compound_statement(false); break;
10829 case T___leave: statement = parse_leave_statement(); break;
10830 case T___try: statement = parse_ms_try_statment(); break;
10831 case T_asm: statement = parse_asm_statement(); break;
10832 case T_break: statement = parse_break(); break;
10833 case T_case: statement = parse_case_statement(); break;
10834 case T_continue: statement = parse_continue(); break;
10835 case T_default: statement = parse_default_statement(); break;
10836 case T_do: statement = parse_do(); break;
10837 case T_for: statement = parse_for(); break;
10838 case T_goto: statement = parse_goto(); break;
10839 case T_if: statement = parse_if(); break;
10840 case T_return: statement = parse_return(); break;
10841 case T_switch: statement = parse_switch(); break;
10842 case T_while: statement = parse_while(); break;
10845 statement = parse_expression_statement();
10849 errorf(HERE, "unexpected token %K while parsing statement", &token);
10850 statement = create_invalid_statement();
10855 rem_anchor_token(';');
10857 assert(statement != NULL
10858 && statement->base.source_position.input_name != NULL);
10864 * parse a statement and emits "statement has no effect" warning if needed
10865 * (This is really a wrapper around intern_parse_statement with check for 1
10866 * single warning. It is needed, because for statement expressions we have
10867 * to avoid the warning on the last statement)
10869 static statement_t *parse_statement(void)
10871 statement_t *statement = intern_parse_statement();
10873 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10874 expression_t *expression = statement->expression.expression;
10875 if (!expression_has_effect(expression)) {
10876 warningf(&expression->base.source_position,
10877 "statement has no effect");
10885 * Parse a compound statement.
10887 static statement_t *parse_compound_statement(bool inside_expression_statement)
10889 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10891 PUSH_PARENT(statement);
10894 add_anchor_token('}');
10895 /* tokens, which can start a statement */
10896 /* TODO MS, __builtin_FOO */
10897 add_anchor_token('!');
10898 add_anchor_token('&');
10899 add_anchor_token('(');
10900 add_anchor_token('*');
10901 add_anchor_token('+');
10902 add_anchor_token('-');
10903 add_anchor_token('{');
10904 add_anchor_token('~');
10905 add_anchor_token(T_CHARACTER_CONSTANT);
10906 add_anchor_token(T_COLONCOLON);
10907 add_anchor_token(T_FLOATINGPOINT);
10908 add_anchor_token(T_IDENTIFIER);
10909 add_anchor_token(T_INTEGER);
10910 add_anchor_token(T_MINUSMINUS);
10911 add_anchor_token(T_PLUSPLUS);
10912 add_anchor_token(T_STRING_LITERAL);
10913 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10914 add_anchor_token(T_WIDE_STRING_LITERAL);
10915 add_anchor_token(T__Bool);
10916 add_anchor_token(T__Complex);
10917 add_anchor_token(T__Imaginary);
10918 add_anchor_token(T___FUNCTION__);
10919 add_anchor_token(T___PRETTY_FUNCTION__);
10920 add_anchor_token(T___alignof__);
10921 add_anchor_token(T___attribute__);
10922 add_anchor_token(T___builtin_va_start);
10923 add_anchor_token(T___extension__);
10924 add_anchor_token(T___func__);
10925 add_anchor_token(T___imag__);
10926 add_anchor_token(T___label__);
10927 add_anchor_token(T___real__);
10928 add_anchor_token(T___thread);
10929 add_anchor_token(T_asm);
10930 add_anchor_token(T_auto);
10931 add_anchor_token(T_bool);
10932 add_anchor_token(T_break);
10933 add_anchor_token(T_case);
10934 add_anchor_token(T_char);
10935 add_anchor_token(T_class);
10936 add_anchor_token(T_const);
10937 add_anchor_token(T_const_cast);
10938 add_anchor_token(T_continue);
10939 add_anchor_token(T_default);
10940 add_anchor_token(T_delete);
10941 add_anchor_token(T_double);
10942 add_anchor_token(T_do);
10943 add_anchor_token(T_dynamic_cast);
10944 add_anchor_token(T_enum);
10945 add_anchor_token(T_extern);
10946 add_anchor_token(T_false);
10947 add_anchor_token(T_float);
10948 add_anchor_token(T_for);
10949 add_anchor_token(T_goto);
10950 add_anchor_token(T_if);
10951 add_anchor_token(T_inline);
10952 add_anchor_token(T_int);
10953 add_anchor_token(T_long);
10954 add_anchor_token(T_new);
10955 add_anchor_token(T_operator);
10956 add_anchor_token(T_register);
10957 add_anchor_token(T_reinterpret_cast);
10958 add_anchor_token(T_restrict);
10959 add_anchor_token(T_return);
10960 add_anchor_token(T_short);
10961 add_anchor_token(T_signed);
10962 add_anchor_token(T_sizeof);
10963 add_anchor_token(T_static);
10964 add_anchor_token(T_static_cast);
10965 add_anchor_token(T_struct);
10966 add_anchor_token(T_switch);
10967 add_anchor_token(T_template);
10968 add_anchor_token(T_this);
10969 add_anchor_token(T_throw);
10970 add_anchor_token(T_true);
10971 add_anchor_token(T_try);
10972 add_anchor_token(T_typedef);
10973 add_anchor_token(T_typeid);
10974 add_anchor_token(T_typename);
10975 add_anchor_token(T_typeof);
10976 add_anchor_token(T_union);
10977 add_anchor_token(T_unsigned);
10978 add_anchor_token(T_using);
10979 add_anchor_token(T_void);
10980 add_anchor_token(T_volatile);
10981 add_anchor_token(T_wchar_t);
10982 add_anchor_token(T_while);
10984 size_t const top = environment_top();
10985 scope_t *old_scope = scope_push(&statement->compound.scope);
10987 statement_t **anchor = &statement->compound.statements;
10988 bool only_decls_so_far = true;
10989 while (token.type != '}') {
10990 if (token.type == T_EOF) {
10991 errorf(&statement->base.source_position,
10992 "EOF while parsing compound statement");
10995 statement_t *sub_statement = intern_parse_statement();
10996 if (is_invalid_statement(sub_statement)) {
10997 /* an error occurred. if we are at an anchor, return */
11003 if (warning.declaration_after_statement) {
11004 if (sub_statement->kind != STATEMENT_DECLARATION) {
11005 only_decls_so_far = false;
11006 } else if (!only_decls_so_far) {
11007 warningf(&sub_statement->base.source_position,
11008 "ISO C90 forbids mixed declarations and code");
11012 *anchor = sub_statement;
11014 while (sub_statement->base.next != NULL)
11015 sub_statement = sub_statement->base.next;
11017 anchor = &sub_statement->base.next;
11021 /* look over all statements again to produce no effect warnings */
11022 if (warning.unused_value) {
11023 statement_t *sub_statement = statement->compound.statements;
11024 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11025 if (sub_statement->kind != STATEMENT_EXPRESSION)
11027 /* don't emit a warning for the last expression in an expression
11028 * statement as it has always an effect */
11029 if (inside_expression_statement && sub_statement->base.next == NULL)
11032 expression_t *expression = sub_statement->expression.expression;
11033 if (!expression_has_effect(expression)) {
11034 warningf(&expression->base.source_position,
11035 "statement has no effect");
11041 rem_anchor_token(T_while);
11042 rem_anchor_token(T_wchar_t);
11043 rem_anchor_token(T_volatile);
11044 rem_anchor_token(T_void);
11045 rem_anchor_token(T_using);
11046 rem_anchor_token(T_unsigned);
11047 rem_anchor_token(T_union);
11048 rem_anchor_token(T_typeof);
11049 rem_anchor_token(T_typename);
11050 rem_anchor_token(T_typeid);
11051 rem_anchor_token(T_typedef);
11052 rem_anchor_token(T_try);
11053 rem_anchor_token(T_true);
11054 rem_anchor_token(T_throw);
11055 rem_anchor_token(T_this);
11056 rem_anchor_token(T_template);
11057 rem_anchor_token(T_switch);
11058 rem_anchor_token(T_struct);
11059 rem_anchor_token(T_static_cast);
11060 rem_anchor_token(T_static);
11061 rem_anchor_token(T_sizeof);
11062 rem_anchor_token(T_signed);
11063 rem_anchor_token(T_short);
11064 rem_anchor_token(T_return);
11065 rem_anchor_token(T_restrict);
11066 rem_anchor_token(T_reinterpret_cast);
11067 rem_anchor_token(T_register);
11068 rem_anchor_token(T_operator);
11069 rem_anchor_token(T_new);
11070 rem_anchor_token(T_long);
11071 rem_anchor_token(T_int);
11072 rem_anchor_token(T_inline);
11073 rem_anchor_token(T_if);
11074 rem_anchor_token(T_goto);
11075 rem_anchor_token(T_for);
11076 rem_anchor_token(T_float);
11077 rem_anchor_token(T_false);
11078 rem_anchor_token(T_extern);
11079 rem_anchor_token(T_enum);
11080 rem_anchor_token(T_dynamic_cast);
11081 rem_anchor_token(T_do);
11082 rem_anchor_token(T_double);
11083 rem_anchor_token(T_delete);
11084 rem_anchor_token(T_default);
11085 rem_anchor_token(T_continue);
11086 rem_anchor_token(T_const_cast);
11087 rem_anchor_token(T_const);
11088 rem_anchor_token(T_class);
11089 rem_anchor_token(T_char);
11090 rem_anchor_token(T_case);
11091 rem_anchor_token(T_break);
11092 rem_anchor_token(T_bool);
11093 rem_anchor_token(T_auto);
11094 rem_anchor_token(T_asm);
11095 rem_anchor_token(T___thread);
11096 rem_anchor_token(T___real__);
11097 rem_anchor_token(T___label__);
11098 rem_anchor_token(T___imag__);
11099 rem_anchor_token(T___func__);
11100 rem_anchor_token(T___extension__);
11101 rem_anchor_token(T___builtin_va_start);
11102 rem_anchor_token(T___attribute__);
11103 rem_anchor_token(T___alignof__);
11104 rem_anchor_token(T___PRETTY_FUNCTION__);
11105 rem_anchor_token(T___FUNCTION__);
11106 rem_anchor_token(T__Imaginary);
11107 rem_anchor_token(T__Complex);
11108 rem_anchor_token(T__Bool);
11109 rem_anchor_token(T_WIDE_STRING_LITERAL);
11110 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11111 rem_anchor_token(T_STRING_LITERAL);
11112 rem_anchor_token(T_PLUSPLUS);
11113 rem_anchor_token(T_MINUSMINUS);
11114 rem_anchor_token(T_INTEGER);
11115 rem_anchor_token(T_IDENTIFIER);
11116 rem_anchor_token(T_FLOATINGPOINT);
11117 rem_anchor_token(T_COLONCOLON);
11118 rem_anchor_token(T_CHARACTER_CONSTANT);
11119 rem_anchor_token('~');
11120 rem_anchor_token('{');
11121 rem_anchor_token('-');
11122 rem_anchor_token('+');
11123 rem_anchor_token('*');
11124 rem_anchor_token('(');
11125 rem_anchor_token('&');
11126 rem_anchor_token('!');
11127 rem_anchor_token('}');
11128 assert(current_scope == &statement->compound.scope);
11129 scope_pop(old_scope);
11130 environment_pop_to(top);
11137 * Check for unused global static functions and variables
11139 static void check_unused_globals(void)
11141 if (!warning.unused_function && !warning.unused_variable)
11144 for (const entity_t *entity = file_scope->entities; entity != NULL;
11145 entity = entity->base.next) {
11146 if (!is_declaration(entity))
11149 const declaration_t *declaration = &entity->declaration;
11150 if (declaration->used ||
11151 declaration->modifiers & DM_UNUSED ||
11152 declaration->modifiers & DM_USED ||
11153 declaration->storage_class != STORAGE_CLASS_STATIC)
11156 type_t *const type = declaration->type;
11158 if (entity->kind == ENTITY_FUNCTION) {
11159 /* inhibit warning for static inline functions */
11160 if (entity->function.is_inline)
11163 s = entity->function.statement != NULL ? "defined" : "declared";
11168 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11169 type, declaration->base.symbol, s);
11173 static void parse_global_asm(void)
11175 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11178 expect('(', end_error);
11180 statement->asms.asm_text = parse_string_literals();
11181 statement->base.next = unit->global_asm;
11182 unit->global_asm = statement;
11184 expect(')', end_error);
11185 expect(';', end_error);
11190 static void parse_linkage_specification(void)
11193 assert(token.type == T_STRING_LITERAL);
11195 const char *linkage = parse_string_literals().begin;
11197 linkage_kind_t old_linkage = current_linkage;
11198 linkage_kind_t new_linkage;
11199 if (strcmp(linkage, "C") == 0) {
11200 new_linkage = LINKAGE_C;
11201 } else if (strcmp(linkage, "C++") == 0) {
11202 new_linkage = LINKAGE_CXX;
11204 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11205 new_linkage = LINKAGE_INVALID;
11207 current_linkage = new_linkage;
11209 if (token.type == '{') {
11212 expect('}', end_error);
11218 assert(current_linkage == new_linkage);
11219 current_linkage = old_linkage;
11222 static void parse_external(void)
11224 switch (token.type) {
11225 DECLARATION_START_NO_EXTERN
11227 case T___extension__:
11228 /* tokens below are for implicit int */
11229 case '&': /* & x; -> int& x; (and error later, because C++ has no
11231 case '*': /* * x; -> int* x; */
11232 case '(': /* (x); -> int (x); */
11233 parse_external_declaration();
11237 if (look_ahead(1)->type == T_STRING_LITERAL) {
11238 parse_linkage_specification();
11240 parse_external_declaration();
11245 parse_global_asm();
11249 parse_namespace_definition();
11253 if (!strict_mode) {
11255 warningf(HERE, "stray ';' outside of function");
11262 errorf(HERE, "stray %K outside of function", &token);
11263 if (token.type == '(' || token.type == '{' || token.type == '[')
11264 eat_until_matching_token(token.type);
11270 static void parse_externals(void)
11272 add_anchor_token('}');
11273 add_anchor_token(T_EOF);
11276 unsigned char token_anchor_copy[T_LAST_TOKEN];
11277 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11280 while (token.type != T_EOF && token.type != '}') {
11282 bool anchor_leak = false;
11283 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11284 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11286 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11287 anchor_leak = true;
11290 if (in_gcc_extension) {
11291 errorf(HERE, "Leaked __extension__");
11292 anchor_leak = true;
11302 rem_anchor_token(T_EOF);
11303 rem_anchor_token('}');
11307 * Parse a translation unit.
11309 static void parse_translation_unit(void)
11311 add_anchor_token(T_EOF);
11316 if (token.type == T_EOF)
11319 errorf(HERE, "stray %K outside of function", &token);
11320 if (token.type == '(' || token.type == '{' || token.type == '[')
11321 eat_until_matching_token(token.type);
11329 * @return the translation unit or NULL if errors occurred.
11331 void start_parsing(void)
11333 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11334 label_stack = NEW_ARR_F(stack_entry_t, 0);
11335 diagnostic_count = 0;
11339 type_set_output(stderr);
11340 ast_set_output(stderr);
11342 assert(unit == NULL);
11343 unit = allocate_ast_zero(sizeof(unit[0]));
11345 assert(file_scope == NULL);
11346 file_scope = &unit->scope;
11348 assert(current_scope == NULL);
11349 scope_push(&unit->scope);
11352 translation_unit_t *finish_parsing(void)
11354 assert(current_scope == &unit->scope);
11357 assert(file_scope == &unit->scope);
11358 check_unused_globals();
11361 DEL_ARR_F(environment_stack);
11362 DEL_ARR_F(label_stack);
11364 translation_unit_t *result = unit;
11369 /* GCC allows global arrays without size and assigns them a length of one,
11370 * if no different declaration follows */
11371 static void complete_incomplete_arrays(void)
11373 size_t n = ARR_LEN(incomplete_arrays);
11374 for (size_t i = 0; i != n; ++i) {
11375 declaration_t *const decl = incomplete_arrays[i];
11376 type_t *const orig_type = decl->type;
11377 type_t *const type = skip_typeref(orig_type);
11379 if (!is_type_incomplete(type))
11382 if (warning.other) {
11383 warningf(&decl->base.source_position,
11384 "array '%#T' assumed to have one element",
11385 orig_type, decl->base.symbol);
11388 type_t *const new_type = duplicate_type(type);
11389 new_type->array.size_constant = true;
11390 new_type->array.has_implicit_size = true;
11391 new_type->array.size = 1;
11393 type_t *const result = identify_new_type(new_type);
11395 decl->type = result;
11401 lookahead_bufpos = 0;
11402 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11405 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11406 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11407 parse_translation_unit();
11408 complete_incomplete_arrays();
11409 DEL_ARR_F(incomplete_arrays);
11410 incomplete_arrays = NULL;
11414 * Initialize the parser.
11416 void init_parser(void)
11418 sym_anonymous = symbol_table_insert("<anonymous>");
11420 if (c_mode & _MS) {
11421 /* add predefined symbols for extended-decl-modifier */
11422 sym_align = symbol_table_insert("align");
11423 sym_allocate = symbol_table_insert("allocate");
11424 sym_dllimport = symbol_table_insert("dllimport");
11425 sym_dllexport = symbol_table_insert("dllexport");
11426 sym_naked = symbol_table_insert("naked");
11427 sym_noinline = symbol_table_insert("noinline");
11428 sym_returns_twice = symbol_table_insert("returns_twice");
11429 sym_noreturn = symbol_table_insert("noreturn");
11430 sym_nothrow = symbol_table_insert("nothrow");
11431 sym_novtable = symbol_table_insert("novtable");
11432 sym_property = symbol_table_insert("property");
11433 sym_get = symbol_table_insert("get");
11434 sym_put = symbol_table_insert("put");
11435 sym_selectany = symbol_table_insert("selectany");
11436 sym_thread = symbol_table_insert("thread");
11437 sym_uuid = symbol_table_insert("uuid");
11438 sym_deprecated = symbol_table_insert("deprecated");
11439 sym_restrict = symbol_table_insert("restrict");
11440 sym_noalias = symbol_table_insert("noalias");
11442 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11444 init_expression_parsers();
11445 obstack_init(&temp_obst);
11447 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11448 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11452 * Terminate the parser.
11454 void exit_parser(void)
11456 obstack_free(&temp_obst, NULL);