2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 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
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_CURRENT_ENTITY(entity) \
113 entity_t *const new_current_entity = (entity); \
114 entity_t *const old_current_entity = current_entity; \
115 ((void)(current_entity = new_current_entity))
116 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
118 #define PUSH_PARENT(stmt) \
119 statement_t *const new_parent = (stmt); \
120 statement_t *const old_parent = current_parent; \
121 ((void)(current_parent = new_parent))
122 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
124 #define PUSH_SCOPE(scope) \
125 size_t const top = environment_top(); \
126 scope_t *const new_scope = (scope); \
127 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
128 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
129 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
131 #define PUSH_EXTENSION() \
133 bool const old_gcc_extension = in_gcc_extension; \
134 while (next_if(T___extension__)) { \
135 in_gcc_extension = true; \
138 #define POP_EXTENSION() \
139 ((void)(in_gcc_extension = old_gcc_extension))
141 /** special symbol used for anonymous entities. */
142 static symbol_t *sym_anonymous = NULL;
144 /** The token anchor set */
145 static unsigned short token_anchor_set[T_LAST_TOKEN];
147 /** The current source position. */
148 #define HERE (&token.base.source_position)
150 /** true if we are in GCC mode. */
151 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
153 static statement_t *parse_compound_statement(bool inside_expression_statement);
154 static statement_t *parse_statement(void);
156 static expression_t *parse_subexpression(precedence_t);
157 static expression_t *parse_expression(void);
158 static type_t *parse_typename(void);
159 static void parse_externals(void);
160 static void parse_external(void);
162 static void parse_compound_type_entries(compound_t *compound_declaration);
164 static void check_call_argument(type_t *expected_type,
165 call_argument_t *argument, unsigned pos);
167 typedef enum declarator_flags_t {
169 DECL_MAY_BE_ABSTRACT = 1U << 0,
170 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
171 DECL_IS_PARAMETER = 1U << 2
172 } declarator_flags_t;
174 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
175 declarator_flags_t flags);
177 static void semantic_comparison(binary_expression_t *expression);
179 #define STORAGE_CLASSES \
180 STORAGE_CLASSES_NO_EXTERN \
183 #define STORAGE_CLASSES_NO_EXTERN \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #define COMPLEX_SPECIFIERS \
200 #define IMAGINARY_SPECIFIERS \
203 #define TYPE_SPECIFIERS \
205 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define DECLARATION_START_NO_EXTERN \
236 STORAGE_CLASSES_NO_EXTERN \
240 #define EXPRESSION_START \
249 case T_CHARACTER_CONSTANT: \
250 case T_FLOATINGPOINT: \
254 case T_STRING_LITERAL: \
255 case T___FUNCDNAME__: \
256 case T___FUNCSIG__: \
257 case T___FUNCTION__: \
258 case T___PRETTY_FUNCTION__: \
259 case T___alignof__: \
260 case T___builtin_classify_type: \
261 case T___builtin_constant_p: \
262 case T___builtin_isgreater: \
263 case T___builtin_isgreaterequal: \
264 case T___builtin_isless: \
265 case T___builtin_islessequal: \
266 case T___builtin_islessgreater: \
267 case T___builtin_isunordered: \
268 case T___builtin_offsetof: \
269 case T___builtin_va_arg: \
270 case T___builtin_va_copy: \
271 case T___builtin_va_start: \
282 * Returns the size of a statement node.
284 * @param kind the statement kind
286 static size_t get_statement_struct_size(statement_kind_t kind)
288 static const size_t sizes[] = {
289 [STATEMENT_ERROR] = sizeof(statement_base_t),
290 [STATEMENT_EMPTY] = sizeof(statement_base_t),
291 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
292 [STATEMENT_RETURN] = sizeof(return_statement_t),
293 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
294 [STATEMENT_IF] = sizeof(if_statement_t),
295 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
296 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
297 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
298 [STATEMENT_BREAK] = sizeof(statement_base_t),
299 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
300 [STATEMENT_GOTO] = sizeof(goto_statement_t),
301 [STATEMENT_LABEL] = sizeof(label_statement_t),
302 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
303 [STATEMENT_WHILE] = sizeof(while_statement_t),
304 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
305 [STATEMENT_FOR] = sizeof(for_statement_t),
306 [STATEMENT_ASM] = sizeof(asm_statement_t),
307 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
308 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
310 assert((size_t)kind < lengthof(sizes));
311 assert(sizes[kind] != 0);
316 * Returns the size of an expression node.
318 * @param kind the expression kind
320 static size_t get_expression_struct_size(expression_kind_t kind)
322 static const size_t sizes[] = {
323 [EXPR_ERROR] = sizeof(expression_base_t),
324 [EXPR_REFERENCE] = sizeof(reference_expression_t),
325 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
326 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
331 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
332 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
333 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
334 [EXPR_CALL] = sizeof(call_expression_t),
335 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
336 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
337 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
338 [EXPR_SELECT] = sizeof(select_expression_t),
339 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
340 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
341 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
342 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
343 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
344 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
345 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
346 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
347 [EXPR_VA_START] = sizeof(va_start_expression_t),
348 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
349 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
350 [EXPR_STATEMENT] = sizeof(statement_expression_t),
351 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
353 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
354 return sizes[EXPR_UNARY_FIRST];
356 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
357 return sizes[EXPR_BINARY_FIRST];
359 assert((size_t)kind < lengthof(sizes));
360 assert(sizes[kind] != 0);
365 * Allocate a statement node of given kind and initialize all
366 * fields with zero. Sets its source position to the position
367 * of the current token.
369 static statement_t *allocate_statement_zero(statement_kind_t kind)
371 size_t size = get_statement_struct_size(kind);
372 statement_t *res = allocate_ast_zero(size);
374 res->base.kind = kind;
375 res->base.parent = current_parent;
376 res->base.source_position = *HERE;
381 * Allocate an expression node of given kind and initialize all
384 * @param kind the kind of the expression to allocate
386 static expression_t *allocate_expression_zero(expression_kind_t kind)
388 size_t size = get_expression_struct_size(kind);
389 expression_t *res = allocate_ast_zero(size);
391 res->base.kind = kind;
392 res->base.type = type_error_type;
393 res->base.source_position = *HERE;
398 * Creates a new invalid expression at the source position
399 * of the current token.
401 static expression_t *create_error_expression(void)
403 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
404 expression->base.type = type_error_type;
409 * Creates a new invalid statement.
411 static statement_t *create_error_statement(void)
413 return allocate_statement_zero(STATEMENT_ERROR);
417 * Allocate a new empty statement.
419 static statement_t *create_empty_statement(void)
421 return allocate_statement_zero(STATEMENT_EMPTY);
425 * Returns the size of an initializer node.
427 * @param kind the initializer kind
429 static size_t get_initializer_size(initializer_kind_t kind)
431 static const size_t sizes[] = {
432 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
433 [INITIALIZER_STRING] = sizeof(initializer_string_t),
434 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
435 [INITIALIZER_LIST] = sizeof(initializer_list_t),
436 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
438 assert((size_t)kind < lengthof(sizes));
439 assert(sizes[kind] != 0);
444 * Allocate an initializer node of given kind and initialize all
447 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
449 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
456 * Returns the index of the top element of the environment stack.
458 static size_t environment_top(void)
460 return ARR_LEN(environment_stack);
464 * Returns the index of the top element of the global label stack.
466 static size_t label_top(void)
468 return ARR_LEN(label_stack);
472 * Return the next token.
474 static inline void next_token(void)
476 token = lookahead_buffer[lookahead_bufpos];
477 lookahead_buffer[lookahead_bufpos] = lexer_token;
480 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
483 print_token(stderr, &token);
484 fprintf(stderr, "\n");
488 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
490 static inline bool next_if(token_kind_t const type)
492 if (token.kind == type) {
501 * Return the next token with a given lookahead.
503 static inline const token_t *look_ahead(size_t num)
505 assert(0 < num && num <= MAX_LOOKAHEAD);
506 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
507 return &lookahead_buffer[pos];
511 * Adds a token type to the token type anchor set (a multi-set).
513 static void add_anchor_token(token_kind_t const token_kind)
515 assert(token_kind < T_LAST_TOKEN);
516 ++token_anchor_set[token_kind];
520 * Remove a token type from the token type anchor set (a multi-set).
522 static void rem_anchor_token(token_kind_t const token_kind)
524 assert(token_kind < T_LAST_TOKEN);
525 assert(token_anchor_set[token_kind] != 0);
526 --token_anchor_set[token_kind];
530 * Eat tokens until a matching token type is found.
532 static void eat_until_matching_token(token_kind_t const type)
534 token_kind_t end_token;
536 case '(': end_token = ')'; break;
537 case '{': end_token = '}'; break;
538 case '[': end_token = ']'; break;
539 default: end_token = type; break;
542 unsigned parenthesis_count = 0;
543 unsigned brace_count = 0;
544 unsigned bracket_count = 0;
545 while (token.kind != end_token ||
546 parenthesis_count != 0 ||
548 bracket_count != 0) {
549 switch (token.kind) {
551 case '(': ++parenthesis_count; break;
552 case '{': ++brace_count; break;
553 case '[': ++bracket_count; break;
556 if (parenthesis_count > 0)
566 if (bracket_count > 0)
569 if (token.kind == end_token &&
570 parenthesis_count == 0 &&
584 * Eat input tokens until an anchor is found.
586 static void eat_until_anchor(void)
588 while (token_anchor_set[token.kind] == 0) {
589 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
590 eat_until_matching_token(token.kind);
596 * Eat a whole block from input tokens.
598 static void eat_block(void)
600 eat_until_matching_token('{');
605 * Report a parse error because an expected token was not found.
608 #if defined __GNUC__ && __GNUC__ >= 4
609 __attribute__((sentinel))
611 void parse_error_expected(const char *message, ...)
613 if (message != NULL) {
614 errorf(HERE, "%s", message);
617 va_start(ap, message);
618 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
623 * Report an incompatible type.
625 static void type_error_incompatible(const char *msg,
626 const source_position_t *source_position, type_t *type1, type_t *type2)
628 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
633 * Expect the current token is the expected token.
634 * If not, generate an error and skip until the next anchor.
636 static void expect(token_kind_t const expected)
638 if (UNLIKELY(token.kind != expected)) {
639 parse_error_expected(NULL, expected, NULL);
640 add_anchor_token(expected);
642 rem_anchor_token(expected);
643 if (token.kind != expected)
649 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
651 if (token.kind != T_IDENTIFIER) {
652 parse_error_expected(context, T_IDENTIFIER, NULL);
653 add_anchor_token(T_IDENTIFIER);
655 rem_anchor_token(T_IDENTIFIER);
656 if (token.kind != T_IDENTIFIER)
659 symbol_t *const sym = token.base.symbol;
667 * Push a given scope on the scope stack and make it the
670 static scope_t *scope_push(scope_t *new_scope)
672 if (current_scope != NULL) {
673 new_scope->depth = current_scope->depth + 1;
676 scope_t *old_scope = current_scope;
677 current_scope = new_scope;
682 * Pop the current scope from the scope stack.
684 static void scope_pop(scope_t *old_scope)
686 current_scope = old_scope;
690 * Search an entity by its symbol in a given namespace.
692 static entity_t *get_entity(const symbol_t *const symbol,
693 namespace_tag_t namespc)
695 entity_t *entity = symbol->entity;
696 for (; entity != NULL; entity = entity->base.symbol_next) {
697 if ((namespace_tag_t)entity->base.namespc == namespc)
704 /* §6.2.3:1 24) There is only one name space for tags even though three are
706 static entity_t *get_tag(symbol_t const *const symbol,
707 entity_kind_tag_t const kind)
709 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
710 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
712 "'%Y' defined as wrong kind of tag (previous definition %P)",
713 symbol, &entity->base.source_position);
720 * pushs an entity on the environment stack and links the corresponding symbol
723 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
725 symbol_t *symbol = entity->base.symbol;
726 entity_namespace_t namespc = entity->base.namespc;
727 assert(namespc != 0);
729 /* replace/add entity into entity list of the symbol */
732 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
737 /* replace an entry? */
738 if (iter->base.namespc == namespc) {
739 entity->base.symbol_next = iter->base.symbol_next;
745 /* remember old declaration */
747 entry.symbol = symbol;
748 entry.old_entity = iter;
749 entry.namespc = namespc;
750 ARR_APP1(stack_entry_t, *stack_ptr, entry);
754 * Push an entity on the environment stack.
756 static void environment_push(entity_t *entity)
758 assert(entity->base.source_position.input_name != NULL);
759 assert(entity->base.parent_scope != NULL);
760 stack_push(&environment_stack, entity);
764 * Push a declaration on the global label stack.
766 * @param declaration the declaration
768 static void label_push(entity_t *label)
770 /* we abuse the parameters scope as parent for the labels */
771 label->base.parent_scope = ¤t_function->parameters;
772 stack_push(&label_stack, label);
776 * pops symbols from the environment stack until @p new_top is the top element
778 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
780 stack_entry_t *stack = *stack_ptr;
781 size_t top = ARR_LEN(stack);
784 assert(new_top <= top);
788 for (i = top; i > new_top; --i) {
789 stack_entry_t *entry = &stack[i - 1];
791 entity_t *old_entity = entry->old_entity;
792 symbol_t *symbol = entry->symbol;
793 entity_namespace_t namespc = entry->namespc;
795 /* replace with old_entity/remove */
798 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
800 assert(iter != NULL);
801 /* replace an entry? */
802 if (iter->base.namespc == namespc)
806 /* restore definition from outer scopes (if there was one) */
807 if (old_entity != NULL) {
808 old_entity->base.symbol_next = iter->base.symbol_next;
809 *anchor = old_entity;
811 /* remove entry from list */
812 *anchor = iter->base.symbol_next;
816 ARR_SHRINKLEN(*stack_ptr, new_top);
820 * Pop all entries from the environment stack until the new_top
823 * @param new_top the new stack top
825 static void environment_pop_to(size_t new_top)
827 stack_pop_to(&environment_stack, new_top);
831 * Pop all entries from the global label stack until the new_top
834 * @param new_top the new stack top
836 static void label_pop_to(size_t new_top)
838 stack_pop_to(&label_stack, new_top);
841 static atomic_type_kind_t get_akind(const type_t *type)
843 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
844 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
845 return type->atomic.akind;
849 * §6.3.1.1:2 Do integer promotion for a given type.
851 * @param type the type to promote
852 * @return the promoted type
854 static type_t *promote_integer(type_t *type)
856 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
863 * Check if a given expression represents a null pointer constant.
865 * @param expression the expression to check
867 static bool is_null_pointer_constant(const expression_t *expression)
869 /* skip void* cast */
870 if (expression->kind == EXPR_UNARY_CAST) {
871 type_t *const type = skip_typeref(expression->base.type);
872 if (types_compatible(type, type_void_ptr))
873 expression = expression->unary.value;
876 type_t *const type = skip_typeref(expression->base.type);
877 if (!is_type_integer(type))
879 switch (is_constant_expression(expression)) {
880 case EXPR_CLASS_ERROR: return true;
881 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
882 default: return false;
887 * Create an implicit cast expression.
889 * @param expression the expression to cast
890 * @param dest_type the destination type
892 static expression_t *create_implicit_cast(expression_t *expression,
895 type_t *const source_type = expression->base.type;
897 if (source_type == dest_type)
900 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
901 cast->unary.value = expression;
902 cast->base.type = dest_type;
903 cast->base.implicit = true;
908 typedef enum assign_error_t {
910 ASSIGN_ERROR_INCOMPATIBLE,
911 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
912 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
913 ASSIGN_WARNING_POINTER_FROM_INT,
914 ASSIGN_WARNING_INT_FROM_POINTER
917 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, source_position_t const *const pos)
919 type_t *const orig_type_right = right->base.type;
920 type_t *const type_left = skip_typeref(orig_type_left);
921 type_t *const type_right = skip_typeref(orig_type_right);
926 case ASSIGN_ERROR_INCOMPATIBLE:
927 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
930 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
931 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
932 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
934 /* the left type has all qualifiers from the right type */
935 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
936 warningf(WARN_OTHER, pos, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type", orig_type_left, context, orig_type_right, missing_qualifiers);
940 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
941 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
944 case ASSIGN_WARNING_POINTER_FROM_INT:
945 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
948 case ASSIGN_WARNING_INT_FROM_POINTER:
949 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
953 panic("invalid error value");
957 /** Implements the rules from §6.5.16.1 */
958 static assign_error_t semantic_assign(type_t *orig_type_left,
959 const expression_t *const right)
961 type_t *const orig_type_right = right->base.type;
962 type_t *const type_left = skip_typeref(orig_type_left);
963 type_t *const type_right = skip_typeref(orig_type_right);
965 if (is_type_pointer(type_left)) {
966 if (is_null_pointer_constant(right)) {
967 return ASSIGN_SUCCESS;
968 } else if (is_type_pointer(type_right)) {
969 type_t *points_to_left
970 = skip_typeref(type_left->pointer.points_to);
971 type_t *points_to_right
972 = skip_typeref(type_right->pointer.points_to);
973 assign_error_t res = ASSIGN_SUCCESS;
975 /* the left type has all qualifiers from the right type */
976 unsigned missing_qualifiers
977 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
978 if (missing_qualifiers != 0) {
979 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
982 points_to_left = get_unqualified_type(points_to_left);
983 points_to_right = get_unqualified_type(points_to_right);
985 if (is_type_void(points_to_left))
988 if (is_type_void(points_to_right)) {
989 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
990 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
993 if (!types_compatible(points_to_left, points_to_right)) {
994 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
998 } else if (is_type_integer(type_right)) {
999 return ASSIGN_WARNING_POINTER_FROM_INT;
1001 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1002 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1003 && is_type_pointer(type_right))) {
1004 return ASSIGN_SUCCESS;
1005 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1006 type_t *const unqual_type_left = get_unqualified_type(type_left);
1007 type_t *const unqual_type_right = get_unqualified_type(type_right);
1008 if (types_compatible(unqual_type_left, unqual_type_right)) {
1009 return ASSIGN_SUCCESS;
1011 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1012 return ASSIGN_WARNING_INT_FROM_POINTER;
1015 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1016 return ASSIGN_SUCCESS;
1018 return ASSIGN_ERROR_INCOMPATIBLE;
1021 static expression_t *parse_constant_expression(void)
1023 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1025 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1026 errorf(&result->base.source_position,
1027 "expression '%E' is not constant", result);
1033 static expression_t *parse_assignment_expression(void)
1035 return parse_subexpression(PREC_ASSIGNMENT);
1038 static void append_string(string_t const *const s)
1040 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1041 * possible, because other tokens are grown there alongside. */
1042 obstack_grow(&ast_obstack, s->begin, s->size - 1);
1045 static string_t finish_string(void)
1047 obstack_1grow(&ast_obstack, '\0');
1048 size_t const size = obstack_object_size(&ast_obstack);
1049 char const *const string = obstack_finish(&ast_obstack);
1050 return (string_t){ string, size };
1053 static string_t concat_string_literals(string_encoding_t *const out_enc)
1055 assert(token.kind == T_STRING_LITERAL);
1058 string_encoding_t enc = token.string.encoding;
1059 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1060 append_string(&token.string.string);
1061 eat(T_STRING_LITERAL);
1062 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1064 if (token.string.encoding != STRING_ENCODING_CHAR) {
1065 enc = token.string.encoding;
1067 append_string(&token.string.string);
1068 eat(T_STRING_LITERAL);
1069 } while (token.kind == T_STRING_LITERAL);
1070 result = finish_string();
1072 result = token.string.string;
1073 eat(T_STRING_LITERAL);
1080 static string_t parse_string_literals(void)
1082 string_encoding_t enc;
1083 source_position_t const pos = *HERE;
1084 string_t const res = concat_string_literals(&enc);
1086 if (enc != STRING_ENCODING_CHAR) {
1087 errorf(&pos, "expected plain string literal, got wide string literal");
1093 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1095 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1096 attribute->kind = kind;
1097 attribute->source_position = *HERE;
1102 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1105 * __attribute__ ( ( attribute-list ) )
1109 * attribute_list , attrib
1114 * any-word ( identifier )
1115 * any-word ( identifier , nonempty-expr-list )
1116 * any-word ( expr-list )
1118 * where the "identifier" must not be declared as a type, and
1119 * "any-word" may be any identifier (including one declared as a
1120 * type), a reserved word storage class specifier, type specifier or
1121 * type qualifier. ??? This still leaves out most reserved keywords
1122 * (following the old parser), shouldn't we include them, and why not
1123 * allow identifiers declared as types to start the arguments?
1125 * Matze: this all looks confusing and little systematic, so we're even less
1126 * strict and parse any list of things which are identifiers or
1127 * (assignment-)expressions.
1129 static attribute_argument_t *parse_attribute_arguments(void)
1131 attribute_argument_t *first = NULL;
1132 attribute_argument_t **anchor = &first;
1133 if (token.kind != ')') do {
1134 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1136 /* is it an identifier */
1137 if (token.kind == T_IDENTIFIER
1138 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1139 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1140 argument->v.symbol = token.base.symbol;
1143 /* must be an expression */
1144 expression_t *expression = parse_assignment_expression();
1146 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1147 argument->v.expression = expression;
1150 /* append argument */
1152 anchor = &argument->next;
1153 } while (next_if(','));
1158 static attribute_t *parse_attribute_asm(void)
1160 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1163 attribute->a.arguments = parse_attribute_arguments();
1167 static attribute_t *parse_attribute_gnu_single(void)
1169 /* parse "any-word" */
1170 symbol_t *const symbol = token.base.symbol;
1171 if (symbol == NULL) {
1172 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1176 attribute_kind_t kind;
1177 char const *const name = symbol->string;
1178 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1179 if (kind > ATTRIBUTE_GNU_LAST) {
1180 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1181 /* TODO: we should still save the attribute in the list... */
1182 kind = ATTRIBUTE_UNKNOWN;
1186 const char *attribute_name = get_attribute_name(kind);
1187 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1191 attribute_t *attribute = allocate_attribute_zero(kind);
1194 /* parse arguments */
1196 attribute->a.arguments = parse_attribute_arguments();
1201 static attribute_t *parse_attribute_gnu(void)
1203 attribute_t *first = NULL;
1204 attribute_t **anchor = &first;
1206 eat(T___attribute__);
1207 add_anchor_token(')');
1208 add_anchor_token(',');
1212 if (token.kind != ')') do {
1213 attribute_t *attribute = parse_attribute_gnu_single();
1215 *anchor = attribute;
1216 anchor = &attribute->next;
1218 } while (next_if(','));
1219 rem_anchor_token(',');
1220 rem_anchor_token(')');
1227 /** Parse attributes. */
1228 static attribute_t *parse_attributes(attribute_t *first)
1230 attribute_t **anchor = &first;
1232 while (*anchor != NULL)
1233 anchor = &(*anchor)->next;
1235 attribute_t *attribute;
1236 switch (token.kind) {
1237 case T___attribute__:
1238 attribute = parse_attribute_gnu();
1239 if (attribute == NULL)
1244 attribute = parse_attribute_asm();
1248 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1253 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1257 case T__forceinline:
1258 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1259 eat(T__forceinline);
1263 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1268 /* TODO record modifier */
1269 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1270 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1278 *anchor = attribute;
1279 anchor = &attribute->next;
1283 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1285 static entity_t *determine_lhs_ent(expression_t *const expr,
1288 switch (expr->kind) {
1289 case EXPR_REFERENCE: {
1290 entity_t *const entity = expr->reference.entity;
1291 /* we should only find variables as lvalues... */
1292 if (entity->base.kind != ENTITY_VARIABLE
1293 && entity->base.kind != ENTITY_PARAMETER)
1299 case EXPR_ARRAY_ACCESS: {
1300 expression_t *const ref = expr->array_access.array_ref;
1301 entity_t * ent = NULL;
1302 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1303 ent = determine_lhs_ent(ref, lhs_ent);
1306 mark_vars_read(ref, lhs_ent);
1308 mark_vars_read(expr->array_access.index, lhs_ent);
1313 mark_vars_read(expr->select.compound, lhs_ent);
1314 if (is_type_compound(skip_typeref(expr->base.type)))
1315 return determine_lhs_ent(expr->select.compound, lhs_ent);
1319 case EXPR_UNARY_DEREFERENCE: {
1320 expression_t *const val = expr->unary.value;
1321 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1323 return determine_lhs_ent(val->unary.value, lhs_ent);
1325 mark_vars_read(val, NULL);
1331 mark_vars_read(expr, NULL);
1336 #define ENT_ANY ((entity_t*)-1)
1339 * Mark declarations, which are read. This is used to detect variables, which
1343 * x is not marked as "read", because it is only read to calculate its own new
1347 * x and y are not detected as "not read", because multiple variables are
1350 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1352 switch (expr->kind) {
1353 case EXPR_REFERENCE: {
1354 entity_t *const entity = expr->reference.entity;
1355 if (entity->kind != ENTITY_VARIABLE
1356 && entity->kind != ENTITY_PARAMETER)
1359 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1360 entity->variable.read = true;
1366 // TODO respect pure/const
1367 mark_vars_read(expr->call.function, NULL);
1368 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1369 mark_vars_read(arg->expression, NULL);
1373 case EXPR_CONDITIONAL:
1374 // TODO lhs_decl should depend on whether true/false have an effect
1375 mark_vars_read(expr->conditional.condition, NULL);
1376 if (expr->conditional.true_expression != NULL)
1377 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1378 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1382 if (lhs_ent == ENT_ANY
1383 && !is_type_compound(skip_typeref(expr->base.type)))
1385 mark_vars_read(expr->select.compound, lhs_ent);
1388 case EXPR_ARRAY_ACCESS: {
1389 mark_vars_read(expr->array_access.index, lhs_ent);
1390 expression_t *const ref = expr->array_access.array_ref;
1391 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1392 if (lhs_ent == ENT_ANY)
1395 mark_vars_read(ref, lhs_ent);
1400 mark_vars_read(expr->va_arge.ap, lhs_ent);
1404 mark_vars_read(expr->va_copye.src, lhs_ent);
1407 case EXPR_UNARY_CAST:
1408 /* Special case: Use void cast to mark a variable as "read" */
1409 if (is_type_void(skip_typeref(expr->base.type)))
1414 case EXPR_UNARY_THROW:
1415 if (expr->unary.value == NULL)
1418 case EXPR_UNARY_DEREFERENCE:
1419 case EXPR_UNARY_DELETE:
1420 case EXPR_UNARY_DELETE_ARRAY:
1421 if (lhs_ent == ENT_ANY)
1425 case EXPR_UNARY_NEGATE:
1426 case EXPR_UNARY_PLUS:
1427 case EXPR_UNARY_BITWISE_NEGATE:
1428 case EXPR_UNARY_NOT:
1429 case EXPR_UNARY_TAKE_ADDRESS:
1430 case EXPR_UNARY_POSTFIX_INCREMENT:
1431 case EXPR_UNARY_POSTFIX_DECREMENT:
1432 case EXPR_UNARY_PREFIX_INCREMENT:
1433 case EXPR_UNARY_PREFIX_DECREMENT:
1434 case EXPR_UNARY_ASSUME:
1436 mark_vars_read(expr->unary.value, lhs_ent);
1439 case EXPR_BINARY_ADD:
1440 case EXPR_BINARY_SUB:
1441 case EXPR_BINARY_MUL:
1442 case EXPR_BINARY_DIV:
1443 case EXPR_BINARY_MOD:
1444 case EXPR_BINARY_EQUAL:
1445 case EXPR_BINARY_NOTEQUAL:
1446 case EXPR_BINARY_LESS:
1447 case EXPR_BINARY_LESSEQUAL:
1448 case EXPR_BINARY_GREATER:
1449 case EXPR_BINARY_GREATEREQUAL:
1450 case EXPR_BINARY_BITWISE_AND:
1451 case EXPR_BINARY_BITWISE_OR:
1452 case EXPR_BINARY_BITWISE_XOR:
1453 case EXPR_BINARY_LOGICAL_AND:
1454 case EXPR_BINARY_LOGICAL_OR:
1455 case EXPR_BINARY_SHIFTLEFT:
1456 case EXPR_BINARY_SHIFTRIGHT:
1457 case EXPR_BINARY_COMMA:
1458 case EXPR_BINARY_ISGREATER:
1459 case EXPR_BINARY_ISGREATEREQUAL:
1460 case EXPR_BINARY_ISLESS:
1461 case EXPR_BINARY_ISLESSEQUAL:
1462 case EXPR_BINARY_ISLESSGREATER:
1463 case EXPR_BINARY_ISUNORDERED:
1464 mark_vars_read(expr->binary.left, lhs_ent);
1465 mark_vars_read(expr->binary.right, lhs_ent);
1468 case EXPR_BINARY_ASSIGN:
1469 case EXPR_BINARY_MUL_ASSIGN:
1470 case EXPR_BINARY_DIV_ASSIGN:
1471 case EXPR_BINARY_MOD_ASSIGN:
1472 case EXPR_BINARY_ADD_ASSIGN:
1473 case EXPR_BINARY_SUB_ASSIGN:
1474 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1475 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1476 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1477 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1478 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1479 if (lhs_ent == ENT_ANY)
1481 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1482 mark_vars_read(expr->binary.right, lhs_ent);
1487 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1490 case EXPR_LITERAL_CASES:
1492 case EXPR_STRING_LITERAL:
1493 case EXPR_WIDE_STRING_LITERAL:
1494 case EXPR_COMPOUND_LITERAL: // TODO init?
1496 case EXPR_CLASSIFY_TYPE:
1499 case EXPR_BUILTIN_CONSTANT_P:
1500 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1502 case EXPR_STATEMENT: // TODO
1503 case EXPR_LABEL_ADDRESS:
1504 case EXPR_ENUM_CONSTANT:
1508 panic("unhandled expression");
1511 static designator_t *parse_designation(void)
1513 designator_t *result = NULL;
1514 designator_t **anchor = &result;
1517 designator_t *designator;
1518 switch (token.kind) {
1520 designator = allocate_ast_zero(sizeof(designator[0]));
1521 designator->source_position = *HERE;
1523 add_anchor_token(']');
1524 designator->array_index = parse_constant_expression();
1525 rem_anchor_token(']');
1529 designator = allocate_ast_zero(sizeof(designator[0]));
1530 designator->source_position = *HERE;
1532 designator->symbol = expect_identifier("while parsing designator", NULL);
1533 if (!designator->symbol)
1541 assert(designator != NULL);
1542 *anchor = designator;
1543 anchor = &designator->next;
1547 static initializer_t *initializer_from_string(array_type_t *const type,
1548 const string_t *const string)
1550 /* TODO: check len vs. size of array type */
1553 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1554 initializer->string.string = *string;
1559 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1560 const string_t *const string)
1562 /* TODO: check len vs. size of array type */
1565 initializer_t *const initializer =
1566 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1567 initializer->wide_string.string = *string;
1573 * Build an initializer from a given expression.
1575 static initializer_t *initializer_from_expression(type_t *orig_type,
1576 expression_t *expression)
1578 /* TODO check that expression is a constant expression */
1580 /* §6.7.8.14/15 char array may be initialized by string literals */
1581 type_t *type = skip_typeref(orig_type);
1582 type_t *expr_type_orig = expression->base.type;
1583 type_t *expr_type = skip_typeref(expr_type_orig);
1585 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1586 array_type_t *const array_type = &type->array;
1587 type_t *const element_type = skip_typeref(array_type->element_type);
1589 if (element_type->kind == TYPE_ATOMIC) {
1590 atomic_type_kind_t akind = element_type->atomic.akind;
1591 switch (expression->kind) {
1592 case EXPR_STRING_LITERAL:
1593 if (akind == ATOMIC_TYPE_CHAR
1594 || akind == ATOMIC_TYPE_SCHAR
1595 || akind == ATOMIC_TYPE_UCHAR) {
1596 return initializer_from_string(array_type,
1597 &expression->string_literal.value);
1601 case EXPR_WIDE_STRING_LITERAL: {
1602 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1603 if (get_unqualified_type(element_type) == bare_wchar_type) {
1604 return initializer_from_wide_string(array_type,
1605 &expression->string_literal.value);
1616 assign_error_t error = semantic_assign(type, expression);
1617 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1619 report_assign_error(error, type, expression, "initializer",
1620 &expression->base.source_position);
1622 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1623 result->value.value = create_implicit_cast(expression, type);
1629 * Parses an scalar initializer.
1631 * §6.7.8.11; eat {} without warning
1633 static initializer_t *parse_scalar_initializer(type_t *type,
1634 bool must_be_constant)
1636 /* there might be extra {} hierarchies */
1638 if (token.kind == '{') {
1639 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1643 } while (token.kind == '{');
1646 expression_t *expression = parse_assignment_expression();
1647 mark_vars_read(expression, NULL);
1648 if (must_be_constant && !is_linker_constant(expression)) {
1649 errorf(&expression->base.source_position,
1650 "initialisation expression '%E' is not constant",
1654 initializer_t *initializer = initializer_from_expression(type, expression);
1656 if (initializer == NULL) {
1657 errorf(&expression->base.source_position,
1658 "expression '%E' (type '%T') doesn't match expected type '%T'",
1659 expression, expression->base.type, type);
1664 bool additional_warning_displayed = false;
1665 while (braces > 0) {
1667 if (token.kind != '}') {
1668 if (!additional_warning_displayed) {
1669 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1670 additional_warning_displayed = true;
1681 * An entry in the type path.
1683 typedef struct type_path_entry_t type_path_entry_t;
1684 struct type_path_entry_t {
1685 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1687 size_t index; /**< For array types: the current index. */
1688 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1693 * A type path expression a position inside compound or array types.
1695 typedef struct type_path_t type_path_t;
1696 struct type_path_t {
1697 type_path_entry_t *path; /**< An flexible array containing the current path. */
1698 type_t *top_type; /**< type of the element the path points */
1699 size_t max_index; /**< largest index in outermost array */
1703 * Prints a type path for debugging.
1705 static __attribute__((unused)) void debug_print_type_path(
1706 const type_path_t *path)
1708 size_t len = ARR_LEN(path->path);
1710 for (size_t i = 0; i < len; ++i) {
1711 const type_path_entry_t *entry = & path->path[i];
1713 type_t *type = skip_typeref(entry->type);
1714 if (is_type_compound(type)) {
1715 /* in gcc mode structs can have no members */
1716 if (entry->v.compound_entry == NULL) {
1720 fprintf(stderr, ".%s",
1721 entry->v.compound_entry->base.symbol->string);
1722 } else if (is_type_array(type)) {
1723 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1725 fprintf(stderr, "-INVALID-");
1728 if (path->top_type != NULL) {
1729 fprintf(stderr, " (");
1730 print_type(path->top_type);
1731 fprintf(stderr, ")");
1736 * Return the top type path entry, ie. in a path
1737 * (type).a.b returns the b.
1739 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1741 size_t len = ARR_LEN(path->path);
1743 return &path->path[len-1];
1747 * Enlarge the type path by an (empty) element.
1749 static type_path_entry_t *append_to_type_path(type_path_t *path)
1751 size_t len = ARR_LEN(path->path);
1752 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1754 type_path_entry_t *result = & path->path[len];
1755 memset(result, 0, sizeof(result[0]));
1760 * Descending into a sub-type. Enter the scope of the current top_type.
1762 static void descend_into_subtype(type_path_t *path)
1764 type_t *orig_top_type = path->top_type;
1765 type_t *top_type = skip_typeref(orig_top_type);
1767 type_path_entry_t *top = append_to_type_path(path);
1768 top->type = top_type;
1770 if (is_type_compound(top_type)) {
1771 compound_t *const compound = top_type->compound.compound;
1772 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1774 if (entry != NULL) {
1775 top->v.compound_entry = &entry->declaration;
1776 path->top_type = entry->declaration.type;
1778 path->top_type = NULL;
1780 } else if (is_type_array(top_type)) {
1782 path->top_type = top_type->array.element_type;
1784 assert(!is_type_valid(top_type));
1789 * Pop an entry from the given type path, ie. returning from
1790 * (type).a.b to (type).a
1792 static void ascend_from_subtype(type_path_t *path)
1794 type_path_entry_t *top = get_type_path_top(path);
1796 path->top_type = top->type;
1798 size_t len = ARR_LEN(path->path);
1799 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1803 * Pop entries from the given type path until the given
1804 * path level is reached.
1806 static void ascend_to(type_path_t *path, size_t top_path_level)
1808 size_t len = ARR_LEN(path->path);
1810 while (len > top_path_level) {
1811 ascend_from_subtype(path);
1812 len = ARR_LEN(path->path);
1816 static bool walk_designator(type_path_t *path, const designator_t *designator,
1817 bool used_in_offsetof)
1819 for (; designator != NULL; designator = designator->next) {
1820 type_path_entry_t *top = get_type_path_top(path);
1821 type_t *orig_type = top->type;
1823 type_t *type = skip_typeref(orig_type);
1825 if (designator->symbol != NULL) {
1826 symbol_t *symbol = designator->symbol;
1827 if (!is_type_compound(type)) {
1828 if (is_type_valid(type)) {
1829 errorf(&designator->source_position,
1830 "'.%Y' designator used for non-compound type '%T'",
1834 top->type = type_error_type;
1835 top->v.compound_entry = NULL;
1836 orig_type = type_error_type;
1838 compound_t *compound = type->compound.compound;
1839 entity_t *iter = compound->members.entities;
1840 for (; iter != NULL; iter = iter->base.next) {
1841 if (iter->base.symbol == symbol) {
1846 errorf(&designator->source_position,
1847 "'%T' has no member named '%Y'", orig_type, symbol);
1850 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1851 if (used_in_offsetof && iter->compound_member.bitfield) {
1852 errorf(&designator->source_position,
1853 "offsetof designator '%Y' must not specify bitfield",
1858 top->type = orig_type;
1859 top->v.compound_entry = &iter->declaration;
1860 orig_type = iter->declaration.type;
1863 expression_t *array_index = designator->array_index;
1864 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1867 if (!is_type_array(type)) {
1868 if (is_type_valid(type)) {
1869 errorf(&designator->source_position,
1870 "[%E] designator used for non-array type '%T'",
1871 array_index, orig_type);
1876 long index = fold_constant_to_int(array_index);
1877 if (!used_in_offsetof) {
1879 errorf(&designator->source_position,
1880 "array index [%E] must be positive", array_index);
1881 } else if (type->array.size_constant) {
1882 long array_size = type->array.size;
1883 if (index >= array_size) {
1884 errorf(&designator->source_position,
1885 "designator [%E] (%d) exceeds array size %d",
1886 array_index, index, array_size);
1891 top->type = orig_type;
1892 top->v.index = (size_t) index;
1893 orig_type = type->array.element_type;
1895 path->top_type = orig_type;
1897 if (designator->next != NULL) {
1898 descend_into_subtype(path);
1904 static void advance_current_object(type_path_t *path, size_t top_path_level)
1906 type_path_entry_t *top = get_type_path_top(path);
1908 type_t *type = skip_typeref(top->type);
1909 if (is_type_union(type)) {
1910 /* in unions only the first element is initialized */
1911 top->v.compound_entry = NULL;
1912 } else if (is_type_struct(type)) {
1913 declaration_t *entry = top->v.compound_entry;
1915 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1916 if (next_entity != NULL) {
1917 assert(is_declaration(next_entity));
1918 entry = &next_entity->declaration;
1923 top->v.compound_entry = entry;
1924 if (entry != NULL) {
1925 path->top_type = entry->type;
1928 } else if (is_type_array(type)) {
1929 assert(is_type_array(type));
1933 if (!type->array.size_constant || top->v.index < type->array.size) {
1937 assert(!is_type_valid(type));
1941 /* we're past the last member of the current sub-aggregate, try if we
1942 * can ascend in the type hierarchy and continue with another subobject */
1943 size_t len = ARR_LEN(path->path);
1945 if (len > top_path_level) {
1946 ascend_from_subtype(path);
1947 advance_current_object(path, top_path_level);
1949 path->top_type = NULL;
1954 * skip any {...} blocks until a closing bracket is reached.
1956 static void skip_initializers(void)
1960 while (token.kind != '}') {
1961 if (token.kind == T_EOF)
1963 if (token.kind == '{') {
1971 static initializer_t *create_empty_initializer(void)
1973 static initializer_t empty_initializer
1974 = { .list = { { INITIALIZER_LIST }, 0 } };
1975 return &empty_initializer;
1979 * Parse a part of an initialiser for a struct or union,
1981 static initializer_t *parse_sub_initializer(type_path_t *path,
1982 type_t *outer_type, size_t top_path_level,
1983 parse_initializer_env_t *env)
1985 if (token.kind == '}') {
1986 /* empty initializer */
1987 return create_empty_initializer();
1990 type_t *orig_type = path->top_type;
1991 type_t *type = NULL;
1993 if (orig_type == NULL) {
1994 /* We are initializing an empty compound. */
1996 type = skip_typeref(orig_type);
1999 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2002 designator_t *designator = NULL;
2003 if (token.kind == '.' || token.kind == '[') {
2004 designator = parse_designation();
2005 goto finish_designator;
2006 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2007 /* GNU-style designator ("identifier: value") */
2008 designator = allocate_ast_zero(sizeof(designator[0]));
2009 designator->source_position = *HERE;
2010 designator->symbol = token.base.symbol;
2015 /* reset path to toplevel, evaluate designator from there */
2016 ascend_to(path, top_path_level);
2017 if (!walk_designator(path, designator, false)) {
2018 /* can't continue after designation error */
2022 initializer_t *designator_initializer
2023 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2024 designator_initializer->designator.designator = designator;
2025 ARR_APP1(initializer_t*, initializers, designator_initializer);
2027 orig_type = path->top_type;
2028 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2033 if (token.kind == '{') {
2034 if (type != NULL && is_type_scalar(type)) {
2035 sub = parse_scalar_initializer(type, env->must_be_constant);
2038 if (env->entity != NULL) {
2039 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2041 errorf(HERE, "extra brace group at end of initializer");
2046 descend_into_subtype(path);
2049 add_anchor_token('}');
2050 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2052 rem_anchor_token('}');
2057 goto error_parse_next;
2059 ascend_from_subtype(path);
2062 /* must be an expression */
2063 expression_t *expression = parse_assignment_expression();
2064 mark_vars_read(expression, NULL);
2066 if (env->must_be_constant && !is_linker_constant(expression)) {
2067 errorf(&expression->base.source_position,
2068 "Initialisation expression '%E' is not constant",
2073 /* we are already outside, ... */
2074 if (outer_type == NULL)
2075 goto error_parse_next;
2076 type_t *const outer_type_skip = skip_typeref(outer_type);
2077 if (is_type_compound(outer_type_skip) &&
2078 !outer_type_skip->compound.compound->complete) {
2079 goto error_parse_next;
2082 source_position_t const* const pos = &expression->base.source_position;
2083 if (env->entity != NULL) {
2084 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2086 warningf(WARN_OTHER, pos, "excess elements in initializer");
2088 goto error_parse_next;
2091 /* handle { "string" } special case */
2092 if ((expression->kind == EXPR_STRING_LITERAL
2093 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2094 && outer_type != NULL) {
2095 sub = initializer_from_expression(outer_type, expression);
2098 if (token.kind != '}') {
2099 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2101 /* TODO: eat , ... */
2106 /* descend into subtypes until expression matches type */
2108 orig_type = path->top_type;
2109 type = skip_typeref(orig_type);
2111 sub = initializer_from_expression(orig_type, expression);
2115 if (!is_type_valid(type)) {
2118 if (is_type_scalar(type)) {
2119 errorf(&expression->base.source_position,
2120 "expression '%E' doesn't match expected type '%T'",
2121 expression, orig_type);
2125 descend_into_subtype(path);
2129 /* update largest index of top array */
2130 const type_path_entry_t *first = &path->path[0];
2131 type_t *first_type = first->type;
2132 first_type = skip_typeref(first_type);
2133 if (is_type_array(first_type)) {
2134 size_t index = first->v.index;
2135 if (index > path->max_index)
2136 path->max_index = index;
2139 /* append to initializers list */
2140 ARR_APP1(initializer_t*, initializers, sub);
2143 if (token.kind == '}') {
2146 add_anchor_token('}');
2148 rem_anchor_token('}');
2149 if (token.kind == '}') {
2154 /* advance to the next declaration if we are not at the end */
2155 advance_current_object(path, top_path_level);
2156 orig_type = path->top_type;
2157 if (orig_type != NULL)
2158 type = skip_typeref(orig_type);
2164 size_t len = ARR_LEN(initializers);
2165 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2166 initializer_t *result = allocate_ast_zero(size);
2167 result->kind = INITIALIZER_LIST;
2168 result->list.len = len;
2169 memcpy(&result->list.initializers, initializers,
2170 len * sizeof(initializers[0]));
2172 DEL_ARR_F(initializers);
2173 ascend_to(path, top_path_level+1);
2178 skip_initializers();
2179 DEL_ARR_F(initializers);
2180 ascend_to(path, top_path_level+1);
2184 static expression_t *make_size_literal(size_t value)
2186 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2187 literal->base.type = type_size_t;
2190 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2191 literal->literal.value = make_string(buf);
2197 * Parses an initializer. Parsers either a compound literal
2198 * (env->declaration == NULL) or an initializer of a declaration.
2200 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2202 type_t *type = skip_typeref(env->type);
2203 size_t max_index = 0;
2204 initializer_t *result;
2206 if (is_type_scalar(type)) {
2207 result = parse_scalar_initializer(type, env->must_be_constant);
2208 } else if (token.kind == '{') {
2212 memset(&path, 0, sizeof(path));
2213 path.top_type = env->type;
2214 path.path = NEW_ARR_F(type_path_entry_t, 0);
2216 descend_into_subtype(&path);
2218 add_anchor_token('}');
2219 result = parse_sub_initializer(&path, env->type, 1, env);
2220 rem_anchor_token('}');
2222 max_index = path.max_index;
2223 DEL_ARR_F(path.path);
2227 /* parse_scalar_initializer() also works in this case: we simply
2228 * have an expression without {} around it */
2229 result = parse_scalar_initializer(type, env->must_be_constant);
2232 /* §6.7.8:22 array initializers for arrays with unknown size determine
2233 * the array type size */
2234 if (is_type_array(type) && type->array.size_expression == NULL
2235 && result != NULL) {
2237 switch (result->kind) {
2238 case INITIALIZER_LIST:
2239 assert(max_index != 0xdeadbeaf);
2240 size = max_index + 1;
2243 case INITIALIZER_STRING:
2244 size = result->string.string.size;
2247 case INITIALIZER_WIDE_STRING:
2248 size = result->wide_string.string.size;
2251 case INITIALIZER_DESIGNATOR:
2252 case INITIALIZER_VALUE:
2253 /* can happen for parse errors */
2258 internal_errorf(HERE, "invalid initializer type");
2261 type_t *new_type = duplicate_type(type);
2263 new_type->array.size_expression = make_size_literal(size);
2264 new_type->array.size_constant = true;
2265 new_type->array.has_implicit_size = true;
2266 new_type->array.size = size;
2267 env->type = new_type;
2273 static void append_entity(scope_t *scope, entity_t *entity)
2275 if (scope->last_entity != NULL) {
2276 scope->last_entity->base.next = entity;
2278 scope->entities = entity;
2280 entity->base.parent_entity = current_entity;
2281 scope->last_entity = entity;
2285 static compound_t *parse_compound_type_specifier(bool is_struct)
2287 source_position_t const pos = *HERE;
2288 eat(is_struct ? T_struct : T_union);
2290 symbol_t *symbol = NULL;
2291 entity_t *entity = NULL;
2292 attribute_t *attributes = NULL;
2294 if (token.kind == T___attribute__) {
2295 attributes = parse_attributes(NULL);
2298 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2299 if (token.kind == T_IDENTIFIER) {
2300 /* the compound has a name, check if we have seen it already */
2301 symbol = token.base.symbol;
2302 entity = get_tag(symbol, kind);
2305 if (entity != NULL) {
2306 if (entity->base.parent_scope != current_scope &&
2307 (token.kind == '{' || token.kind == ';')) {
2308 /* we're in an inner scope and have a definition. Shadow
2309 * existing definition in outer scope */
2311 } else if (entity->compound.complete && token.kind == '{') {
2312 source_position_t const *const ppos = &entity->base.source_position;
2313 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2314 /* clear members in the hope to avoid further errors */
2315 entity->compound.members.entities = NULL;
2318 } else if (token.kind != '{') {
2319 char const *const msg =
2320 is_struct ? "while parsing struct type specifier" :
2321 "while parsing union type specifier";
2322 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2327 if (entity == NULL) {
2328 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2329 entity->compound.alignment = 1;
2330 entity->base.parent_scope = current_scope;
2331 if (symbol != NULL) {
2332 environment_push(entity);
2334 append_entity(current_scope, entity);
2337 if (token.kind == '{') {
2338 parse_compound_type_entries(&entity->compound);
2340 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2341 if (symbol == NULL) {
2342 assert(anonymous_entity == NULL);
2343 anonymous_entity = entity;
2347 if (attributes != NULL) {
2348 handle_entity_attributes(attributes, entity);
2351 return &entity->compound;
2354 static void parse_enum_entries(type_t *const enum_type)
2358 if (token.kind == '}') {
2359 errorf(HERE, "empty enum not allowed");
2364 add_anchor_token('}');
2365 add_anchor_token(',');
2367 add_anchor_token('=');
2368 source_position_t pos;
2369 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2370 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2371 entity->enum_value.enum_type = enum_type;
2372 rem_anchor_token('=');
2375 expression_t *value = parse_constant_expression();
2377 value = create_implicit_cast(value, enum_type);
2378 entity->enum_value.value = value;
2383 record_entity(entity, false);
2384 } while (next_if(',') && token.kind != '}');
2385 rem_anchor_token(',');
2386 rem_anchor_token('}');
2391 static type_t *parse_enum_specifier(void)
2393 source_position_t const pos = *HERE;
2398 switch (token.kind) {
2400 symbol = token.base.symbol;
2401 entity = get_tag(symbol, ENTITY_ENUM);
2404 if (entity != NULL) {
2405 if (entity->base.parent_scope != current_scope &&
2406 (token.kind == '{' || token.kind == ';')) {
2407 /* we're in an inner scope and have a definition. Shadow
2408 * existing definition in outer scope */
2410 } else if (entity->enume.complete && token.kind == '{') {
2411 source_position_t const *const ppos = &entity->base.source_position;
2412 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2423 parse_error_expected("while parsing enum type specifier",
2424 T_IDENTIFIER, '{', NULL);
2428 if (entity == NULL) {
2429 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2430 entity->base.parent_scope = current_scope;
2433 type_t *const type = allocate_type_zero(TYPE_ENUM);
2434 type->enumt.enume = &entity->enume;
2435 type->enumt.base.akind = ATOMIC_TYPE_INT;
2437 if (token.kind == '{') {
2438 if (symbol != NULL) {
2439 environment_push(entity);
2441 append_entity(current_scope, entity);
2442 entity->enume.complete = true;
2444 parse_enum_entries(type);
2445 parse_attributes(NULL);
2447 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2448 if (symbol == NULL) {
2449 assert(anonymous_entity == NULL);
2450 anonymous_entity = entity;
2452 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2453 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2460 * if a symbol is a typedef to another type, return true
2462 static bool is_typedef_symbol(symbol_t *symbol)
2464 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2465 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2468 static type_t *parse_typeof(void)
2474 add_anchor_token(')');
2477 expression_t *expression = NULL;
2479 switch (token.kind) {
2481 if (is_typedef_symbol(token.base.symbol)) {
2483 type = parse_typename();
2486 expression = parse_expression();
2487 type = revert_automatic_type_conversion(expression);
2492 rem_anchor_token(')');
2495 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2496 typeof_type->typeoft.expression = expression;
2497 typeof_type->typeoft.typeof_type = type;
2502 typedef enum specifiers_t {
2503 SPECIFIER_SIGNED = 1 << 0,
2504 SPECIFIER_UNSIGNED = 1 << 1,
2505 SPECIFIER_LONG = 1 << 2,
2506 SPECIFIER_INT = 1 << 3,
2507 SPECIFIER_DOUBLE = 1 << 4,
2508 SPECIFIER_CHAR = 1 << 5,
2509 SPECIFIER_WCHAR_T = 1 << 6,
2510 SPECIFIER_SHORT = 1 << 7,
2511 SPECIFIER_LONG_LONG = 1 << 8,
2512 SPECIFIER_FLOAT = 1 << 9,
2513 SPECIFIER_BOOL = 1 << 10,
2514 SPECIFIER_VOID = 1 << 11,
2515 SPECIFIER_INT8 = 1 << 12,
2516 SPECIFIER_INT16 = 1 << 13,
2517 SPECIFIER_INT32 = 1 << 14,
2518 SPECIFIER_INT64 = 1 << 15,
2519 SPECIFIER_INT128 = 1 << 16,
2520 SPECIFIER_COMPLEX = 1 << 17,
2521 SPECIFIER_IMAGINARY = 1 << 18,
2524 static type_t *get_typedef_type(symbol_t *symbol)
2526 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2527 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2530 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2531 type->typedeft.typedefe = &entity->typedefe;
2536 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2538 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2540 add_anchor_token(')');
2541 add_anchor_token(',');
2545 add_anchor_token('=');
2546 source_position_t pos;
2547 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2548 rem_anchor_token('=');
2550 symbol_t **prop = NULL;
2552 if (streq(prop_sym->string, "put")) {
2553 prop = &property->put_symbol;
2554 } else if (streq(prop_sym->string, "get")) {
2555 prop = &property->get_symbol;
2557 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2561 add_anchor_token(T_IDENTIFIER);
2563 rem_anchor_token(T_IDENTIFIER);
2565 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2567 *prop = sym ? sym : sym_anonymous;
2568 } while (next_if(','));
2569 rem_anchor_token(',');
2570 rem_anchor_token(')');
2572 attribute->a.property = property;
2578 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2580 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2581 if (next_if(T_restrict)) {
2582 kind = ATTRIBUTE_MS_RESTRICT;
2583 } else if (token.kind == T_IDENTIFIER) {
2584 char const *const name = token.base.symbol->string;
2585 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2587 const char *attribute_name = get_attribute_name(k);
2588 if (attribute_name != NULL && streq(attribute_name, name)) {
2594 if (kind == ATTRIBUTE_UNKNOWN) {
2595 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2598 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2602 attribute_t *attribute = allocate_attribute_zero(kind);
2605 if (kind == ATTRIBUTE_MS_PROPERTY) {
2606 return parse_attribute_ms_property(attribute);
2609 /* parse arguments */
2611 attribute->a.arguments = parse_attribute_arguments();
2616 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2620 add_anchor_token(')');
2622 if (token.kind != ')') {
2623 attribute_t **anchor = &first;
2625 while (*anchor != NULL)
2626 anchor = &(*anchor)->next;
2628 attribute_t *attribute
2629 = parse_microsoft_extended_decl_modifier_single();
2630 if (attribute == NULL)
2633 *anchor = attribute;
2634 anchor = &attribute->next;
2635 } while (next_if(','));
2637 rem_anchor_token(')');
2642 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2644 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2645 if (is_declaration(entity)) {
2646 entity->declaration.type = type_error_type;
2647 entity->declaration.implicit = true;
2648 } else if (kind == ENTITY_TYPEDEF) {
2649 entity->typedefe.type = type_error_type;
2650 entity->typedefe.builtin = true;
2652 if (kind != ENTITY_COMPOUND_MEMBER)
2653 record_entity(entity, false);
2657 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2659 type_t *type = NULL;
2660 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2661 unsigned type_specifiers = 0;
2662 bool newtype = false;
2663 bool saw_error = false;
2665 memset(specifiers, 0, sizeof(*specifiers));
2666 specifiers->source_position = *HERE;
2669 specifiers->attributes = parse_attributes(specifiers->attributes);
2671 switch (token.kind) {
2673 #define MATCH_STORAGE_CLASS(token, class) \
2675 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2676 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2678 specifiers->storage_class = class; \
2679 if (specifiers->thread_local) \
2680 goto check_thread_storage_class; \
2684 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2685 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2686 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2687 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2688 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2691 specifiers->attributes
2692 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2696 if (specifiers->thread_local) {
2697 errorf(HERE, "duplicate '__thread'");
2699 specifiers->thread_local = true;
2700 check_thread_storage_class:
2701 switch (specifiers->storage_class) {
2702 case STORAGE_CLASS_EXTERN:
2703 case STORAGE_CLASS_NONE:
2704 case STORAGE_CLASS_STATIC:
2708 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2709 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2710 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2711 wrong_thread_storage_class:
2712 errorf(HERE, "'__thread' used with '%s'", wrong);
2719 /* type qualifiers */
2720 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2722 qualifiers |= qualifier; \
2726 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2727 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2728 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2729 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2730 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2731 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2732 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2733 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2735 /* type specifiers */
2736 #define MATCH_SPECIFIER(token, specifier, name) \
2738 if (type_specifiers & specifier) { \
2739 errorf(HERE, "multiple " name " type specifiers given"); \
2741 type_specifiers |= specifier; \
2746 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2747 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2748 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2749 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2750 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2751 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2752 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2753 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2754 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2755 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2756 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2757 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2758 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2759 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2760 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2761 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2762 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2763 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2767 specifiers->is_inline = true;
2771 case T__forceinline:
2772 eat(T__forceinline);
2773 specifiers->modifiers |= DM_FORCEINLINE;
2778 if (type_specifiers & SPECIFIER_LONG_LONG) {
2779 errorf(HERE, "too many long type specifiers given");
2780 } else if (type_specifiers & SPECIFIER_LONG) {
2781 type_specifiers |= SPECIFIER_LONG_LONG;
2783 type_specifiers |= SPECIFIER_LONG;
2788 #define CHECK_DOUBLE_TYPE() \
2789 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2792 CHECK_DOUBLE_TYPE();
2793 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2795 type->compound.compound = parse_compound_type_specifier(true);
2798 CHECK_DOUBLE_TYPE();
2799 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2800 type->compound.compound = parse_compound_type_specifier(false);
2803 CHECK_DOUBLE_TYPE();
2804 type = parse_enum_specifier();
2807 CHECK_DOUBLE_TYPE();
2808 type = parse_typeof();
2810 case T___builtin_va_list:
2811 CHECK_DOUBLE_TYPE();
2812 type = duplicate_type(type_valist);
2813 eat(T___builtin_va_list);
2816 case T_IDENTIFIER: {
2817 /* only parse identifier if we haven't found a type yet */
2818 if (type != NULL || type_specifiers != 0) {
2819 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2820 * declaration, so it doesn't generate errors about expecting '(' or
2822 switch (look_ahead(1)->kind) {
2829 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2833 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2838 goto finish_specifiers;
2842 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2843 if (typedef_type == NULL) {
2844 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2845 * declaration, so it doesn't generate 'implicit int' followed by more
2846 * errors later on. */
2847 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2853 errorf(HERE, "%K does not name a type", &token);
2855 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2857 type = allocate_type_zero(TYPE_TYPEDEF);
2858 type->typedeft.typedefe = &entity->typedefe;
2866 goto finish_specifiers;
2871 type = typedef_type;
2875 /* function specifier */
2877 goto finish_specifiers;
2882 specifiers->attributes = parse_attributes(specifiers->attributes);
2884 if (type == NULL || (saw_error && type_specifiers != 0)) {
2885 atomic_type_kind_t atomic_type;
2887 /* match valid basic types */
2888 switch (type_specifiers) {
2889 case SPECIFIER_VOID:
2890 atomic_type = ATOMIC_TYPE_VOID;
2892 case SPECIFIER_WCHAR_T:
2893 atomic_type = ATOMIC_TYPE_WCHAR_T;
2895 case SPECIFIER_CHAR:
2896 atomic_type = ATOMIC_TYPE_CHAR;
2898 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2899 atomic_type = ATOMIC_TYPE_SCHAR;
2901 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2902 atomic_type = ATOMIC_TYPE_UCHAR;
2904 case SPECIFIER_SHORT:
2905 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2906 case SPECIFIER_SHORT | SPECIFIER_INT:
2907 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2908 atomic_type = ATOMIC_TYPE_SHORT;
2910 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2911 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2912 atomic_type = ATOMIC_TYPE_USHORT;
2915 case SPECIFIER_SIGNED:
2916 case SPECIFIER_SIGNED | SPECIFIER_INT:
2917 atomic_type = ATOMIC_TYPE_INT;
2919 case SPECIFIER_UNSIGNED:
2920 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2921 atomic_type = ATOMIC_TYPE_UINT;
2923 case SPECIFIER_LONG:
2924 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2925 case SPECIFIER_LONG | SPECIFIER_INT:
2926 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2927 atomic_type = ATOMIC_TYPE_LONG;
2929 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2930 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2931 atomic_type = ATOMIC_TYPE_ULONG;
2934 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2935 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2936 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2937 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2939 atomic_type = ATOMIC_TYPE_LONGLONG;
2940 goto warn_about_long_long;
2942 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2943 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2945 atomic_type = ATOMIC_TYPE_ULONGLONG;
2946 warn_about_long_long:
2947 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2950 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2951 atomic_type = unsigned_int8_type_kind;
2954 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2955 atomic_type = unsigned_int16_type_kind;
2958 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2959 atomic_type = unsigned_int32_type_kind;
2962 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2963 atomic_type = unsigned_int64_type_kind;
2966 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2967 atomic_type = unsigned_int128_type_kind;
2970 case SPECIFIER_INT8:
2971 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2972 atomic_type = int8_type_kind;
2975 case SPECIFIER_INT16:
2976 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2977 atomic_type = int16_type_kind;
2980 case SPECIFIER_INT32:
2981 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2982 atomic_type = int32_type_kind;
2985 case SPECIFIER_INT64:
2986 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2987 atomic_type = int64_type_kind;
2990 case SPECIFIER_INT128:
2991 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2992 atomic_type = int128_type_kind;
2995 case SPECIFIER_FLOAT:
2996 atomic_type = ATOMIC_TYPE_FLOAT;
2998 case SPECIFIER_DOUBLE:
2999 atomic_type = ATOMIC_TYPE_DOUBLE;
3001 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3002 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3004 case SPECIFIER_BOOL:
3005 atomic_type = ATOMIC_TYPE_BOOL;
3007 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3008 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3009 atomic_type = ATOMIC_TYPE_FLOAT;
3011 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3012 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3013 atomic_type = ATOMIC_TYPE_DOUBLE;
3015 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3016 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3017 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3020 /* invalid specifier combination, give an error message */
3021 source_position_t const* const pos = &specifiers->source_position;
3022 if (type_specifiers == 0) {
3024 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3025 if (!(c_mode & _CXX) && !strict_mode) {
3026 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3027 atomic_type = ATOMIC_TYPE_INT;
3030 errorf(pos, "no type specifiers given in declaration");
3033 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3034 (type_specifiers & SPECIFIER_UNSIGNED)) {
3035 errorf(pos, "signed and unsigned specifiers given");
3036 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3037 errorf(pos, "only integer types can be signed or unsigned");
3039 errorf(pos, "multiple datatypes in declaration");
3045 if (type_specifiers & SPECIFIER_COMPLEX) {
3046 type = allocate_type_zero(TYPE_COMPLEX);
3047 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3048 type = allocate_type_zero(TYPE_IMAGINARY);
3050 type = allocate_type_zero(TYPE_ATOMIC);
3052 type->atomic.akind = atomic_type;
3054 } else if (type_specifiers != 0) {
3055 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3058 /* FIXME: check type qualifiers here */
3059 type->base.qualifiers = qualifiers;
3062 type = identify_new_type(type);
3064 type = typehash_insert(type);
3067 if (specifiers->attributes != NULL)
3068 type = handle_type_attributes(specifiers->attributes, type);
3069 specifiers->type = type;
3073 specifiers->type = type_error_type;
3076 static type_qualifiers_t parse_type_qualifiers(void)
3078 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3081 switch (token.kind) {
3082 /* type qualifiers */
3083 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3084 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3085 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3086 /* microsoft extended type modifiers */
3087 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3088 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3089 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3090 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3091 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3100 * Parses an K&R identifier list
3102 static void parse_identifier_list(scope_t *scope)
3104 assert(token.kind == T_IDENTIFIER);
3106 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3107 /* a K&R parameter has no type, yet */
3111 append_entity(scope, entity);
3112 } while (next_if(',') && token.kind == T_IDENTIFIER);
3115 static entity_t *parse_parameter(void)
3117 declaration_specifiers_t specifiers;
3118 parse_declaration_specifiers(&specifiers);
3120 entity_t *entity = parse_declarator(&specifiers,
3121 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3122 anonymous_entity = NULL;
3126 static void semantic_parameter_incomplete(const entity_t *entity)
3128 assert(entity->kind == ENTITY_PARAMETER);
3130 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3131 * list in a function declarator that is part of a
3132 * definition of that function shall not have
3133 * incomplete type. */
3134 type_t *type = skip_typeref(entity->declaration.type);
3135 if (is_type_incomplete(type)) {
3136 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3140 static bool has_parameters(void)
3142 /* func(void) is not a parameter */
3143 if (look_ahead(1)->kind != ')')
3145 if (token.kind == T_IDENTIFIER) {
3146 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3149 if (entity->kind != ENTITY_TYPEDEF)
3151 type_t const *const type = skip_typeref(entity->typedefe.type);
3152 if (!is_type_void(type))
3154 if (c_mode & _CXX) {
3155 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3156 * is not allowed. */
3157 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3158 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3159 /* §6.7.5.3:10 Qualification is not allowed here. */
3160 errorf(HERE, "'void' as parameter must not have type qualifiers");
3162 } else if (token.kind != T_void) {
3170 * Parses function type parameters (and optionally creates variable_t entities
3171 * for them in a scope)
3173 static void parse_parameters(function_type_t *type, scope_t *scope)
3175 add_anchor_token(')');
3178 if (token.kind == T_IDENTIFIER &&
3179 !is_typedef_symbol(token.base.symbol) &&
3180 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3181 type->kr_style_parameters = true;
3182 parse_identifier_list(scope);
3183 } else if (token.kind == ')') {
3184 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3185 if (!(c_mode & _CXX))
3186 type->unspecified_parameters = true;
3187 } else if (has_parameters()) {
3188 function_parameter_t **anchor = &type->parameters;
3189 add_anchor_token(',');
3191 switch (token.kind) {
3194 type->variadic = true;
3195 goto parameters_finished;
3200 entity_t *entity = parse_parameter();
3201 if (entity->kind == ENTITY_TYPEDEF) {
3202 errorf(&entity->base.source_position,
3203 "typedef not allowed as function parameter");
3206 assert(is_declaration(entity));
3208 semantic_parameter_incomplete(entity);
3210 function_parameter_t *const parameter =
3211 allocate_parameter(entity->declaration.type);
3213 if (scope != NULL) {
3214 append_entity(scope, entity);
3217 *anchor = parameter;
3218 anchor = ¶meter->next;
3223 goto parameters_finished;
3225 } while (next_if(','));
3226 parameters_finished:
3227 rem_anchor_token(',');
3230 rem_anchor_token(')');
3234 typedef enum construct_type_kind_t {
3235 CONSTRUCT_POINTER = 1,
3236 CONSTRUCT_REFERENCE,
3239 } construct_type_kind_t;
3241 typedef union construct_type_t construct_type_t;
3243 typedef struct construct_type_base_t {
3244 construct_type_kind_t kind;
3245 source_position_t pos;
3246 construct_type_t *next;
3247 } construct_type_base_t;
3249 typedef struct parsed_pointer_t {
3250 construct_type_base_t base;
3251 type_qualifiers_t type_qualifiers;
3252 variable_t *base_variable; /**< MS __based extension. */
3255 typedef struct parsed_reference_t {
3256 construct_type_base_t base;
3257 } parsed_reference_t;
3259 typedef struct construct_function_type_t {
3260 construct_type_base_t base;
3261 type_t *function_type;
3262 } construct_function_type_t;
3264 typedef struct parsed_array_t {
3265 construct_type_base_t base;
3266 type_qualifiers_t type_qualifiers;
3272 union construct_type_t {
3273 construct_type_kind_t kind;
3274 construct_type_base_t base;
3275 parsed_pointer_t pointer;
3276 parsed_reference_t reference;
3277 construct_function_type_t function;
3278 parsed_array_t array;
3281 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3283 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3284 memset(cons, 0, size);
3286 cons->base.pos = *HERE;
3291 static construct_type_t *parse_pointer_declarator(void)
3293 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3295 cons->pointer.type_qualifiers = parse_type_qualifiers();
3296 //cons->pointer.base_variable = base_variable;
3301 /* ISO/IEC 14882:1998(E) §8.3.2 */
3302 static construct_type_t *parse_reference_declarator(void)
3304 if (!(c_mode & _CXX))
3305 errorf(HERE, "references are only available for C++");
3307 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3314 static construct_type_t *parse_array_declarator(void)
3316 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3317 parsed_array_t *const array = &cons->array;
3320 add_anchor_token(']');
3322 bool is_static = next_if(T_static);
3324 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3327 is_static = next_if(T_static);
3329 array->type_qualifiers = type_qualifiers;
3330 array->is_static = is_static;
3332 expression_t *size = NULL;
3333 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3334 array->is_variable = true;
3336 } else if (token.kind != ']') {
3337 size = parse_assignment_expression();
3339 /* §6.7.5.2:1 Array size must have integer type */
3340 type_t *const orig_type = size->base.type;
3341 type_t *const type = skip_typeref(orig_type);
3342 if (!is_type_integer(type) && is_type_valid(type)) {
3343 errorf(&size->base.source_position,
3344 "array size '%E' must have integer type but has type '%T'",
3349 mark_vars_read(size, NULL);
3352 if (is_static && size == NULL)
3353 errorf(&array->base.pos, "static array parameters require a size");
3355 rem_anchor_token(']');
3361 static construct_type_t *parse_function_declarator(scope_t *scope)
3363 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3365 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3366 function_type_t *ftype = &type->function;
3368 ftype->linkage = current_linkage;
3369 ftype->calling_convention = CC_DEFAULT;
3371 parse_parameters(ftype, scope);
3373 cons->function.function_type = type;
3378 typedef struct parse_declarator_env_t {
3379 bool may_be_abstract : 1;
3380 bool must_be_abstract : 1;
3381 decl_modifiers_t modifiers;
3383 source_position_t source_position;
3385 attribute_t *attributes;
3386 } parse_declarator_env_t;
3389 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3391 /* construct a single linked list of construct_type_t's which describe
3392 * how to construct the final declarator type */
3393 construct_type_t *first = NULL;
3394 construct_type_t **anchor = &first;
3396 env->attributes = parse_attributes(env->attributes);
3399 construct_type_t *type;
3400 //variable_t *based = NULL; /* MS __based extension */
3401 switch (token.kind) {
3403 type = parse_reference_declarator();
3407 panic("based not supported anymore");
3412 type = parse_pointer_declarator();
3416 goto ptr_operator_end;
3420 anchor = &type->base.next;
3422 /* TODO: find out if this is correct */
3423 env->attributes = parse_attributes(env->attributes);
3427 construct_type_t *inner_types = NULL;
3429 switch (token.kind) {
3431 if (env->must_be_abstract) {
3432 errorf(HERE, "no identifier expected in typename");
3434 env->symbol = token.base.symbol;
3435 env->source_position = *HERE;
3441 /* Parenthesized declarator or function declarator? */
3442 token_t const *const la1 = look_ahead(1);
3443 switch (la1->kind) {
3445 if (is_typedef_symbol(la1->base.symbol)) {
3447 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3448 * interpreted as ``function with no parameter specification'', rather
3449 * than redundant parentheses around the omitted identifier. */
3451 /* Function declarator. */
3452 if (!env->may_be_abstract) {
3453 errorf(HERE, "function declarator must have a name");
3460 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3461 /* Paranthesized declarator. */
3463 add_anchor_token(')');
3464 inner_types = parse_inner_declarator(env);
3465 if (inner_types != NULL) {
3466 /* All later declarators only modify the return type */
3467 env->must_be_abstract = true;
3469 rem_anchor_token(')');
3478 if (env->may_be_abstract)
3480 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3485 construct_type_t **const p = anchor;
3488 construct_type_t *type;
3489 switch (token.kind) {
3491 scope_t *scope = NULL;
3492 if (!env->must_be_abstract) {
3493 scope = &env->parameters;
3496 type = parse_function_declarator(scope);
3500 type = parse_array_declarator();
3503 goto declarator_finished;
3506 /* insert in the middle of the list (at p) */
3507 type->base.next = *p;
3510 anchor = &type->base.next;
3513 declarator_finished:
3514 /* append inner_types at the end of the list, we don't to set anchor anymore
3515 * as it's not needed anymore */
3516 *anchor = inner_types;
3521 static type_t *construct_declarator_type(construct_type_t *construct_list,
3524 construct_type_t *iter = construct_list;
3525 for (; iter != NULL; iter = iter->base.next) {
3526 source_position_t const* const pos = &iter->base.pos;
3527 switch (iter->kind) {
3528 case CONSTRUCT_FUNCTION: {
3529 construct_function_type_t *function = &iter->function;
3530 type_t *function_type = function->function_type;
3532 function_type->function.return_type = type;
3534 type_t *skipped_return_type = skip_typeref(type);
3536 if (is_type_function(skipped_return_type)) {
3537 errorf(pos, "function returning function is not allowed");
3538 } else if (is_type_array(skipped_return_type)) {
3539 errorf(pos, "function returning array is not allowed");
3541 if (skipped_return_type->base.qualifiers != 0) {
3542 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3546 /* The function type was constructed earlier. Freeing it here will
3547 * destroy other types. */
3548 type = typehash_insert(function_type);
3552 case CONSTRUCT_POINTER: {
3553 if (is_type_reference(skip_typeref(type)))
3554 errorf(pos, "cannot declare a pointer to reference");
3556 parsed_pointer_t *pointer = &iter->pointer;
3557 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3561 case CONSTRUCT_REFERENCE:
3562 if (is_type_reference(skip_typeref(type)))
3563 errorf(pos, "cannot declare a reference to reference");
3565 type = make_reference_type(type);
3568 case CONSTRUCT_ARRAY: {
3569 if (is_type_reference(skip_typeref(type)))
3570 errorf(pos, "cannot declare an array of references");
3572 parsed_array_t *array = &iter->array;
3573 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3575 expression_t *size_expression = array->size;
3576 if (size_expression != NULL) {
3578 = create_implicit_cast(size_expression, type_size_t);
3581 array_type->base.qualifiers = array->type_qualifiers;
3582 array_type->array.element_type = type;
3583 array_type->array.is_static = array->is_static;
3584 array_type->array.is_variable = array->is_variable;
3585 array_type->array.size_expression = size_expression;
3587 if (size_expression != NULL) {
3588 switch (is_constant_expression(size_expression)) {
3589 case EXPR_CLASS_CONSTANT: {
3590 long const size = fold_constant_to_int(size_expression);
3591 array_type->array.size = size;
3592 array_type->array.size_constant = true;
3593 /* §6.7.5.2:1 If the expression is a constant expression,
3594 * it shall have a value greater than zero. */
3596 errorf(&size_expression->base.source_position,
3597 "size of array must be greater than zero");
3598 } else if (size == 0 && !GNU_MODE) {
3599 errorf(&size_expression->base.source_position,
3600 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3605 case EXPR_CLASS_VARIABLE:
3606 array_type->array.is_vla = true;
3609 case EXPR_CLASS_ERROR:
3614 type_t *skipped_type = skip_typeref(type);
3616 if (is_type_incomplete(skipped_type)) {
3617 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3618 } else if (is_type_function(skipped_type)) {
3619 errorf(pos, "array of functions is not allowed");
3621 type = identify_new_type(array_type);
3625 internal_errorf(pos, "invalid type construction found");
3631 static type_t *automatic_type_conversion(type_t *orig_type);
3633 static type_t *semantic_parameter(const source_position_t *pos,
3635 const declaration_specifiers_t *specifiers,
3636 entity_t const *const param)
3638 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3639 * shall be adjusted to ``qualified pointer to type'',
3641 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3642 * type'' shall be adjusted to ``pointer to function
3643 * returning type'', as in 6.3.2.1. */
3644 type = automatic_type_conversion(type);
3646 if (specifiers->is_inline && is_type_valid(type)) {
3647 errorf(pos, "'%N' declared 'inline'", param);
3650 /* §6.9.1:6 The declarations in the declaration list shall contain
3651 * no storage-class specifier other than register and no
3652 * initializations. */
3653 if (specifiers->thread_local || (
3654 specifiers->storage_class != STORAGE_CLASS_NONE &&
3655 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3657 errorf(pos, "invalid storage class for '%N'", param);
3660 /* delay test for incomplete type, because we might have (void)
3661 * which is legal but incomplete... */
3666 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3667 declarator_flags_t flags)
3669 parse_declarator_env_t env;
3670 memset(&env, 0, sizeof(env));
3671 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3673 construct_type_t *construct_type = parse_inner_declarator(&env);
3675 construct_declarator_type(construct_type, specifiers->type);
3676 type_t *type = skip_typeref(orig_type);
3678 if (construct_type != NULL) {
3679 obstack_free(&temp_obst, construct_type);
3682 attribute_t *attributes = parse_attributes(env.attributes);
3683 /* append (shared) specifier attribute behind attributes of this
3685 attribute_t **anchor = &attributes;
3686 while (*anchor != NULL)
3687 anchor = &(*anchor)->next;
3688 *anchor = specifiers->attributes;
3691 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3692 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3693 entity->typedefe.type = orig_type;
3695 if (anonymous_entity != NULL) {
3696 if (is_type_compound(type)) {
3697 assert(anonymous_entity->compound.alias == NULL);
3698 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3699 anonymous_entity->kind == ENTITY_UNION);
3700 anonymous_entity->compound.alias = entity;
3701 anonymous_entity = NULL;
3702 } else if (is_type_enum(type)) {
3703 assert(anonymous_entity->enume.alias == NULL);
3704 assert(anonymous_entity->kind == ENTITY_ENUM);
3705 anonymous_entity->enume.alias = entity;
3706 anonymous_entity = NULL;
3710 /* create a declaration type entity */
3711 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3712 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3713 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3715 if (env.symbol != NULL) {
3716 if (specifiers->is_inline && is_type_valid(type)) {
3717 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3720 if (specifiers->thread_local ||
3721 specifiers->storage_class != STORAGE_CLASS_NONE) {
3722 errorf(&env.source_position, "'%N' must have no storage class", entity);
3725 } else if (flags & DECL_IS_PARAMETER) {
3726 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3727 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3728 } else if (is_type_function(type)) {
3729 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3730 entity->function.is_inline = specifiers->is_inline;
3731 entity->function.elf_visibility = default_visibility;
3732 entity->function.parameters = env.parameters;
3734 if (env.symbol != NULL) {
3735 /* this needs fixes for C++ */
3736 bool in_function_scope = current_function != NULL;
3738 if (specifiers->thread_local || (
3739 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3740 specifiers->storage_class != STORAGE_CLASS_NONE &&
3741 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3743 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3747 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3748 entity->variable.elf_visibility = default_visibility;
3749 entity->variable.thread_local = specifiers->thread_local;
3751 if (env.symbol != NULL) {
3752 if (specifiers->is_inline && is_type_valid(type)) {
3753 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3756 bool invalid_storage_class = false;
3757 if (current_scope == file_scope) {
3758 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3759 specifiers->storage_class != STORAGE_CLASS_NONE &&
3760 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3761 invalid_storage_class = true;
3764 if (specifiers->thread_local &&
3765 specifiers->storage_class == STORAGE_CLASS_NONE) {
3766 invalid_storage_class = true;
3769 if (invalid_storage_class) {
3770 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3775 entity->declaration.type = orig_type;
3776 entity->declaration.alignment = get_type_alignment(orig_type);
3777 entity->declaration.modifiers = env.modifiers;
3778 entity->declaration.attributes = attributes;
3780 storage_class_t storage_class = specifiers->storage_class;
3781 entity->declaration.declared_storage_class = storage_class;
3783 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3784 storage_class = STORAGE_CLASS_AUTO;
3785 entity->declaration.storage_class = storage_class;
3788 if (attributes != NULL) {
3789 handle_entity_attributes(attributes, entity);
3792 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3793 adapt_special_functions(&entity->function);
3799 static type_t *parse_abstract_declarator(type_t *base_type)
3801 parse_declarator_env_t env;
3802 memset(&env, 0, sizeof(env));
3803 env.may_be_abstract = true;
3804 env.must_be_abstract = true;
3806 construct_type_t *construct_type = parse_inner_declarator(&env);
3808 type_t *result = construct_declarator_type(construct_type, base_type);
3809 if (construct_type != NULL) {
3810 obstack_free(&temp_obst, construct_type);
3812 result = handle_type_attributes(env.attributes, result);
3818 * Check if the declaration of main is suspicious. main should be a
3819 * function with external linkage, returning int, taking either zero
3820 * arguments, two, or three arguments of appropriate types, ie.
3822 * int main([ int argc, char **argv [, char **env ] ]).
3824 * @param decl the declaration to check
3825 * @param type the function type of the declaration
3827 static void check_main(const entity_t *entity)
3829 const source_position_t *pos = &entity->base.source_position;
3830 if (entity->kind != ENTITY_FUNCTION) {
3831 warningf(WARN_MAIN, pos, "'main' is not a function");
3835 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3836 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3839 type_t *type = skip_typeref(entity->declaration.type);
3840 assert(is_type_function(type));
3842 function_type_t const *const func_type = &type->function;
3843 type_t *const ret_type = func_type->return_type;
3844 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3845 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3847 const function_parameter_t *parm = func_type->parameters;
3849 type_t *const first_type = skip_typeref(parm->type);
3850 type_t *const first_type_unqual = get_unqualified_type(first_type);
3851 if (!types_compatible(first_type_unqual, type_int)) {
3852 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3856 type_t *const second_type = skip_typeref(parm->type);
3857 type_t *const second_type_unqual
3858 = get_unqualified_type(second_type);
3859 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3860 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3864 type_t *const third_type = skip_typeref(parm->type);
3865 type_t *const third_type_unqual
3866 = get_unqualified_type(third_type);
3867 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3868 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3872 goto warn_arg_count;
3876 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3881 static void error_redefined_as_different_kind(const source_position_t *pos,
3882 const entity_t *old, entity_kind_t new_kind)
3884 char const *const what = get_entity_kind_name(new_kind);
3885 source_position_t const *const ppos = &old->base.source_position;
3886 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3889 static bool is_entity_valid(entity_t *const ent)
3891 if (is_declaration(ent)) {
3892 return is_type_valid(skip_typeref(ent->declaration.type));
3893 } else if (ent->kind == ENTITY_TYPEDEF) {
3894 return is_type_valid(skip_typeref(ent->typedefe.type));
3899 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3901 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3902 if (attributes_equal(tattr, attr))
3909 * test wether new_list contains any attributes not included in old_list
3911 static bool has_new_attributes(const attribute_t *old_list,
3912 const attribute_t *new_list)
3914 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3915 if (!contains_attribute(old_list, attr))
3922 * Merge in attributes from an attribute list (probably from a previous
3923 * declaration with the same name). Warning: destroys the old structure
3924 * of the attribute list - don't reuse attributes after this call.
3926 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3929 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3931 if (contains_attribute(decl->attributes, attr))
3934 /* move attribute to new declarations attributes list */
3935 attr->next = decl->attributes;
3936 decl->attributes = attr;
3940 static bool is_main(entity_t*);
3943 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3944 * for various problems that occur for multiple definitions
3946 entity_t *record_entity(entity_t *entity, const bool is_definition)
3948 const symbol_t *const symbol = entity->base.symbol;
3949 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3950 const source_position_t *pos = &entity->base.source_position;
3952 /* can happen in error cases */
3956 assert(!entity->base.parent_scope);
3957 assert(current_scope);
3958 entity->base.parent_scope = current_scope;
3960 entity_t *const previous_entity = get_entity(symbol, namespc);
3961 /* pushing the same entity twice will break the stack structure */
3962 assert(previous_entity != entity);
3964 if (entity->kind == ENTITY_FUNCTION) {
3965 type_t *const orig_type = entity->declaration.type;
3966 type_t *const type = skip_typeref(orig_type);
3968 assert(is_type_function(type));
3969 if (type->function.unspecified_parameters &&
3970 previous_entity == NULL &&
3971 !entity->declaration.implicit) {
3972 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3975 if (is_main(entity)) {
3980 if (is_declaration(entity) &&
3981 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3982 current_scope != file_scope &&
3983 !entity->declaration.implicit) {
3984 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3987 if (previous_entity != NULL) {
3988 source_position_t const *const ppos = &previous_entity->base.source_position;
3990 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3991 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3992 assert(previous_entity->kind == ENTITY_PARAMETER);
3993 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3997 if (previous_entity->base.parent_scope == current_scope) {
3998 if (previous_entity->kind != entity->kind) {
3999 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4000 error_redefined_as_different_kind(pos, previous_entity,
4005 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4006 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4009 if (previous_entity->kind == ENTITY_TYPEDEF) {
4010 type_t *const type = skip_typeref(entity->typedefe.type);
4011 type_t *const prev_type
4012 = skip_typeref(previous_entity->typedefe.type);
4013 if (c_mode & _CXX) {
4014 /* C++ allows double typedef if they are identical
4015 * (after skipping typedefs) */
4016 if (type == prev_type)
4019 /* GCC extension: redef in system headers is allowed */
4020 if ((pos->is_system_header || ppos->is_system_header) &&
4021 types_compatible(type, prev_type))
4024 errorf(pos, "redefinition of '%N' (declared %P)",
4029 /* at this point we should have only VARIABLES or FUNCTIONS */
4030 assert(is_declaration(previous_entity) && is_declaration(entity));
4032 declaration_t *const prev_decl = &previous_entity->declaration;
4033 declaration_t *const decl = &entity->declaration;
4035 /* can happen for K&R style declarations */
4036 if (prev_decl->type == NULL &&
4037 previous_entity->kind == ENTITY_PARAMETER &&
4038 entity->kind == ENTITY_PARAMETER) {
4039 prev_decl->type = decl->type;
4040 prev_decl->storage_class = decl->storage_class;
4041 prev_decl->declared_storage_class = decl->declared_storage_class;
4042 prev_decl->modifiers = decl->modifiers;
4043 return previous_entity;
4046 type_t *const type = skip_typeref(decl->type);
4047 type_t *const prev_type = skip_typeref(prev_decl->type);
4049 if (!types_compatible(type, prev_type)) {
4050 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4052 unsigned old_storage_class = prev_decl->storage_class;
4054 if (is_definition &&
4056 !(prev_decl->modifiers & DM_USED) &&
4057 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4058 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4061 storage_class_t new_storage_class = decl->storage_class;
4063 /* pretend no storage class means extern for function
4064 * declarations (except if the previous declaration is neither
4065 * none nor extern) */
4066 if (entity->kind == ENTITY_FUNCTION) {
4067 /* the previous declaration could have unspecified parameters or
4068 * be a typedef, so use the new type */
4069 if (prev_type->function.unspecified_parameters || is_definition)
4070 prev_decl->type = type;
4072 switch (old_storage_class) {
4073 case STORAGE_CLASS_NONE:
4074 old_storage_class = STORAGE_CLASS_EXTERN;
4077 case STORAGE_CLASS_EXTERN:
4078 if (is_definition) {
4079 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4080 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4082 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4083 new_storage_class = STORAGE_CLASS_EXTERN;
4090 } else if (is_type_incomplete(prev_type)) {
4091 prev_decl->type = type;
4094 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4095 new_storage_class == STORAGE_CLASS_EXTERN) {
4097 warn_redundant_declaration: ;
4099 = has_new_attributes(prev_decl->attributes,
4101 if (has_new_attrs) {
4102 merge_in_attributes(decl, prev_decl->attributes);
4103 } else if (!is_definition &&
4104 is_type_valid(prev_type) &&
4105 !pos->is_system_header) {
4106 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4108 } else if (current_function == NULL) {
4109 if (old_storage_class != STORAGE_CLASS_STATIC &&
4110 new_storage_class == STORAGE_CLASS_STATIC) {
4111 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4112 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4113 prev_decl->storage_class = STORAGE_CLASS_NONE;
4114 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4116 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4118 goto error_redeclaration;
4119 goto warn_redundant_declaration;
4121 } else if (is_type_valid(prev_type)) {
4122 if (old_storage_class == new_storage_class) {
4123 error_redeclaration:
4124 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4126 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4131 prev_decl->modifiers |= decl->modifiers;
4132 if (entity->kind == ENTITY_FUNCTION) {
4133 previous_entity->function.is_inline |= entity->function.is_inline;
4135 return previous_entity;
4139 if (is_warn_on(why = WARN_SHADOW) ||
4140 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4141 char const *const what = get_entity_kind_name(previous_entity->kind);
4142 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4146 if (entity->kind == ENTITY_FUNCTION) {
4147 if (is_definition &&
4148 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4150 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4151 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4153 goto warn_missing_declaration;
4156 } else if (entity->kind == ENTITY_VARIABLE) {
4157 if (current_scope == file_scope &&
4158 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4159 !entity->declaration.implicit) {
4160 warn_missing_declaration:
4161 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4166 environment_push(entity);
4167 append_entity(current_scope, entity);
4172 static void parser_error_multiple_definition(entity_t *entity,
4173 const source_position_t *source_position)
4175 errorf(source_position, "redefinition of '%N' (declared %P)", entity, &entity->base.source_position);
4178 static bool is_declaration_specifier(const token_t *token)
4180 switch (token->kind) {
4184 return is_typedef_symbol(token->base.symbol);
4191 static void parse_init_declarator_rest(entity_t *entity)
4193 type_t *orig_type = type_error_type;
4195 if (entity->base.kind == ENTITY_TYPEDEF) {
4196 source_position_t const *const pos = &entity->base.source_position;
4197 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4199 assert(is_declaration(entity));
4200 orig_type = entity->declaration.type;
4203 type_t *type = skip_typeref(orig_type);
4205 if (entity->kind == ENTITY_VARIABLE
4206 && entity->variable.initializer != NULL) {
4207 parser_error_multiple_definition(entity, HERE);
4211 declaration_t *const declaration = &entity->declaration;
4212 bool must_be_constant = false;
4213 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4214 entity->base.parent_scope == file_scope) {
4215 must_be_constant = true;
4218 if (is_type_function(type)) {
4219 source_position_t const *const pos = &entity->base.source_position;
4220 errorf(pos, "'%N' is initialized like a variable", entity);
4221 orig_type = type_error_type;
4224 parse_initializer_env_t env;
4225 env.type = orig_type;
4226 env.must_be_constant = must_be_constant;
4227 env.entity = entity;
4229 initializer_t *initializer = parse_initializer(&env);
4231 if (entity->kind == ENTITY_VARIABLE) {
4232 /* §6.7.5:22 array initializers for arrays with unknown size
4233 * determine the array type size */
4234 declaration->type = env.type;
4235 entity->variable.initializer = initializer;
4239 /* parse rest of a declaration without any declarator */
4240 static void parse_anonymous_declaration_rest(
4241 const declaration_specifiers_t *specifiers)
4244 anonymous_entity = NULL;
4246 source_position_t const *const pos = &specifiers->source_position;
4247 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4248 specifiers->thread_local) {
4249 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4252 type_t *type = specifiers->type;
4253 switch (type->kind) {
4254 case TYPE_COMPOUND_STRUCT:
4255 case TYPE_COMPOUND_UNION: {
4256 if (type->compound.compound->base.symbol == NULL) {
4257 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4266 warningf(WARN_OTHER, pos, "empty declaration");
4271 static void check_variable_type_complete(entity_t *ent)
4273 if (ent->kind != ENTITY_VARIABLE)
4276 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4277 * type for the object shall be complete [...] */
4278 declaration_t *decl = &ent->declaration;
4279 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4280 decl->storage_class == STORAGE_CLASS_STATIC)
4283 type_t *const type = skip_typeref(decl->type);
4284 if (!is_type_incomplete(type))
4287 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4288 * are given length one. */
4289 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4290 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4294 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4298 static void parse_declaration_rest(entity_t *ndeclaration,
4299 const declaration_specifiers_t *specifiers,
4300 parsed_declaration_func finished_declaration,
4301 declarator_flags_t flags)
4303 add_anchor_token(';');
4304 add_anchor_token(',');
4306 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4308 if (token.kind == '=') {
4309 parse_init_declarator_rest(entity);
4310 } else if (entity->kind == ENTITY_VARIABLE) {
4311 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4312 * [...] where the extern specifier is explicitly used. */
4313 declaration_t *decl = &entity->declaration;
4314 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4315 is_type_reference(skip_typeref(decl->type))) {
4316 source_position_t const *const pos = &entity->base.source_position;
4317 errorf(pos, "reference '%#N' must be initialized", entity);
4321 check_variable_type_complete(entity);
4326 add_anchor_token('=');
4327 ndeclaration = parse_declarator(specifiers, flags);
4328 rem_anchor_token('=');
4330 rem_anchor_token(',');
4331 rem_anchor_token(';');
4334 anonymous_entity = NULL;
4337 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4339 symbol_t *symbol = entity->base.symbol;
4343 assert(entity->base.namespc == NAMESPACE_NORMAL);
4344 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4345 if (previous_entity == NULL
4346 || previous_entity->base.parent_scope != current_scope) {
4347 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4352 if (is_definition) {
4353 errorf(HERE, "'%N' is initialised", entity);
4356 return record_entity(entity, false);
4359 static void parse_declaration(parsed_declaration_func finished_declaration,
4360 declarator_flags_t flags)
4362 add_anchor_token(';');
4363 declaration_specifiers_t specifiers;
4364 parse_declaration_specifiers(&specifiers);
4365 rem_anchor_token(';');
4367 if (token.kind == ';') {
4368 parse_anonymous_declaration_rest(&specifiers);
4370 entity_t *entity = parse_declarator(&specifiers, flags);
4371 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4376 static type_t *get_default_promoted_type(type_t *orig_type)
4378 type_t *result = orig_type;
4380 type_t *type = skip_typeref(orig_type);
4381 if (is_type_integer(type)) {
4382 result = promote_integer(type);
4383 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4384 result = type_double;
4390 static void parse_kr_declaration_list(entity_t *entity)
4392 if (entity->kind != ENTITY_FUNCTION)
4395 type_t *type = skip_typeref(entity->declaration.type);
4396 assert(is_type_function(type));
4397 if (!type->function.kr_style_parameters)
4400 add_anchor_token('{');
4402 PUSH_SCOPE(&entity->function.parameters);
4404 entity_t *parameter = entity->function.parameters.entities;
4405 for ( ; parameter != NULL; parameter = parameter->base.next) {
4406 assert(parameter->base.parent_scope == NULL);
4407 parameter->base.parent_scope = current_scope;
4408 environment_push(parameter);
4411 /* parse declaration list */
4413 switch (token.kind) {
4415 /* This covers symbols, which are no type, too, and results in
4416 * better error messages. The typical cases are misspelled type
4417 * names and missing includes. */
4419 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4429 /* update function type */
4430 type_t *new_type = duplicate_type(type);
4432 function_parameter_t *parameters = NULL;
4433 function_parameter_t **anchor = ¶meters;
4435 /* did we have an earlier prototype? */
4436 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4437 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4440 function_parameter_t *proto_parameter = NULL;
4441 if (proto_type != NULL) {
4442 type_t *proto_type_type = proto_type->declaration.type;
4443 proto_parameter = proto_type_type->function.parameters;
4444 /* If a K&R function definition has a variadic prototype earlier, then
4445 * make the function definition variadic, too. This should conform to
4446 * §6.7.5.3:15 and §6.9.1:8. */
4447 new_type->function.variadic = proto_type_type->function.variadic;
4449 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4451 new_type->function.unspecified_parameters = true;
4454 bool need_incompatible_warning = false;
4455 parameter = entity->function.parameters.entities;
4456 for (; parameter != NULL; parameter = parameter->base.next,
4458 proto_parameter == NULL ? NULL : proto_parameter->next) {
4459 if (parameter->kind != ENTITY_PARAMETER)
4462 type_t *parameter_type = parameter->declaration.type;
4463 if (parameter_type == NULL) {
4464 source_position_t const* const pos = ¶meter->base.source_position;
4466 errorf(pos, "no type specified for function '%N'", parameter);
4467 parameter_type = type_error_type;
4469 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4470 parameter_type = type_int;
4472 parameter->declaration.type = parameter_type;
4475 semantic_parameter_incomplete(parameter);
4477 /* we need the default promoted types for the function type */
4478 type_t *not_promoted = parameter_type;
4479 parameter_type = get_default_promoted_type(parameter_type);
4481 /* gcc special: if the type of the prototype matches the unpromoted
4482 * type don't promote */
4483 if (!strict_mode && proto_parameter != NULL) {
4484 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4485 type_t *promo_skip = skip_typeref(parameter_type);
4486 type_t *param_skip = skip_typeref(not_promoted);
4487 if (!types_compatible(proto_p_type, promo_skip)
4488 && types_compatible(proto_p_type, param_skip)) {
4490 need_incompatible_warning = true;
4491 parameter_type = not_promoted;
4494 function_parameter_t *const function_parameter
4495 = allocate_parameter(parameter_type);
4497 *anchor = function_parameter;
4498 anchor = &function_parameter->next;
4501 new_type->function.parameters = parameters;
4502 new_type = identify_new_type(new_type);
4504 if (need_incompatible_warning) {
4505 symbol_t const *const sym = entity->base.symbol;
4506 source_position_t const *const pos = &entity->base.source_position;
4507 source_position_t const *const ppos = &proto_type->base.source_position;
4508 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4510 entity->declaration.type = new_type;
4512 rem_anchor_token('{');
4515 static bool first_err = true;
4518 * When called with first_err set, prints the name of the current function,
4521 static void print_in_function(void)
4525 char const *const file = current_function->base.base.source_position.input_name;
4526 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4531 * Check if all labels are defined in the current function.
4532 * Check if all labels are used in the current function.
4534 static void check_labels(void)
4536 for (const goto_statement_t *goto_statement = goto_first;
4537 goto_statement != NULL;
4538 goto_statement = goto_statement->next) {
4539 label_t *label = goto_statement->label;
4540 if (label->base.source_position.input_name == NULL) {
4541 print_in_function();
4542 source_position_t const *const pos = &goto_statement->base.source_position;
4543 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4547 if (is_warn_on(WARN_UNUSED_LABEL)) {
4548 for (const label_statement_t *label_statement = label_first;
4549 label_statement != NULL;
4550 label_statement = label_statement->next) {
4551 label_t *label = label_statement->label;
4553 if (! label->used) {
4554 print_in_function();
4555 source_position_t const *const pos = &label_statement->base.source_position;
4556 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4562 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4564 entity_t const *const end = last != NULL ? last->base.next : NULL;
4565 for (; entity != end; entity = entity->base.next) {
4566 if (!is_declaration(entity))
4569 declaration_t *declaration = &entity->declaration;
4570 if (declaration->implicit)
4573 if (!declaration->used) {
4574 print_in_function();
4575 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4576 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4577 print_in_function();
4578 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4583 static void check_unused_variables(statement_t *const stmt, void *const env)
4587 switch (stmt->kind) {
4588 case STATEMENT_DECLARATION: {
4589 declaration_statement_t const *const decls = &stmt->declaration;
4590 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4595 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4604 * Check declarations of current_function for unused entities.
4606 static void check_declarations(void)
4608 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4609 const scope_t *scope = ¤t_function->parameters;
4610 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4612 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4613 walk_statements(current_function->statement, check_unused_variables,
4618 static int determine_truth(expression_t const* const cond)
4621 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4622 fold_constant_to_bool(cond) ? 1 :
4626 static void check_reachable(statement_t *);
4627 static bool reaches_end;
4629 static bool expression_returns(expression_t const *const expr)
4631 switch (expr->kind) {
4633 expression_t const *const func = expr->call.function;
4634 type_t const *const type = skip_typeref(func->base.type);
4635 if (type->kind == TYPE_POINTER) {
4636 type_t const *const points_to
4637 = skip_typeref(type->pointer.points_to);
4638 if (points_to->kind == TYPE_FUNCTION
4639 && points_to->function.modifiers & DM_NORETURN)
4643 if (!expression_returns(func))
4646 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4647 if (!expression_returns(arg->expression))
4654 case EXPR_REFERENCE:
4655 case EXPR_ENUM_CONSTANT:
4656 case EXPR_LITERAL_CASES:
4657 case EXPR_STRING_LITERAL:
4658 case EXPR_WIDE_STRING_LITERAL:
4659 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4660 case EXPR_LABEL_ADDRESS:
4661 case EXPR_CLASSIFY_TYPE:
4662 case EXPR_SIZEOF: // TODO handle obscure VLA case
4665 case EXPR_BUILTIN_CONSTANT_P:
4666 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4671 case EXPR_STATEMENT: {
4672 bool old_reaches_end = reaches_end;
4673 reaches_end = false;
4674 check_reachable(expr->statement.statement);
4675 bool returns = reaches_end;
4676 reaches_end = old_reaches_end;
4680 case EXPR_CONDITIONAL:
4681 // TODO handle constant expression
4683 if (!expression_returns(expr->conditional.condition))
4686 if (expr->conditional.true_expression != NULL
4687 && expression_returns(expr->conditional.true_expression))
4690 return expression_returns(expr->conditional.false_expression);
4693 return expression_returns(expr->select.compound);
4695 case EXPR_ARRAY_ACCESS:
4697 expression_returns(expr->array_access.array_ref) &&
4698 expression_returns(expr->array_access.index);
4701 return expression_returns(expr->va_starte.ap);
4704 return expression_returns(expr->va_arge.ap);
4707 return expression_returns(expr->va_copye.src);
4709 case EXPR_UNARY_CASES_MANDATORY:
4710 return expression_returns(expr->unary.value);
4712 case EXPR_UNARY_THROW:
4715 case EXPR_BINARY_CASES:
4716 // TODO handle constant lhs of && and ||
4718 expression_returns(expr->binary.left) &&
4719 expression_returns(expr->binary.right);
4722 panic("unhandled expression");
4725 static bool initializer_returns(initializer_t const *const init)
4727 switch (init->kind) {
4728 case INITIALIZER_VALUE:
4729 return expression_returns(init->value.value);
4731 case INITIALIZER_LIST: {
4732 initializer_t * const* i = init->list.initializers;
4733 initializer_t * const* const end = i + init->list.len;
4734 bool returns = true;
4735 for (; i != end; ++i) {
4736 if (!initializer_returns(*i))
4742 case INITIALIZER_STRING:
4743 case INITIALIZER_WIDE_STRING:
4744 case INITIALIZER_DESIGNATOR: // designators have no payload
4747 panic("unhandled initializer");
4750 static bool noreturn_candidate;
4752 static void check_reachable(statement_t *const stmt)
4754 if (stmt->base.reachable)
4756 if (stmt->kind != STATEMENT_DO_WHILE)
4757 stmt->base.reachable = true;
4759 statement_t *last = stmt;
4761 switch (stmt->kind) {
4762 case STATEMENT_ERROR:
4763 case STATEMENT_EMPTY:
4765 next = stmt->base.next;
4768 case STATEMENT_DECLARATION: {
4769 declaration_statement_t const *const decl = &stmt->declaration;
4770 entity_t const * ent = decl->declarations_begin;
4771 entity_t const *const last_decl = decl->declarations_end;
4773 for (;; ent = ent->base.next) {
4774 if (ent->kind == ENTITY_VARIABLE &&
4775 ent->variable.initializer != NULL &&
4776 !initializer_returns(ent->variable.initializer)) {
4779 if (ent == last_decl)
4783 next = stmt->base.next;
4787 case STATEMENT_COMPOUND:
4788 next = stmt->compound.statements;
4790 next = stmt->base.next;
4793 case STATEMENT_RETURN: {
4794 expression_t const *const val = stmt->returns.value;
4795 if (val == NULL || expression_returns(val))
4796 noreturn_candidate = false;
4800 case STATEMENT_IF: {
4801 if_statement_t const *const ifs = &stmt->ifs;
4802 expression_t const *const cond = ifs->condition;
4804 if (!expression_returns(cond))
4807 int const val = determine_truth(cond);
4810 check_reachable(ifs->true_statement);
4815 if (ifs->false_statement != NULL) {
4816 check_reachable(ifs->false_statement);
4820 next = stmt->base.next;
4824 case STATEMENT_SWITCH: {
4825 switch_statement_t const *const switchs = &stmt->switchs;
4826 expression_t const *const expr = switchs->expression;
4828 if (!expression_returns(expr))
4831 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4832 long const val = fold_constant_to_int(expr);
4833 case_label_statement_t * defaults = NULL;
4834 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4835 if (i->expression == NULL) {
4840 if (i->first_case <= val && val <= i->last_case) {
4841 check_reachable((statement_t*)i);
4846 if (defaults != NULL) {
4847 check_reachable((statement_t*)defaults);
4851 bool has_default = false;
4852 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4853 if (i->expression == NULL)
4856 check_reachable((statement_t*)i);
4863 next = stmt->base.next;
4867 case STATEMENT_EXPRESSION: {
4868 /* Check for noreturn function call */
4869 expression_t const *const expr = stmt->expression.expression;
4870 if (!expression_returns(expr))
4873 next = stmt->base.next;
4877 case STATEMENT_CONTINUE:
4878 for (statement_t *parent = stmt;;) {
4879 parent = parent->base.parent;
4880 if (parent == NULL) /* continue not within loop */
4884 switch (parent->kind) {
4885 case STATEMENT_WHILE: goto continue_while;
4886 case STATEMENT_DO_WHILE: goto continue_do_while;
4887 case STATEMENT_FOR: goto continue_for;
4893 case STATEMENT_BREAK:
4894 for (statement_t *parent = stmt;;) {
4895 parent = parent->base.parent;
4896 if (parent == NULL) /* break not within loop/switch */
4899 switch (parent->kind) {
4900 case STATEMENT_SWITCH:
4901 case STATEMENT_WHILE:
4902 case STATEMENT_DO_WHILE:
4905 next = parent->base.next;
4906 goto found_break_parent;
4914 case STATEMENT_COMPUTED_GOTO: {
4915 if (!expression_returns(stmt->computed_goto.expression))
4918 statement_t *parent = stmt->base.parent;
4919 if (parent == NULL) /* top level goto */
4925 case STATEMENT_GOTO:
4926 next = stmt->gotos.label->statement;
4927 if (next == NULL) /* missing label */
4931 case STATEMENT_LABEL:
4932 next = stmt->label.statement;
4935 case STATEMENT_CASE_LABEL:
4936 next = stmt->case_label.statement;
4939 case STATEMENT_WHILE: {
4940 while_statement_t const *const whiles = &stmt->whiles;
4941 expression_t const *const cond = whiles->condition;
4943 if (!expression_returns(cond))
4946 int const val = determine_truth(cond);
4949 check_reachable(whiles->body);
4954 next = stmt->base.next;
4958 case STATEMENT_DO_WHILE:
4959 next = stmt->do_while.body;
4962 case STATEMENT_FOR: {
4963 for_statement_t *const fors = &stmt->fors;
4965 if (fors->condition_reachable)
4967 fors->condition_reachable = true;
4969 expression_t const *const cond = fors->condition;
4974 } else if (expression_returns(cond)) {
4975 val = determine_truth(cond);
4981 check_reachable(fors->body);
4986 next = stmt->base.next;
4990 case STATEMENT_MS_TRY: {
4991 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4992 check_reachable(ms_try->try_statement);
4993 next = ms_try->final_statement;
4997 case STATEMENT_LEAVE: {
4998 statement_t *parent = stmt;
5000 parent = parent->base.parent;
5001 if (parent == NULL) /* __leave not within __try */
5004 if (parent->kind == STATEMENT_MS_TRY) {
5006 next = parent->ms_try.final_statement;
5014 panic("invalid statement kind");
5017 while (next == NULL) {
5018 next = last->base.parent;
5020 noreturn_candidate = false;
5022 type_t *const type = skip_typeref(current_function->base.type);
5023 assert(is_type_function(type));
5024 type_t *const ret = skip_typeref(type->function.return_type);
5025 if (!is_type_void(ret) &&
5026 is_type_valid(ret) &&
5027 !is_main(current_entity)) {
5028 source_position_t const *const pos = &stmt->base.source_position;
5029 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5034 switch (next->kind) {
5035 case STATEMENT_ERROR:
5036 case STATEMENT_EMPTY:
5037 case STATEMENT_DECLARATION:
5038 case STATEMENT_EXPRESSION:
5040 case STATEMENT_RETURN:
5041 case STATEMENT_CONTINUE:
5042 case STATEMENT_BREAK:
5043 case STATEMENT_COMPUTED_GOTO:
5044 case STATEMENT_GOTO:
5045 case STATEMENT_LEAVE:
5046 panic("invalid control flow in function");
5048 case STATEMENT_COMPOUND:
5049 if (next->compound.stmt_expr) {
5055 case STATEMENT_SWITCH:
5056 case STATEMENT_LABEL:
5057 case STATEMENT_CASE_LABEL:
5059 next = next->base.next;
5062 case STATEMENT_WHILE: {
5064 if (next->base.reachable)
5066 next->base.reachable = true;
5068 while_statement_t const *const whiles = &next->whiles;
5069 expression_t const *const cond = whiles->condition;
5071 if (!expression_returns(cond))
5074 int const val = determine_truth(cond);
5077 check_reachable(whiles->body);
5083 next = next->base.next;
5087 case STATEMENT_DO_WHILE: {
5089 if (next->base.reachable)
5091 next->base.reachable = true;
5093 do_while_statement_t const *const dw = &next->do_while;
5094 expression_t const *const cond = dw->condition;
5096 if (!expression_returns(cond))
5099 int const val = determine_truth(cond);
5102 check_reachable(dw->body);
5108 next = next->base.next;
5112 case STATEMENT_FOR: {
5114 for_statement_t *const fors = &next->fors;
5116 fors->step_reachable = true;
5118 if (fors->condition_reachable)
5120 fors->condition_reachable = true;
5122 expression_t const *const cond = fors->condition;
5127 } else if (expression_returns(cond)) {
5128 val = determine_truth(cond);
5134 check_reachable(fors->body);
5140 next = next->base.next;
5144 case STATEMENT_MS_TRY:
5146 next = next->ms_try.final_statement;
5151 check_reachable(next);
5154 static void check_unreachable(statement_t* const stmt, void *const env)
5158 switch (stmt->kind) {
5159 case STATEMENT_DO_WHILE:
5160 if (!stmt->base.reachable) {
5161 expression_t const *const cond = stmt->do_while.condition;
5162 if (determine_truth(cond) >= 0) {
5163 source_position_t const *const pos = &cond->base.source_position;
5164 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5169 case STATEMENT_FOR: {
5170 for_statement_t const* const fors = &stmt->fors;
5172 // if init and step are unreachable, cond is unreachable, too
5173 if (!stmt->base.reachable && !fors->step_reachable) {
5174 goto warn_unreachable;
5176 if (!stmt->base.reachable && fors->initialisation != NULL) {
5177 source_position_t const *const pos = &fors->initialisation->base.source_position;
5178 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5181 if (!fors->condition_reachable && fors->condition != NULL) {
5182 source_position_t const *const pos = &fors->condition->base.source_position;
5183 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5186 if (!fors->step_reachable && fors->step != NULL) {
5187 source_position_t const *const pos = &fors->step->base.source_position;
5188 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5194 case STATEMENT_COMPOUND:
5195 if (stmt->compound.statements != NULL)
5197 goto warn_unreachable;
5199 case STATEMENT_DECLARATION: {
5200 /* Only warn if there is at least one declarator with an initializer.
5201 * This typically occurs in switch statements. */
5202 declaration_statement_t const *const decl = &stmt->declaration;
5203 entity_t const * ent = decl->declarations_begin;
5204 entity_t const *const last = decl->declarations_end;
5206 for (;; ent = ent->base.next) {
5207 if (ent->kind == ENTITY_VARIABLE &&
5208 ent->variable.initializer != NULL) {
5209 goto warn_unreachable;
5219 if (!stmt->base.reachable) {
5220 source_position_t const *const pos = &stmt->base.source_position;
5221 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5227 static bool is_main(entity_t *entity)
5229 static symbol_t *sym_main = NULL;
5230 if (sym_main == NULL) {
5231 sym_main = symbol_table_insert("main");
5234 if (entity->base.symbol != sym_main)
5236 /* must be in outermost scope */
5237 if (entity->base.parent_scope != file_scope)
5243 static void prepare_main_collect2(entity_t*);
5245 static void parse_external_declaration(void)
5247 /* function-definitions and declarations both start with declaration
5249 add_anchor_token(';');
5250 declaration_specifiers_t specifiers;
5251 parse_declaration_specifiers(&specifiers);
5252 rem_anchor_token(';');
5254 /* must be a declaration */
5255 if (token.kind == ';') {
5256 parse_anonymous_declaration_rest(&specifiers);
5260 add_anchor_token(',');
5261 add_anchor_token('=');
5262 add_anchor_token(';');
5263 add_anchor_token('{');
5265 /* declarator is common to both function-definitions and declarations */
5266 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5268 rem_anchor_token('{');
5269 rem_anchor_token(';');
5270 rem_anchor_token('=');
5271 rem_anchor_token(',');
5273 /* must be a declaration */
5274 switch (token.kind) {
5278 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5283 /* must be a function definition */
5284 parse_kr_declaration_list(ndeclaration);
5286 if (token.kind != '{') {
5287 parse_error_expected("while parsing function definition", '{', NULL);
5288 eat_until_matching_token(';');
5292 assert(is_declaration(ndeclaration));
5293 type_t *const orig_type = ndeclaration->declaration.type;
5294 type_t * type = skip_typeref(orig_type);
5296 if (!is_type_function(type)) {
5297 if (is_type_valid(type)) {
5298 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5304 source_position_t const *const pos = &ndeclaration->base.source_position;
5305 if (is_typeref(orig_type)) {
5307 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5310 if (is_type_compound(skip_typeref(type->function.return_type))) {
5311 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5313 if (type->function.unspecified_parameters) {
5314 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5316 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5319 /* §6.7.5.3:14 a function definition with () means no
5320 * parameters (and not unspecified parameters) */
5321 if (type->function.unspecified_parameters &&
5322 type->function.parameters == NULL) {
5323 type_t *copy = duplicate_type(type);
5324 copy->function.unspecified_parameters = false;
5325 type = identify_new_type(copy);
5327 ndeclaration->declaration.type = type;
5330 entity_t *const entity = record_entity(ndeclaration, true);
5331 assert(entity->kind == ENTITY_FUNCTION);
5332 assert(ndeclaration->kind == ENTITY_FUNCTION);
5334 function_t *const function = &entity->function;
5335 if (ndeclaration != entity) {
5336 function->parameters = ndeclaration->function.parameters;
5339 PUSH_SCOPE(&function->parameters);
5341 entity_t *parameter = function->parameters.entities;
5342 for (; parameter != NULL; parameter = parameter->base.next) {
5343 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5344 parameter->base.parent_scope = current_scope;
5346 assert(parameter->base.parent_scope == NULL
5347 || parameter->base.parent_scope == current_scope);
5348 parameter->base.parent_scope = current_scope;
5349 if (parameter->base.symbol == NULL) {
5350 errorf(¶meter->base.source_position, "parameter name omitted");
5353 environment_push(parameter);
5356 if (function->statement != NULL) {
5357 parser_error_multiple_definition(entity, HERE);
5360 /* parse function body */
5361 int label_stack_top = label_top();
5362 function_t *old_current_function = current_function;
5363 current_function = function;
5364 PUSH_CURRENT_ENTITY(entity);
5368 goto_anchor = &goto_first;
5370 label_anchor = &label_first;
5372 statement_t *const body = parse_compound_statement(false);
5373 function->statement = body;
5376 check_declarations();
5377 if (is_warn_on(WARN_RETURN_TYPE) ||
5378 is_warn_on(WARN_UNREACHABLE_CODE) ||
5379 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5380 noreturn_candidate = true;
5381 check_reachable(body);
5382 if (is_warn_on(WARN_UNREACHABLE_CODE))
5383 walk_statements(body, check_unreachable, NULL);
5384 if (noreturn_candidate &&
5385 !(function->base.modifiers & DM_NORETURN)) {
5386 source_position_t const *const pos = &body->base.source_position;
5387 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5391 if (is_main(entity)) {
5392 /* Force main to C linkage. */
5393 type_t *const type = entity->declaration.type;
5394 assert(is_type_function(type));
5395 if (type->function.linkage != LINKAGE_C) {
5396 type_t *new_type = duplicate_type(type);
5397 new_type->function.linkage = LINKAGE_C;
5398 entity->declaration.type = identify_new_type(new_type);
5401 if (enable_main_collect2_hack)
5402 prepare_main_collect2(entity);
5405 POP_CURRENT_ENTITY();
5407 assert(current_function == function);
5408 current_function = old_current_function;
5409 label_pop_to(label_stack_top);
5415 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5417 entity_t *iter = compound->members.entities;
5418 for (; iter != NULL; iter = iter->base.next) {
5419 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5422 if (iter->base.symbol == symbol) {
5424 } else if (iter->base.symbol == NULL) {
5425 /* search in anonymous structs and unions */
5426 type_t *type = skip_typeref(iter->declaration.type);
5427 if (is_type_compound(type)) {
5428 if (find_compound_entry(type->compound.compound, symbol)
5439 static void check_deprecated(const source_position_t *source_position,
5440 const entity_t *entity)
5442 if (!is_declaration(entity))
5444 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5447 source_position_t const *const epos = &entity->base.source_position;
5448 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5450 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5452 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5457 static expression_t *create_select(const source_position_t *pos,
5459 type_qualifiers_t qualifiers,
5462 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5464 check_deprecated(pos, entry);
5466 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5467 select->select.compound = addr;
5468 select->select.compound_entry = entry;
5470 type_t *entry_type = entry->declaration.type;
5471 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5473 /* bitfields need special treatment */
5474 if (entry->compound_member.bitfield) {
5475 unsigned bit_size = entry->compound_member.bit_size;
5476 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5477 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5478 res_type = type_int;
5482 /* we always do the auto-type conversions; the & and sizeof parser contains
5483 * code to revert this! */
5484 select->base.type = automatic_type_conversion(res_type);
5491 * Find entry with symbol in compound. Search anonymous structs and unions and
5492 * creates implicit select expressions for them.
5493 * Returns the adress for the innermost compound.
5495 static expression_t *find_create_select(const source_position_t *pos,
5497 type_qualifiers_t qualifiers,
5498 compound_t *compound, symbol_t *symbol)
5500 entity_t *iter = compound->members.entities;
5501 for (; iter != NULL; iter = iter->base.next) {
5502 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5505 symbol_t *iter_symbol = iter->base.symbol;
5506 if (iter_symbol == NULL) {
5507 type_t *type = iter->declaration.type;
5508 if (type->kind != TYPE_COMPOUND_STRUCT
5509 && type->kind != TYPE_COMPOUND_UNION)
5512 compound_t *sub_compound = type->compound.compound;
5514 if (find_compound_entry(sub_compound, symbol) == NULL)
5517 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5518 sub_addr->base.source_position = *pos;
5519 sub_addr->base.implicit = true;
5520 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5524 if (iter_symbol == symbol) {
5525 return create_select(pos, addr, qualifiers, iter);
5532 static void parse_bitfield_member(entity_t *entity)
5536 expression_t *size = parse_constant_expression();
5539 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5540 type_t *type = entity->declaration.type;
5541 if (!is_type_integer(skip_typeref(type))) {
5542 errorf(HERE, "bitfield base type '%T' is not an integer type",
5546 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5547 /* error already reported by parse_constant_expression */
5548 size_long = get_type_size(type) * 8;
5550 size_long = fold_constant_to_int(size);
5552 const symbol_t *symbol = entity->base.symbol;
5553 const symbol_t *user_symbol
5554 = symbol == NULL ? sym_anonymous : symbol;
5555 unsigned bit_size = get_type_size(type) * 8;
5556 if (size_long < 0) {
5557 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5558 } else if (size_long == 0 && symbol != NULL) {
5559 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5560 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5561 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5564 /* hope that people don't invent crazy types with more bits
5565 * than our struct can hold */
5567 (1 << sizeof(entity->compound_member.bit_size)*8));
5571 entity->compound_member.bitfield = true;
5572 entity->compound_member.bit_size = (unsigned char)size_long;
5575 static void parse_compound_declarators(compound_t *compound,
5576 const declaration_specifiers_t *specifiers)
5578 add_anchor_token(';');
5579 add_anchor_token(',');
5583 if (token.kind == ':') {
5584 /* anonymous bitfield */
5585 type_t *type = specifiers->type;
5586 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5587 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5588 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5589 entity->declaration.type = type;
5591 parse_bitfield_member(entity);
5593 attribute_t *attributes = parse_attributes(NULL);
5594 attribute_t **anchor = &attributes;
5595 while (*anchor != NULL)
5596 anchor = &(*anchor)->next;
5597 *anchor = specifiers->attributes;
5598 if (attributes != NULL) {
5599 handle_entity_attributes(attributes, entity);
5601 entity->declaration.attributes = attributes;
5603 append_entity(&compound->members, entity);
5605 entity = parse_declarator(specifiers,
5606 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5607 source_position_t const *const pos = &entity->base.source_position;
5608 if (entity->kind == ENTITY_TYPEDEF) {
5609 errorf(pos, "typedef not allowed as compound member");
5611 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5613 /* make sure we don't define a symbol multiple times */
5614 symbol_t *symbol = entity->base.symbol;
5615 if (symbol != NULL) {
5616 entity_t *prev = find_compound_entry(compound, symbol);
5618 source_position_t const *const ppos = &prev->base.source_position;
5619 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5623 if (token.kind == ':') {
5624 parse_bitfield_member(entity);
5626 attribute_t *attributes = parse_attributes(NULL);
5627 handle_entity_attributes(attributes, entity);
5629 type_t *orig_type = entity->declaration.type;
5630 type_t *type = skip_typeref(orig_type);
5631 if (is_type_function(type)) {
5632 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5633 } else if (is_type_incomplete(type)) {
5634 /* §6.7.2.1:16 flexible array member */
5635 if (!is_type_array(type) ||
5636 token.kind != ';' ||
5637 look_ahead(1)->kind != '}') {
5638 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5639 } else if (compound->members.entities == NULL) {
5640 errorf(pos, "flexible array member in otherwise empty struct");
5645 append_entity(&compound->members, entity);
5648 } while (next_if(','));
5649 rem_anchor_token(',');
5650 rem_anchor_token(';');
5653 anonymous_entity = NULL;
5656 static void parse_compound_type_entries(compound_t *compound)
5659 add_anchor_token('}');
5662 switch (token.kind) {
5664 case T___extension__:
5665 case T_IDENTIFIER: {
5667 declaration_specifiers_t specifiers;
5668 parse_declaration_specifiers(&specifiers);
5669 parse_compound_declarators(compound, &specifiers);
5675 rem_anchor_token('}');
5678 compound->complete = true;
5684 static type_t *parse_typename(void)
5686 declaration_specifiers_t specifiers;
5687 parse_declaration_specifiers(&specifiers);
5688 if (specifiers.storage_class != STORAGE_CLASS_NONE
5689 || specifiers.thread_local) {
5690 /* TODO: improve error message, user does probably not know what a
5691 * storage class is...
5693 errorf(&specifiers.source_position, "typename must not have a storage class");
5696 type_t *result = parse_abstract_declarator(specifiers.type);
5704 typedef expression_t* (*parse_expression_function)(void);
5705 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5707 typedef struct expression_parser_function_t expression_parser_function_t;
5708 struct expression_parser_function_t {
5709 parse_expression_function parser;
5710 precedence_t infix_precedence;
5711 parse_expression_infix_function infix_parser;
5714 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5716 static type_t *get_string_type(void)
5718 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5721 static type_t *get_wide_string_type(void)
5723 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5727 * Parse a string constant.
5729 static expression_t *parse_string_literal(void)
5731 string_encoding_t enc;
5732 source_position_t const pos = *HERE;
5733 string_t const res = concat_string_literals(&enc);
5735 expression_t *literal;
5736 if (enc != STRING_ENCODING_CHAR) {
5737 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5738 literal->base.type = get_wide_string_type();
5740 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5741 literal->base.type = get_string_type();
5743 literal->base.source_position = pos;
5744 literal->literal.value = res;
5750 * Parse a boolean constant.
5752 static expression_t *parse_boolean_literal(bool value)
5754 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5755 literal->base.type = type_bool;
5756 literal->literal.value.begin = value ? "true" : "false";
5757 literal->literal.value.size = value ? 4 : 5;
5759 eat(value ? T_true : T_false);
5763 static void warn_traditional_suffix(void)
5765 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5766 &token.number.suffix);
5769 static void check_integer_suffix(void)
5771 const string_t *suffix = &token.number.suffix;
5772 if (suffix->size == 0)
5775 bool not_traditional = false;
5776 const char *c = suffix->begin;
5777 if (*c == 'l' || *c == 'L') {
5780 not_traditional = true;
5782 if (*c == 'u' || *c == 'U') {
5785 } else if (*c == 'u' || *c == 'U') {
5786 not_traditional = true;
5789 } else if (*c == 'u' || *c == 'U') {
5790 not_traditional = true;
5792 if (*c == 'l' || *c == 'L') {
5800 errorf(HERE, "invalid suffix '%S' on integer constant", suffix);
5801 } else if (not_traditional) {
5802 warn_traditional_suffix();
5806 static type_t *check_floatingpoint_suffix(void)
5808 const string_t *suffix = &token.number.suffix;
5809 type_t *type = type_double;
5810 if (suffix->size == 0)
5813 bool not_traditional = false;
5814 const char *c = suffix->begin;
5815 if (*c == 'f' || *c == 'F') {
5818 } else if (*c == 'l' || *c == 'L') {
5820 type = type_long_double;
5823 errorf(HERE, "invalid suffix '%S' on floatingpoint constant", suffix);
5824 } else if (not_traditional) {
5825 warn_traditional_suffix();
5832 * Parse an integer constant.
5834 static expression_t *parse_number_literal(void)
5836 expression_kind_t kind;
5839 switch (token.kind) {
5841 kind = EXPR_LITERAL_INTEGER;
5842 check_integer_suffix();
5846 case T_FLOATINGPOINT:
5847 kind = EXPR_LITERAL_FLOATINGPOINT;
5848 type = check_floatingpoint_suffix();
5852 panic("unexpected token type in parse_number_literal");
5855 expression_t *literal = allocate_expression_zero(kind);
5856 literal->base.type = type;
5857 literal->literal.value = token.number.number;
5858 literal->literal.suffix = token.number.suffix;
5861 /* integer type depends on the size of the number and the size
5862 * representable by the types. The backend/codegeneration has to determine
5865 determine_literal_type(&literal->literal);
5870 * Parse a character constant.
5872 static expression_t *parse_character_constant(void)
5874 expression_t *literal;
5875 switch (token.string.encoding) {
5876 case STRING_ENCODING_CHAR: {
5877 literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5878 literal->base.type = c_mode & _CXX ? type_char : type_int;
5879 literal->literal.value = token.string.string;
5881 size_t len = literal->literal.value.size;
5883 if (!GNU_MODE && !(c_mode & _C99)) {
5884 errorf(HERE, "more than 1 character in character constant");
5886 literal->base.type = type_int;
5887 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5893 case STRING_ENCODING_WIDE: {
5894 literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5895 literal->base.type = type_int;
5896 literal->literal.value = token.string.string;
5898 size_t len = wstrlen(&literal->literal.value);
5900 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5906 eat(T_CHARACTER_CONSTANT);
5910 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5912 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5913 ntype->function.return_type = type_int;
5914 ntype->function.unspecified_parameters = true;
5915 ntype->function.linkage = LINKAGE_C;
5916 type_t *type = identify_new_type(ntype);
5918 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5919 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5920 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5921 entity->declaration.type = type;
5922 entity->declaration.implicit = true;
5924 if (current_scope != NULL)
5925 record_entity(entity, false);
5931 * Performs automatic type cast as described in §6.3.2.1.
5933 * @param orig_type the original type
5935 static type_t *automatic_type_conversion(type_t *orig_type)
5937 type_t *type = skip_typeref(orig_type);
5938 if (is_type_array(type)) {
5939 array_type_t *array_type = &type->array;
5940 type_t *element_type = array_type->element_type;
5941 unsigned qualifiers = array_type->base.qualifiers;
5943 return make_pointer_type(element_type, qualifiers);
5946 if (is_type_function(type)) {
5947 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5954 * reverts the automatic casts of array to pointer types and function
5955 * to function-pointer types as defined §6.3.2.1
5957 type_t *revert_automatic_type_conversion(const expression_t *expression)
5959 switch (expression->kind) {
5960 case EXPR_REFERENCE: {
5961 entity_t *entity = expression->reference.entity;
5962 if (is_declaration(entity)) {
5963 return entity->declaration.type;
5964 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5965 return entity->enum_value.enum_type;
5967 panic("no declaration or enum in reference");
5972 entity_t *entity = expression->select.compound_entry;
5973 assert(is_declaration(entity));
5974 type_t *type = entity->declaration.type;
5975 return get_qualified_type(type, expression->base.type->base.qualifiers);
5978 case EXPR_UNARY_DEREFERENCE: {
5979 const expression_t *const value = expression->unary.value;
5980 type_t *const type = skip_typeref(value->base.type);
5981 if (!is_type_pointer(type))
5982 return type_error_type;
5983 return type->pointer.points_to;
5986 case EXPR_ARRAY_ACCESS: {
5987 const expression_t *array_ref = expression->array_access.array_ref;
5988 type_t *type_left = skip_typeref(array_ref->base.type);
5989 if (!is_type_pointer(type_left))
5990 return type_error_type;
5991 return type_left->pointer.points_to;
5994 case EXPR_STRING_LITERAL: {
5995 size_t size = expression->string_literal.value.size;
5996 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5999 case EXPR_WIDE_STRING_LITERAL: {
6000 size_t size = wstrlen(&expression->string_literal.value);
6001 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6004 case EXPR_COMPOUND_LITERAL:
6005 return expression->compound_literal.type;
6010 return expression->base.type;
6014 * Find an entity matching a symbol in a scope.
6015 * Uses current scope if scope is NULL
6017 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6018 namespace_tag_t namespc)
6020 if (scope == NULL) {
6021 return get_entity(symbol, namespc);
6024 /* we should optimize here, if scope grows above a certain size we should
6025 construct a hashmap here... */
6026 entity_t *entity = scope->entities;
6027 for ( ; entity != NULL; entity = entity->base.next) {
6028 if (entity->base.symbol == symbol
6029 && (namespace_tag_t)entity->base.namespc == namespc)
6036 static entity_t *parse_qualified_identifier(void)
6038 /* namespace containing the symbol */
6040 source_position_t pos;
6041 const scope_t *lookup_scope = NULL;
6043 if (next_if(T_COLONCOLON))
6044 lookup_scope = &unit->scope;
6048 symbol = expect_identifier("while parsing identifier", &pos);
6050 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6053 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6055 if (!next_if(T_COLONCOLON))
6058 switch (entity->kind) {
6059 case ENTITY_NAMESPACE:
6060 lookup_scope = &entity->namespacee.members;
6065 lookup_scope = &entity->compound.members;
6068 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6069 symbol, get_entity_kind_name(entity->kind));
6071 /* skip further qualifications */
6072 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6074 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6078 if (entity == NULL) {
6079 if (!strict_mode && token.kind == '(') {
6080 /* an implicitly declared function */
6081 entity = create_implicit_function(symbol, &pos);
6082 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6084 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6085 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6092 static expression_t *parse_reference(void)
6094 source_position_t const pos = *HERE;
6095 entity_t *const entity = parse_qualified_identifier();
6098 if (is_declaration(entity)) {
6099 orig_type = entity->declaration.type;
6100 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6101 orig_type = entity->enum_value.enum_type;
6103 panic("expected declaration or enum value in reference");
6106 /* we always do the auto-type conversions; the & and sizeof parser contains
6107 * code to revert this! */
6108 type_t *type = automatic_type_conversion(orig_type);
6110 expression_kind_t kind = EXPR_REFERENCE;
6111 if (entity->kind == ENTITY_ENUM_VALUE)
6112 kind = EXPR_ENUM_CONSTANT;
6114 expression_t *expression = allocate_expression_zero(kind);
6115 expression->base.source_position = pos;
6116 expression->base.type = type;
6117 expression->reference.entity = entity;
6119 /* this declaration is used */
6120 if (is_declaration(entity)) {
6121 entity->declaration.used = true;
6124 if (entity->base.parent_scope != file_scope
6125 && (current_function != NULL
6126 && entity->base.parent_scope->depth < current_function->parameters.depth)
6127 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6128 /* access of a variable from an outer function */
6129 entity->variable.address_taken = true;
6130 current_function->need_closure = true;
6133 check_deprecated(&pos, entity);
6138 static bool semantic_cast(expression_t *cast)
6140 expression_t *expression = cast->unary.value;
6141 type_t *orig_dest_type = cast->base.type;
6142 type_t *orig_type_right = expression->base.type;
6143 type_t const *dst_type = skip_typeref(orig_dest_type);
6144 type_t const *src_type = skip_typeref(orig_type_right);
6145 source_position_t const *pos = &cast->base.source_position;
6147 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6148 if (is_type_void(dst_type))
6151 /* only integer and pointer can be casted to pointer */
6152 if (is_type_pointer(dst_type) &&
6153 !is_type_pointer(src_type) &&
6154 !is_type_integer(src_type) &&
6155 is_type_valid(src_type)) {
6156 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6160 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6161 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6165 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6166 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6170 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6171 type_t *src = skip_typeref(src_type->pointer.points_to);
6172 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6173 unsigned missing_qualifiers =
6174 src->base.qualifiers & ~dst->base.qualifiers;
6175 if (missing_qualifiers != 0) {
6176 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6182 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6184 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6185 expression->base.source_position = *pos;
6187 parse_initializer_env_t env;
6190 env.must_be_constant = false;
6191 initializer_t *initializer = parse_initializer(&env);
6194 expression->compound_literal.initializer = initializer;
6195 expression->compound_literal.type = type;
6196 expression->base.type = automatic_type_conversion(type);
6202 * Parse a cast expression.
6204 static expression_t *parse_cast(void)
6206 source_position_t const pos = *HERE;
6209 add_anchor_token(')');
6211 type_t *type = parse_typename();
6213 rem_anchor_token(')');
6216 if (token.kind == '{') {
6217 return parse_compound_literal(&pos, type);
6220 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6221 cast->base.source_position = pos;
6223 expression_t *value = parse_subexpression(PREC_CAST);
6224 cast->base.type = type;
6225 cast->unary.value = value;
6227 if (! semantic_cast(cast)) {
6228 /* TODO: record the error in the AST. else it is impossible to detect it */
6235 * Parse a statement expression.
6237 static expression_t *parse_statement_expression(void)
6239 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6242 add_anchor_token(')');
6244 statement_t *statement = parse_compound_statement(true);
6245 statement->compound.stmt_expr = true;
6246 expression->statement.statement = statement;
6248 /* find last statement and use its type */
6249 type_t *type = type_void;
6250 const statement_t *stmt = statement->compound.statements;
6252 while (stmt->base.next != NULL)
6253 stmt = stmt->base.next;
6255 if (stmt->kind == STATEMENT_EXPRESSION) {
6256 type = stmt->expression.expression->base.type;
6259 source_position_t const *const pos = &expression->base.source_position;
6260 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6262 expression->base.type = type;
6264 rem_anchor_token(')');
6270 * Parse a parenthesized expression.
6272 static expression_t *parse_parenthesized_expression(void)
6274 token_t const* const la1 = look_ahead(1);
6275 switch (la1->kind) {
6277 /* gcc extension: a statement expression */
6278 return parse_statement_expression();
6281 if (is_typedef_symbol(la1->base.symbol)) {
6283 return parse_cast();
6288 add_anchor_token(')');
6289 expression_t *result = parse_expression();
6290 result->base.parenthesized = true;
6291 rem_anchor_token(')');
6297 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6299 if (current_function == NULL) {
6300 errorf(HERE, "'%K' used outside of a function", &token);
6303 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6304 expression->base.type = type_char_ptr;
6305 expression->funcname.kind = kind;
6312 static designator_t *parse_designator(void)
6314 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6315 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6316 if (!result->symbol)
6319 designator_t *last_designator = result;
6322 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6323 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6324 if (!designator->symbol)
6327 last_designator->next = designator;
6328 last_designator = designator;
6332 add_anchor_token(']');
6333 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6334 designator->source_position = *HERE;
6335 designator->array_index = parse_expression();
6336 rem_anchor_token(']');
6338 if (designator->array_index == NULL) {
6342 last_designator->next = designator;
6343 last_designator = designator;
6353 * Parse the __builtin_offsetof() expression.
6355 static expression_t *parse_offsetof(void)
6357 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6358 expression->base.type = type_size_t;
6360 eat(T___builtin_offsetof);
6362 add_anchor_token(')');
6363 add_anchor_token(',');
6365 type_t *type = parse_typename();
6366 rem_anchor_token(',');
6368 designator_t *designator = parse_designator();
6369 rem_anchor_token(')');
6372 expression->offsetofe.type = type;
6373 expression->offsetofe.designator = designator;
6376 memset(&path, 0, sizeof(path));
6377 path.top_type = type;
6378 path.path = NEW_ARR_F(type_path_entry_t, 0);
6380 descend_into_subtype(&path);
6382 if (!walk_designator(&path, designator, true)) {
6383 return create_error_expression();
6386 DEL_ARR_F(path.path);
6391 static bool is_last_parameter(expression_t *const param)
6393 if (param->kind == EXPR_REFERENCE) {
6394 entity_t *const entity = param->reference.entity;
6395 if (entity->kind == ENTITY_PARAMETER &&
6396 !entity->base.next &&
6397 entity->base.parent_scope == ¤t_function->parameters) {
6402 if (!is_type_valid(skip_typeref(param->base.type)))
6409 * Parses a __builtin_va_start() expression.
6411 static expression_t *parse_va_start(void)
6413 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6415 eat(T___builtin_va_start);
6417 add_anchor_token(')');
6418 add_anchor_token(',');
6420 expression->va_starte.ap = parse_assignment_expression();
6421 rem_anchor_token(',');
6423 expression_t *const param = parse_assignment_expression();
6424 expression->va_starte.parameter = param;
6425 rem_anchor_token(')');
6428 if (!current_function) {
6429 errorf(&expression->base.source_position, "'va_start' used outside of function");
6430 } else if (!current_function->base.type->function.variadic) {
6431 errorf(&expression->base.source_position, "'va_start' used in non-variadic function");
6432 } else if (!is_last_parameter(param)) {
6433 errorf(¶m->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
6440 * Parses a __builtin_va_arg() expression.
6442 static expression_t *parse_va_arg(void)
6444 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6446 eat(T___builtin_va_arg);
6448 add_anchor_token(')');
6449 add_anchor_token(',');
6452 ap.expression = parse_assignment_expression();
6453 expression->va_arge.ap = ap.expression;
6454 check_call_argument(type_valist, &ap, 1);
6456 rem_anchor_token(',');
6458 expression->base.type = parse_typename();
6459 rem_anchor_token(')');
6466 * Parses a __builtin_va_copy() expression.
6468 static expression_t *parse_va_copy(void)
6470 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6472 eat(T___builtin_va_copy);
6474 add_anchor_token(')');
6475 add_anchor_token(',');
6477 expression_t *dst = parse_assignment_expression();
6478 assign_error_t error = semantic_assign(type_valist, dst);
6479 report_assign_error(error, type_valist, dst, "call argument 1",
6480 &dst->base.source_position);
6481 expression->va_copye.dst = dst;
6483 rem_anchor_token(',');
6486 call_argument_t src;
6487 src.expression = parse_assignment_expression();
6488 check_call_argument(type_valist, &src, 2);
6489 expression->va_copye.src = src.expression;
6490 rem_anchor_token(')');
6497 * Parses a __builtin_constant_p() expression.
6499 static expression_t *parse_builtin_constant(void)
6501 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6503 eat(T___builtin_constant_p);
6505 add_anchor_token(')');
6507 expression->builtin_constant.value = parse_assignment_expression();
6508 rem_anchor_token(')');
6510 expression->base.type = type_int;
6516 * Parses a __builtin_types_compatible_p() expression.
6518 static expression_t *parse_builtin_types_compatible(void)
6520 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6522 eat(T___builtin_types_compatible_p);
6524 add_anchor_token(')');
6525 add_anchor_token(',');
6527 expression->builtin_types_compatible.left = parse_typename();
6528 rem_anchor_token(',');
6530 expression->builtin_types_compatible.right = parse_typename();
6531 rem_anchor_token(')');
6533 expression->base.type = type_int;
6539 * Parses a __builtin_is_*() compare expression.
6541 static expression_t *parse_compare_builtin(void)
6543 expression_kind_t kind;
6544 switch (token.kind) {
6545 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6546 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6547 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6548 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6549 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6550 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6551 default: internal_errorf(HERE, "invalid compare builtin found");
6553 expression_t *const expression = allocate_expression_zero(kind);
6556 add_anchor_token(')');
6557 add_anchor_token(',');
6559 expression->binary.left = parse_assignment_expression();
6560 rem_anchor_token(',');
6562 expression->binary.right = parse_assignment_expression();
6563 rem_anchor_token(')');
6566 type_t *const orig_type_left = expression->binary.left->base.type;
6567 type_t *const orig_type_right = expression->binary.right->base.type;
6569 type_t *const type_left = skip_typeref(orig_type_left);
6570 type_t *const type_right = skip_typeref(orig_type_right);
6571 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6572 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6573 type_error_incompatible("invalid operands in comparison",
6574 &expression->base.source_position, orig_type_left, orig_type_right);
6577 semantic_comparison(&expression->binary);
6584 * Parses a MS assume() expression.
6586 static expression_t *parse_assume(void)
6588 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6592 add_anchor_token(')');
6594 expression->unary.value = parse_assignment_expression();
6595 rem_anchor_token(')');
6598 expression->base.type = type_void;
6603 * Return the label for the current symbol or create a new one.
6605 static label_t *get_label(char const *const context)
6607 assert(current_function != NULL);
6609 symbol_t *const sym = expect_identifier(context, NULL);
6613 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6614 /* If we find a local label, we already created the declaration. */
6615 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6616 if (label->base.parent_scope != current_scope) {
6617 assert(label->base.parent_scope->depth < current_scope->depth);
6618 current_function->goto_to_outer = true;
6620 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6621 /* There is no matching label in the same function, so create a new one. */
6622 source_position_t const nowhere = { NULL, 0, 0, false };
6623 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6627 return &label->label;
6631 * Parses a GNU && label address expression.
6633 static expression_t *parse_label_address(void)
6635 source_position_t const source_position = *HERE;
6638 label_t *const label = get_label("while parsing label address");
6640 return create_error_expression();
6643 label->address_taken = true;
6645 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6646 expression->base.source_position = source_position;
6648 /* label address is treated as a void pointer */
6649 expression->base.type = type_void_ptr;
6650 expression->label_address.label = label;
6655 * Parse a microsoft __noop expression.
6657 static expression_t *parse_noop_expression(void)
6659 /* the result is a (int)0 */
6660 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6661 literal->base.type = type_int;
6662 literal->literal.value.begin = "__noop";
6663 literal->literal.value.size = 6;
6667 if (token.kind == '(') {
6668 /* parse arguments */
6670 add_anchor_token(')');
6671 add_anchor_token(',');
6673 if (token.kind != ')') do {
6674 (void)parse_assignment_expression();
6675 } while (next_if(','));
6677 rem_anchor_token(',');
6678 rem_anchor_token(')');
6686 * Parses a primary expression.
6688 static expression_t *parse_primary_expression(void)
6690 switch (token.kind) {
6691 case T_false: return parse_boolean_literal(false);
6692 case T_true: return parse_boolean_literal(true);
6694 case T_FLOATINGPOINT: return parse_number_literal();
6695 case T_CHARACTER_CONSTANT: return parse_character_constant();
6696 case T_STRING_LITERAL: return parse_string_literal();
6697 case T___FUNCTION__:
6698 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6699 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6700 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6701 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6702 case T___builtin_offsetof: return parse_offsetof();
6703 case T___builtin_va_start: return parse_va_start();
6704 case T___builtin_va_arg: return parse_va_arg();
6705 case T___builtin_va_copy: return parse_va_copy();
6706 case T___builtin_isgreater:
6707 case T___builtin_isgreaterequal:
6708 case T___builtin_isless:
6709 case T___builtin_islessequal:
6710 case T___builtin_islessgreater:
6711 case T___builtin_isunordered: return parse_compare_builtin();
6712 case T___builtin_constant_p: return parse_builtin_constant();
6713 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6714 case T__assume: return parse_assume();
6717 return parse_label_address();
6720 case '(': return parse_parenthesized_expression();
6721 case T___noop: return parse_noop_expression();
6723 /* Gracefully handle type names while parsing expressions. */
6725 return parse_reference();
6727 if (!is_typedef_symbol(token.base.symbol)) {
6728 return parse_reference();
6732 source_position_t const pos = *HERE;
6733 declaration_specifiers_t specifiers;
6734 parse_declaration_specifiers(&specifiers);
6735 type_t const *const type = parse_abstract_declarator(specifiers.type);
6736 errorf(&pos, "encountered type '%T' while parsing expression", type);
6737 return create_error_expression();
6741 errorf(HERE, "unexpected token %K, expected an expression", &token);
6743 return create_error_expression();
6746 static expression_t *parse_array_expression(expression_t *left)
6748 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6749 array_access_expression_t *const arr = &expr->array_access;
6752 add_anchor_token(']');
6754 expression_t *const inside = parse_expression();
6756 type_t *const orig_type_left = left->base.type;
6757 type_t *const orig_type_inside = inside->base.type;
6759 type_t *const type_left = skip_typeref(orig_type_left);
6760 type_t *const type_inside = skip_typeref(orig_type_inside);
6766 if (is_type_pointer(type_left)) {
6769 idx_type = type_inside;
6770 res_type = type_left->pointer.points_to;
6772 } else if (is_type_pointer(type_inside)) {
6773 arr->flipped = true;
6776 idx_type = type_left;
6777 res_type = type_inside->pointer.points_to;
6779 res_type = automatic_type_conversion(res_type);
6780 if (!is_type_integer(idx_type)) {
6781 errorf(&idx->base.source_position, "array subscript must have integer type");
6782 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6783 source_position_t const *const pos = &idx->base.source_position;
6784 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6787 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6788 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6790 res_type = type_error_type;
6795 arr->array_ref = ref;
6797 arr->base.type = res_type;
6799 rem_anchor_token(']');
6804 static bool is_bitfield(const expression_t *expression)
6806 return expression->kind == EXPR_SELECT
6807 && expression->select.compound_entry->compound_member.bitfield;
6810 static expression_t *parse_typeprop(expression_kind_t const kind)
6812 expression_t *tp_expression = allocate_expression_zero(kind);
6813 tp_expression->base.type = type_size_t;
6815 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6818 expression_t *expression;
6819 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6820 source_position_t const pos = *HERE;
6822 add_anchor_token(')');
6823 orig_type = parse_typename();
6824 rem_anchor_token(')');
6827 if (token.kind == '{') {
6828 /* It was not sizeof(type) after all. It is sizeof of an expression
6829 * starting with a compound literal */
6830 expression = parse_compound_literal(&pos, orig_type);
6831 goto typeprop_expression;
6834 expression = parse_subexpression(PREC_UNARY);
6836 typeprop_expression:
6837 if (is_bitfield(expression)) {
6838 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6839 errorf(&tp_expression->base.source_position,
6840 "operand of %s expression must not be a bitfield", what);
6843 tp_expression->typeprop.tp_expression = expression;
6845 orig_type = revert_automatic_type_conversion(expression);
6846 expression->base.type = orig_type;
6849 tp_expression->typeprop.type = orig_type;
6850 type_t const* const type = skip_typeref(orig_type);
6851 char const* wrong_type = NULL;
6852 if (is_type_incomplete(type)) {
6853 if (!is_type_void(type) || !GNU_MODE)
6854 wrong_type = "incomplete";
6855 } else if (type->kind == TYPE_FUNCTION) {
6857 /* function types are allowed (and return 1) */
6858 source_position_t const *const pos = &tp_expression->base.source_position;
6859 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6860 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6862 wrong_type = "function";
6866 if (wrong_type != NULL) {
6867 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6868 errorf(&tp_expression->base.source_position,
6869 "operand of %s expression must not be of %s type '%T'",
6870 what, wrong_type, orig_type);
6873 return tp_expression;
6876 static expression_t *parse_sizeof(void)
6878 return parse_typeprop(EXPR_SIZEOF);
6881 static expression_t *parse_alignof(void)
6883 return parse_typeprop(EXPR_ALIGNOF);
6886 static expression_t *parse_select_expression(expression_t *addr)
6888 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6889 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6890 source_position_t const pos = *HERE;
6893 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6895 return create_error_expression();
6897 type_t *const orig_type = addr->base.type;
6898 type_t *const type = skip_typeref(orig_type);
6901 bool saw_error = false;
6902 if (is_type_pointer(type)) {
6903 if (!select_left_arrow) {
6905 "request for member '%Y' in something not a struct or union, but '%T'",
6909 type_left = skip_typeref(type->pointer.points_to);
6911 if (select_left_arrow && is_type_valid(type)) {
6912 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6918 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6919 type_left->kind != TYPE_COMPOUND_UNION) {
6921 if (is_type_valid(type_left) && !saw_error) {
6923 "request for member '%Y' in something not a struct or union, but '%T'",
6926 return create_error_expression();
6929 compound_t *compound = type_left->compound.compound;
6930 if (!compound->complete) {
6931 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6933 return create_error_expression();
6936 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6937 expression_t *result =
6938 find_create_select(&pos, addr, qualifiers, compound, symbol);
6940 if (result == NULL) {
6941 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6942 return create_error_expression();
6948 static void check_call_argument(type_t *expected_type,
6949 call_argument_t *argument, unsigned pos)
6951 type_t *expected_type_skip = skip_typeref(expected_type);
6952 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6953 expression_t *arg_expr = argument->expression;
6954 type_t *arg_type = skip_typeref(arg_expr->base.type);
6956 /* handle transparent union gnu extension */
6957 if (is_type_union(expected_type_skip)
6958 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6959 compound_t *union_decl = expected_type_skip->compound.compound;
6960 type_t *best_type = NULL;
6961 entity_t *entry = union_decl->members.entities;
6962 for ( ; entry != NULL; entry = entry->base.next) {
6963 assert(is_declaration(entry));
6964 type_t *decl_type = entry->declaration.type;
6965 error = semantic_assign(decl_type, arg_expr);
6966 if (error == ASSIGN_ERROR_INCOMPATIBLE
6967 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6970 if (error == ASSIGN_SUCCESS) {
6971 best_type = decl_type;
6972 } else if (best_type == NULL) {
6973 best_type = decl_type;
6977 if (best_type != NULL) {
6978 expected_type = best_type;
6982 error = semantic_assign(expected_type, arg_expr);
6983 argument->expression = create_implicit_cast(arg_expr, expected_type);
6985 if (error != ASSIGN_SUCCESS) {
6986 /* report exact scope in error messages (like "in argument 3") */
6988 snprintf(buf, sizeof(buf), "call argument %u", pos);
6989 report_assign_error(error, expected_type, arg_expr, buf,
6990 &arg_expr->base.source_position);
6992 type_t *const promoted_type = get_default_promoted_type(arg_type);
6993 if (!types_compatible(expected_type_skip, promoted_type) &&
6994 !types_compatible(expected_type_skip, type_void_ptr) &&
6995 !types_compatible(type_void_ptr, promoted_type)) {
6996 /* Deliberately show the skipped types in this warning */
6997 source_position_t const *const apos = &arg_expr->base.source_position;
6998 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7004 * Handle the semantic restrictions of builtin calls
7006 static void handle_builtin_argument_restrictions(call_expression_t *call)
7008 entity_t *entity = call->function->reference.entity;
7009 switch (entity->function.btk) {
7011 switch (entity->function.b.firm_builtin_kind) {
7012 case ir_bk_return_address:
7013 case ir_bk_frame_address: {
7014 /* argument must be constant */
7015 call_argument_t *argument = call->arguments;
7017 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7018 errorf(&call->base.source_position,
7019 "argument of '%Y' must be a constant expression",
7020 call->function->reference.entity->base.symbol);
7024 case ir_bk_prefetch:
7025 /* second and third argument must be constant if existent */
7026 if (call->arguments == NULL)
7028 call_argument_t *rw = call->arguments->next;
7029 call_argument_t *locality = NULL;
7032 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7033 errorf(&call->base.source_position,
7034 "second argument of '%Y' must be a constant expression",
7035 call->function->reference.entity->base.symbol);
7037 locality = rw->next;
7039 if (locality != NULL) {
7040 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7041 errorf(&call->base.source_position,
7042 "third argument of '%Y' must be a constant expression",
7043 call->function->reference.entity->base.symbol);
7045 locality = rw->next;
7052 case BUILTIN_OBJECT_SIZE:
7053 if (call->arguments == NULL)
7056 call_argument_t *arg = call->arguments->next;
7057 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7058 errorf(&call->base.source_position,
7059 "second argument of '%Y' must be a constant expression",
7060 call->function->reference.entity->base.symbol);
7069 * Parse a call expression, ie. expression '( ... )'.
7071 * @param expression the function address
7073 static expression_t *parse_call_expression(expression_t *expression)
7075 expression_t *result = allocate_expression_zero(EXPR_CALL);
7076 call_expression_t *call = &result->call;
7077 call->function = expression;
7079 type_t *const orig_type = expression->base.type;
7080 type_t *const type = skip_typeref(orig_type);
7082 function_type_t *function_type = NULL;
7083 if (is_type_pointer(type)) {
7084 type_t *const to_type = skip_typeref(type->pointer.points_to);
7086 if (is_type_function(to_type)) {
7087 function_type = &to_type->function;
7088 call->base.type = function_type->return_type;
7092 if (function_type == NULL && is_type_valid(type)) {
7094 "called object '%E' (type '%T') is not a pointer to a function",
7095 expression, orig_type);
7098 /* parse arguments */
7100 add_anchor_token(')');
7101 add_anchor_token(',');
7103 if (token.kind != ')') {
7104 call_argument_t **anchor = &call->arguments;
7106 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7107 argument->expression = parse_assignment_expression();
7110 anchor = &argument->next;
7111 } while (next_if(','));
7113 rem_anchor_token(',');
7114 rem_anchor_token(')');
7117 if (function_type == NULL)
7120 /* check type and count of call arguments */
7121 function_parameter_t *parameter = function_type->parameters;
7122 call_argument_t *argument = call->arguments;
7123 if (!function_type->unspecified_parameters) {
7124 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7125 parameter = parameter->next, argument = argument->next) {
7126 check_call_argument(parameter->type, argument, ++pos);
7129 if (parameter != NULL) {
7130 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7131 } else if (argument != NULL && !function_type->variadic) {
7132 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7136 /* do default promotion for other arguments */
7137 for (; argument != NULL; argument = argument->next) {
7138 type_t *argument_type = argument->expression->base.type;
7139 if (!is_type_object(skip_typeref(argument_type))) {
7140 errorf(&argument->expression->base.source_position,
7141 "call argument '%E' must not be void", argument->expression);
7144 argument_type = get_default_promoted_type(argument_type);
7146 argument->expression
7147 = create_implicit_cast(argument->expression, argument_type);
7152 if (is_type_compound(skip_typeref(function_type->return_type))) {
7153 source_position_t const *const pos = &expression->base.source_position;
7154 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7157 if (expression->kind == EXPR_REFERENCE) {
7158 reference_expression_t *reference = &expression->reference;
7159 if (reference->entity->kind == ENTITY_FUNCTION &&
7160 reference->entity->function.btk != BUILTIN_NONE)
7161 handle_builtin_argument_restrictions(call);
7167 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7169 static bool same_compound_type(const type_t *type1, const type_t *type2)
7172 is_type_compound(type1) &&
7173 type1->kind == type2->kind &&
7174 type1->compound.compound == type2->compound.compound;
7177 static expression_t const *get_reference_address(expression_t const *expr)
7179 bool regular_take_address = true;
7181 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7182 expr = expr->unary.value;
7184 regular_take_address = false;
7187 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7190 expr = expr->unary.value;
7193 if (expr->kind != EXPR_REFERENCE)
7196 /* special case for functions which are automatically converted to a
7197 * pointer to function without an extra TAKE_ADDRESS operation */
7198 if (!regular_take_address &&
7199 expr->reference.entity->kind != ENTITY_FUNCTION) {
7206 static void warn_reference_address_as_bool(expression_t const* expr)
7208 expr = get_reference_address(expr);
7210 source_position_t const *const pos = &expr->base.source_position;
7211 entity_t const *const ent = expr->reference.entity;
7212 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7216 static void warn_assignment_in_condition(const expression_t *const expr)
7218 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7220 if (expr->base.parenthesized)
7222 source_position_t const *const pos = &expr->base.source_position;
7223 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7226 static void semantic_condition(expression_t const *const expr,
7227 char const *const context)
7229 type_t *const type = skip_typeref(expr->base.type);
7230 if (is_type_scalar(type)) {
7231 warn_reference_address_as_bool(expr);
7232 warn_assignment_in_condition(expr);
7233 } else if (is_type_valid(type)) {
7234 errorf(&expr->base.source_position,
7235 "%s must have scalar type", context);
7240 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7242 * @param expression the conditional expression
7244 static expression_t *parse_conditional_expression(expression_t *expression)
7246 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7248 conditional_expression_t *conditional = &result->conditional;
7249 conditional->condition = expression;
7252 add_anchor_token(':');
7254 /* §6.5.15:2 The first operand shall have scalar type. */
7255 semantic_condition(expression, "condition of conditional operator");
7257 expression_t *true_expression = expression;
7258 bool gnu_cond = false;
7259 if (GNU_MODE && token.kind == ':') {
7262 true_expression = parse_expression();
7264 rem_anchor_token(':');
7266 expression_t *false_expression =
7267 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7269 type_t *const orig_true_type = true_expression->base.type;
7270 type_t *const orig_false_type = false_expression->base.type;
7271 type_t *const true_type = skip_typeref(orig_true_type);
7272 type_t *const false_type = skip_typeref(orig_false_type);
7275 source_position_t const *const pos = &conditional->base.source_position;
7276 type_t *result_type;
7277 if (is_type_void(true_type) || is_type_void(false_type)) {
7278 /* ISO/IEC 14882:1998(E) §5.16:2 */
7279 if (true_expression->kind == EXPR_UNARY_THROW) {
7280 result_type = false_type;
7281 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7282 result_type = true_type;
7284 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7285 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7287 result_type = type_void;
7289 } else if (is_type_arithmetic(true_type)
7290 && is_type_arithmetic(false_type)) {
7291 result_type = semantic_arithmetic(true_type, false_type);
7292 } else if (same_compound_type(true_type, false_type)) {
7293 /* just take 1 of the 2 types */
7294 result_type = true_type;
7295 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7296 type_t *pointer_type;
7298 expression_t *other_expression;
7299 if (is_type_pointer(true_type) &&
7300 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7301 pointer_type = true_type;
7302 other_type = false_type;
7303 other_expression = false_expression;
7305 pointer_type = false_type;
7306 other_type = true_type;
7307 other_expression = true_expression;
7310 if (is_null_pointer_constant(other_expression)) {
7311 result_type = pointer_type;
7312 } else if (is_type_pointer(other_type)) {
7313 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7314 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7317 if (is_type_void(to1) || is_type_void(to2)) {
7319 } else if (types_compatible(get_unqualified_type(to1),
7320 get_unqualified_type(to2))) {
7323 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7327 type_t *const type =
7328 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7329 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7330 } else if (is_type_integer(other_type)) {
7331 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7332 result_type = pointer_type;
7334 goto types_incompatible;
7338 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7339 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7341 result_type = type_error_type;
7344 conditional->true_expression
7345 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7346 conditional->false_expression
7347 = create_implicit_cast(false_expression, result_type);
7348 conditional->base.type = result_type;
7353 * Parse an extension expression.
7355 static expression_t *parse_extension(void)
7358 expression_t *expression = parse_subexpression(PREC_UNARY);
7364 * Parse a __builtin_classify_type() expression.
7366 static expression_t *parse_builtin_classify_type(void)
7368 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7369 result->base.type = type_int;
7371 eat(T___builtin_classify_type);
7373 add_anchor_token(')');
7375 expression_t *expression = parse_expression();
7376 rem_anchor_token(')');
7378 result->classify_type.type_expression = expression;
7384 * Parse a delete expression
7385 * ISO/IEC 14882:1998(E) §5.3.5
7387 static expression_t *parse_delete(void)
7389 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7390 result->base.type = type_void;
7395 result->kind = EXPR_UNARY_DELETE_ARRAY;
7399 expression_t *const value = parse_subexpression(PREC_CAST);
7400 result->unary.value = value;
7402 type_t *const type = skip_typeref(value->base.type);
7403 if (!is_type_pointer(type)) {
7404 if (is_type_valid(type)) {
7405 errorf(&value->base.source_position,
7406 "operand of delete must have pointer type");
7408 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7409 source_position_t const *const pos = &value->base.source_position;
7410 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7417 * Parse a throw expression
7418 * ISO/IEC 14882:1998(E) §15:1
7420 static expression_t *parse_throw(void)
7422 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7423 result->base.type = type_void;
7427 expression_t *value = NULL;
7428 switch (token.kind) {
7430 value = parse_assignment_expression();
7431 /* ISO/IEC 14882:1998(E) §15.1:3 */
7432 type_t *const orig_type = value->base.type;
7433 type_t *const type = skip_typeref(orig_type);
7434 if (is_type_incomplete(type)) {
7435 errorf(&value->base.source_position,
7436 "cannot throw object of incomplete type '%T'", orig_type);
7437 } else if (is_type_pointer(type)) {
7438 type_t *const points_to = skip_typeref(type->pointer.points_to);
7439 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7440 errorf(&value->base.source_position,
7441 "cannot throw pointer to incomplete type '%T'", orig_type);
7449 result->unary.value = value;
7454 static bool check_pointer_arithmetic(const source_position_t *source_position,
7455 type_t *pointer_type,
7456 type_t *orig_pointer_type)
7458 type_t *points_to = pointer_type->pointer.points_to;
7459 points_to = skip_typeref(points_to);
7461 if (is_type_incomplete(points_to)) {
7462 if (!GNU_MODE || !is_type_void(points_to)) {
7463 errorf(source_position,
7464 "arithmetic with pointer to incomplete type '%T' not allowed",
7468 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7470 } else if (is_type_function(points_to)) {
7472 errorf(source_position,
7473 "arithmetic with pointer to function type '%T' not allowed",
7477 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7483 static bool is_lvalue(const expression_t *expression)
7485 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7486 switch (expression->kind) {
7487 case EXPR_ARRAY_ACCESS:
7488 case EXPR_COMPOUND_LITERAL:
7489 case EXPR_REFERENCE:
7491 case EXPR_UNARY_DEREFERENCE:
7495 type_t *type = skip_typeref(expression->base.type);
7497 /* ISO/IEC 14882:1998(E) §3.10:3 */
7498 is_type_reference(type) ||
7499 /* Claim it is an lvalue, if the type is invalid. There was a parse
7500 * error before, which maybe prevented properly recognizing it as
7502 !is_type_valid(type);
7507 static void semantic_incdec(unary_expression_t *expression)
7509 type_t *const orig_type = expression->value->base.type;
7510 type_t *const type = skip_typeref(orig_type);
7511 if (is_type_pointer(type)) {
7512 if (!check_pointer_arithmetic(&expression->base.source_position,
7516 } else if (!is_type_real(type) && is_type_valid(type)) {
7517 /* TODO: improve error message */
7518 errorf(&expression->base.source_position,
7519 "operation needs an arithmetic or pointer type");
7522 if (!is_lvalue(expression->value)) {
7523 /* TODO: improve error message */
7524 errorf(&expression->base.source_position, "lvalue required as operand");
7526 expression->base.type = orig_type;
7529 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7531 type_t *const res_type = promote_integer(type);
7532 expr->base.type = res_type;
7533 expr->value = create_implicit_cast(expr->value, res_type);
7536 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7538 type_t *const orig_type = expression->value->base.type;
7539 type_t *const type = skip_typeref(orig_type);
7540 if (!is_type_arithmetic(type)) {
7541 if (is_type_valid(type)) {
7542 /* TODO: improve error message */
7543 errorf(&expression->base.source_position,
7544 "operation needs an arithmetic type");
7547 } else if (is_type_integer(type)) {
7548 promote_unary_int_expr(expression, type);
7550 expression->base.type = orig_type;
7554 static void semantic_unexpr_plus(unary_expression_t *expression)
7556 semantic_unexpr_arithmetic(expression);
7557 source_position_t const *const pos = &expression->base.source_position;
7558 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7561 static void semantic_not(unary_expression_t *expression)
7563 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7564 semantic_condition(expression->value, "operand of !");
7565 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7568 static void semantic_unexpr_integer(unary_expression_t *expression)
7570 type_t *const orig_type = expression->value->base.type;
7571 type_t *const type = skip_typeref(orig_type);
7572 if (!is_type_integer(type)) {
7573 if (is_type_valid(type)) {
7574 errorf(&expression->base.source_position,
7575 "operand of ~ must be of integer type");
7580 promote_unary_int_expr(expression, type);
7583 static void semantic_dereference(unary_expression_t *expression)
7585 type_t *const orig_type = expression->value->base.type;
7586 type_t *const type = skip_typeref(orig_type);
7587 if (!is_type_pointer(type)) {
7588 if (is_type_valid(type)) {
7589 errorf(&expression->base.source_position,
7590 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7595 type_t *result_type = type->pointer.points_to;
7596 result_type = automatic_type_conversion(result_type);
7597 expression->base.type = result_type;
7601 * Record that an address is taken (expression represents an lvalue).
7603 * @param expression the expression
7604 * @param may_be_register if true, the expression might be an register
7606 static void set_address_taken(expression_t *expression, bool may_be_register)
7608 if (expression->kind != EXPR_REFERENCE)
7611 entity_t *const entity = expression->reference.entity;
7613 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7616 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7617 && !may_be_register) {
7618 source_position_t const *const pos = &expression->base.source_position;
7619 errorf(pos, "address of register '%N' requested", entity);
7622 entity->variable.address_taken = true;
7626 * Check the semantic of the address taken expression.
7628 static void semantic_take_addr(unary_expression_t *expression)
7630 expression_t *value = expression->value;
7631 value->base.type = revert_automatic_type_conversion(value);
7633 type_t *orig_type = value->base.type;
7634 type_t *type = skip_typeref(orig_type);
7635 if (!is_type_valid(type))
7639 if (!is_lvalue(value)) {
7640 errorf(&expression->base.source_position, "'&' requires an lvalue");
7642 if (is_bitfield(value)) {
7643 errorf(&expression->base.source_position,
7644 "'&' not allowed on bitfield");
7647 set_address_taken(value, false);
7649 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7652 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7653 static expression_t *parse_##unexpression_type(void) \
7655 expression_t *unary_expression \
7656 = allocate_expression_zero(unexpression_type); \
7658 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7660 sfunc(&unary_expression->unary); \
7662 return unary_expression; \
7665 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7666 semantic_unexpr_arithmetic)
7667 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7668 semantic_unexpr_plus)
7669 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7671 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7672 semantic_dereference)
7673 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7675 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7676 semantic_unexpr_integer)
7677 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7679 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7682 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7684 static expression_t *parse_##unexpression_type(expression_t *left) \
7686 expression_t *unary_expression \
7687 = allocate_expression_zero(unexpression_type); \
7689 unary_expression->unary.value = left; \
7691 sfunc(&unary_expression->unary); \
7693 return unary_expression; \
7696 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7697 EXPR_UNARY_POSTFIX_INCREMENT,
7699 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7700 EXPR_UNARY_POSTFIX_DECREMENT,
7703 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7705 /* TODO: handle complex + imaginary types */
7707 type_left = get_unqualified_type(type_left);
7708 type_right = get_unqualified_type(type_right);
7710 /* §6.3.1.8 Usual arithmetic conversions */
7711 if (type_left == type_long_double || type_right == type_long_double) {
7712 return type_long_double;
7713 } else if (type_left == type_double || type_right == type_double) {
7715 } else if (type_left == type_float || type_right == type_float) {
7719 type_left = promote_integer(type_left);
7720 type_right = promote_integer(type_right);
7722 if (type_left == type_right)
7725 bool const signed_left = is_type_signed(type_left);
7726 bool const signed_right = is_type_signed(type_right);
7727 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7728 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7730 if (signed_left == signed_right)
7731 return rank_left >= rank_right ? type_left : type_right;
7735 atomic_type_kind_t s_akind;
7736 atomic_type_kind_t u_akind;
7741 u_type = type_right;
7743 s_type = type_right;
7746 s_akind = get_akind(s_type);
7747 u_akind = get_akind(u_type);
7748 s_rank = get_akind_rank(s_akind);
7749 u_rank = get_akind_rank(u_akind);
7751 if (u_rank >= s_rank)
7754 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7758 case ATOMIC_TYPE_INT: return type_unsigned_int;
7759 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7760 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7762 default: panic("invalid atomic type");
7767 * Check the semantic restrictions for a binary expression.
7769 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7771 expression_t *const left = expression->left;
7772 expression_t *const right = expression->right;
7773 type_t *const orig_type_left = left->base.type;
7774 type_t *const orig_type_right = right->base.type;
7775 type_t *const type_left = skip_typeref(orig_type_left);
7776 type_t *const type_right = skip_typeref(orig_type_right);
7778 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7779 /* TODO: improve error message */
7780 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7781 errorf(&expression->base.source_position,
7782 "operation needs arithmetic types");
7787 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7788 expression->left = create_implicit_cast(left, arithmetic_type);
7789 expression->right = create_implicit_cast(right, arithmetic_type);
7790 expression->base.type = arithmetic_type;
7793 static void semantic_binexpr_integer(binary_expression_t *const expression)
7795 expression_t *const left = expression->left;
7796 expression_t *const right = expression->right;
7797 type_t *const orig_type_left = left->base.type;
7798 type_t *const orig_type_right = right->base.type;
7799 type_t *const type_left = skip_typeref(orig_type_left);
7800 type_t *const type_right = skip_typeref(orig_type_right);
7802 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7803 /* TODO: improve error message */
7804 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7805 errorf(&expression->base.source_position,
7806 "operation needs integer types");
7811 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7812 expression->left = create_implicit_cast(left, result_type);
7813 expression->right = create_implicit_cast(right, result_type);
7814 expression->base.type = result_type;
7817 static void warn_div_by_zero(binary_expression_t const *const expression)
7819 if (!is_type_integer(expression->base.type))
7822 expression_t const *const right = expression->right;
7823 /* The type of the right operand can be different for /= */
7824 if (is_type_integer(right->base.type) &&
7825 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7826 !fold_constant_to_bool(right)) {
7827 source_position_t const *const pos = &expression->base.source_position;
7828 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7833 * Check the semantic restrictions for a div/mod expression.
7835 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7837 semantic_binexpr_arithmetic(expression);
7838 warn_div_by_zero(expression);
7841 static void warn_addsub_in_shift(const expression_t *const expr)
7843 if (expr->base.parenthesized)
7847 switch (expr->kind) {
7848 case EXPR_BINARY_ADD: op = '+'; break;
7849 case EXPR_BINARY_SUB: op = '-'; break;
7853 source_position_t const *const pos = &expr->base.source_position;
7854 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7857 static bool semantic_shift(binary_expression_t *expression)
7859 expression_t *const left = expression->left;
7860 expression_t *const right = expression->right;
7861 type_t *const orig_type_left = left->base.type;
7862 type_t *const orig_type_right = right->base.type;
7863 type_t * type_left = skip_typeref(orig_type_left);
7864 type_t * type_right = skip_typeref(orig_type_right);
7866 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7867 /* TODO: improve error message */
7868 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7869 errorf(&expression->base.source_position,
7870 "operands of shift operation must have integer types");
7875 type_left = promote_integer(type_left);
7877 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7878 source_position_t const *const pos = &right->base.source_position;
7879 long const count = fold_constant_to_int(right);
7881 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7882 } else if ((unsigned long)count >=
7883 get_atomic_type_size(type_left->atomic.akind) * 8) {
7884 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7888 type_right = promote_integer(type_right);
7889 expression->right = create_implicit_cast(right, type_right);
7894 static void semantic_shift_op(binary_expression_t *expression)
7896 expression_t *const left = expression->left;
7897 expression_t *const right = expression->right;
7899 if (!semantic_shift(expression))
7902 warn_addsub_in_shift(left);
7903 warn_addsub_in_shift(right);
7905 type_t *const orig_type_left = left->base.type;
7906 type_t * type_left = skip_typeref(orig_type_left);
7908 type_left = promote_integer(type_left);
7909 expression->left = create_implicit_cast(left, type_left);
7910 expression->base.type = type_left;
7913 static void semantic_add(binary_expression_t *expression)
7915 expression_t *const left = expression->left;
7916 expression_t *const right = expression->right;
7917 type_t *const orig_type_left = left->base.type;
7918 type_t *const orig_type_right = right->base.type;
7919 type_t *const type_left = skip_typeref(orig_type_left);
7920 type_t *const type_right = skip_typeref(orig_type_right);
7923 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7924 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7925 expression->left = create_implicit_cast(left, arithmetic_type);
7926 expression->right = create_implicit_cast(right, arithmetic_type);
7927 expression->base.type = arithmetic_type;
7928 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7929 check_pointer_arithmetic(&expression->base.source_position,
7930 type_left, orig_type_left);
7931 expression->base.type = type_left;
7932 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7933 check_pointer_arithmetic(&expression->base.source_position,
7934 type_right, orig_type_right);
7935 expression->base.type = type_right;
7936 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7937 errorf(&expression->base.source_position,
7938 "invalid operands to binary + ('%T', '%T')",
7939 orig_type_left, orig_type_right);
7943 static void semantic_sub(binary_expression_t *expression)
7945 expression_t *const left = expression->left;
7946 expression_t *const right = expression->right;
7947 type_t *const orig_type_left = left->base.type;
7948 type_t *const orig_type_right = right->base.type;
7949 type_t *const type_left = skip_typeref(orig_type_left);
7950 type_t *const type_right = skip_typeref(orig_type_right);
7951 source_position_t const *const pos = &expression->base.source_position;
7954 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7955 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7956 expression->left = create_implicit_cast(left, arithmetic_type);
7957 expression->right = create_implicit_cast(right, arithmetic_type);
7958 expression->base.type = arithmetic_type;
7959 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7960 check_pointer_arithmetic(&expression->base.source_position,
7961 type_left, orig_type_left);
7962 expression->base.type = type_left;
7963 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7964 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7965 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7966 if (!types_compatible(unqual_left, unqual_right)) {
7968 "subtracting pointers to incompatible types '%T' and '%T'",
7969 orig_type_left, orig_type_right);
7970 } else if (!is_type_object(unqual_left)) {
7971 if (!is_type_void(unqual_left)) {
7972 errorf(pos, "subtracting pointers to non-object types '%T'",
7975 warningf(WARN_OTHER, pos, "subtracting pointers to void");
7978 expression->base.type = type_ptrdiff_t;
7979 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7980 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7981 orig_type_left, orig_type_right);
7985 static void warn_string_literal_address(expression_t const* expr)
7987 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7988 expr = expr->unary.value;
7989 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7991 expr = expr->unary.value;
7994 if (expr->kind == EXPR_STRING_LITERAL
7995 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
7996 source_position_t const *const pos = &expr->base.source_position;
7997 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8001 static bool maybe_negative(expression_t const *const expr)
8003 switch (is_constant_expression(expr)) {
8004 case EXPR_CLASS_ERROR: return false;
8005 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8006 default: return true;
8010 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8012 warn_string_literal_address(expr);
8014 expression_t const* const ref = get_reference_address(expr);
8015 if (ref != NULL && is_null_pointer_constant(other)) {
8016 entity_t const *const ent = ref->reference.entity;
8017 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8020 if (!expr->base.parenthesized) {
8021 switch (expr->base.kind) {
8022 case EXPR_BINARY_LESS:
8023 case EXPR_BINARY_GREATER:
8024 case EXPR_BINARY_LESSEQUAL:
8025 case EXPR_BINARY_GREATEREQUAL:
8026 case EXPR_BINARY_NOTEQUAL:
8027 case EXPR_BINARY_EQUAL:
8028 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8037 * Check the semantics of comparison expressions.
8039 * @param expression The expression to check.
8041 static void semantic_comparison(binary_expression_t *expression)
8043 source_position_t const *const pos = &expression->base.source_position;
8044 expression_t *const left = expression->left;
8045 expression_t *const right = expression->right;
8047 warn_comparison(pos, left, right);
8048 warn_comparison(pos, right, left);
8050 type_t *orig_type_left = left->base.type;
8051 type_t *orig_type_right = right->base.type;
8052 type_t *type_left = skip_typeref(orig_type_left);
8053 type_t *type_right = skip_typeref(orig_type_right);
8055 /* TODO non-arithmetic types */
8056 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8057 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8059 /* test for signed vs unsigned compares */
8060 if (is_type_integer(arithmetic_type)) {
8061 bool const signed_left = is_type_signed(type_left);
8062 bool const signed_right = is_type_signed(type_right);
8063 if (signed_left != signed_right) {
8064 /* FIXME long long needs better const folding magic */
8065 /* TODO check whether constant value can be represented by other type */
8066 if ((signed_left && maybe_negative(left)) ||
8067 (signed_right && maybe_negative(right))) {
8068 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8073 expression->left = create_implicit_cast(left, arithmetic_type);
8074 expression->right = create_implicit_cast(right, arithmetic_type);
8075 expression->base.type = arithmetic_type;
8076 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8077 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8078 is_type_float(arithmetic_type)) {
8079 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8081 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8082 /* TODO check compatibility */
8083 } else if (is_type_pointer(type_left)) {
8084 expression->right = create_implicit_cast(right, type_left);
8085 } else if (is_type_pointer(type_right)) {
8086 expression->left = create_implicit_cast(left, type_right);
8087 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8088 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8090 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8094 * Checks if a compound type has constant fields.
8096 static bool has_const_fields(const compound_type_t *type)
8098 compound_t *compound = type->compound;
8099 entity_t *entry = compound->members.entities;
8101 for (; entry != NULL; entry = entry->base.next) {
8102 if (!is_declaration(entry))
8105 const type_t *decl_type = skip_typeref(entry->declaration.type);
8106 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8113 static bool is_valid_assignment_lhs(expression_t const* const left)
8115 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8116 type_t *const type_left = skip_typeref(orig_type_left);
8118 if (!is_lvalue(left)) {
8119 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8124 if (left->kind == EXPR_REFERENCE
8125 && left->reference.entity->kind == ENTITY_FUNCTION) {
8126 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8130 if (is_type_array(type_left)) {
8131 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8134 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8135 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8139 if (is_type_incomplete(type_left)) {
8140 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8141 left, orig_type_left);
8144 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8145 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8146 left, orig_type_left);
8153 static void semantic_arithmetic_assign(binary_expression_t *expression)
8155 expression_t *left = expression->left;
8156 expression_t *right = expression->right;
8157 type_t *orig_type_left = left->base.type;
8158 type_t *orig_type_right = right->base.type;
8160 if (!is_valid_assignment_lhs(left))
8163 type_t *type_left = skip_typeref(orig_type_left);
8164 type_t *type_right = skip_typeref(orig_type_right);
8166 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8167 /* TODO: improve error message */
8168 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8169 errorf(&expression->base.source_position,
8170 "operation needs arithmetic types");
8175 /* combined instructions are tricky. We can't create an implicit cast on
8176 * the left side, because we need the uncasted form for the store.
8177 * The ast2firm pass has to know that left_type must be right_type
8178 * for the arithmetic operation and create a cast by itself */
8179 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8180 expression->right = create_implicit_cast(right, arithmetic_type);
8181 expression->base.type = type_left;
8184 static void semantic_divmod_assign(binary_expression_t *expression)
8186 semantic_arithmetic_assign(expression);
8187 warn_div_by_zero(expression);
8190 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8192 expression_t *const left = expression->left;
8193 expression_t *const right = expression->right;
8194 type_t *const orig_type_left = left->base.type;
8195 type_t *const orig_type_right = right->base.type;
8196 type_t *const type_left = skip_typeref(orig_type_left);
8197 type_t *const type_right = skip_typeref(orig_type_right);
8199 if (!is_valid_assignment_lhs(left))
8202 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8203 /* combined instructions are tricky. We can't create an implicit cast on
8204 * the left side, because we need the uncasted form for the store.
8205 * The ast2firm pass has to know that left_type must be right_type
8206 * for the arithmetic operation and create a cast by itself */
8207 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8208 expression->right = create_implicit_cast(right, arithmetic_type);
8209 expression->base.type = type_left;
8210 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8211 check_pointer_arithmetic(&expression->base.source_position,
8212 type_left, orig_type_left);
8213 expression->base.type = type_left;
8214 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8215 errorf(&expression->base.source_position,
8216 "incompatible types '%T' and '%T' in assignment",
8217 orig_type_left, orig_type_right);
8221 static void semantic_integer_assign(binary_expression_t *expression)
8223 expression_t *left = expression->left;
8224 expression_t *right = expression->right;
8225 type_t *orig_type_left = left->base.type;
8226 type_t *orig_type_right = right->base.type;
8228 if (!is_valid_assignment_lhs(left))
8231 type_t *type_left = skip_typeref(orig_type_left);
8232 type_t *type_right = skip_typeref(orig_type_right);
8234 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8235 /* TODO: improve error message */
8236 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8237 errorf(&expression->base.source_position,
8238 "operation needs integer types");
8243 /* combined instructions are tricky. We can't create an implicit cast on
8244 * the left side, because we need the uncasted form for the store.
8245 * The ast2firm pass has to know that left_type must be right_type
8246 * for the arithmetic operation and create a cast by itself */
8247 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8248 expression->right = create_implicit_cast(right, arithmetic_type);
8249 expression->base.type = type_left;
8252 static void semantic_shift_assign(binary_expression_t *expression)
8254 expression_t *left = expression->left;
8256 if (!is_valid_assignment_lhs(left))
8259 if (!semantic_shift(expression))
8262 expression->base.type = skip_typeref(left->base.type);
8265 static void warn_logical_and_within_or(const expression_t *const expr)
8267 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8269 if (expr->base.parenthesized)
8271 source_position_t const *const pos = &expr->base.source_position;
8272 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8276 * Check the semantic restrictions of a logical expression.
8278 static void semantic_logical_op(binary_expression_t *expression)
8280 /* §6.5.13:2 Each of the operands shall have scalar type.
8281 * §6.5.14:2 Each of the operands shall have scalar type. */
8282 semantic_condition(expression->left, "left operand of logical operator");
8283 semantic_condition(expression->right, "right operand of logical operator");
8284 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8285 warn_logical_and_within_or(expression->left);
8286 warn_logical_and_within_or(expression->right);
8288 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8292 * Check the semantic restrictions of a binary assign expression.
8294 static void semantic_binexpr_assign(binary_expression_t *expression)
8296 expression_t *left = expression->left;
8297 type_t *orig_type_left = left->base.type;
8299 if (!is_valid_assignment_lhs(left))
8302 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8303 report_assign_error(error, orig_type_left, expression->right,
8304 "assignment", &left->base.source_position);
8305 expression->right = create_implicit_cast(expression->right, orig_type_left);
8306 expression->base.type = orig_type_left;
8310 * Determine if the outermost operation (or parts thereof) of the given
8311 * expression has no effect in order to generate a warning about this fact.
8312 * Therefore in some cases this only examines some of the operands of the
8313 * expression (see comments in the function and examples below).
8315 * f() + 23; // warning, because + has no effect
8316 * x || f(); // no warning, because x controls execution of f()
8317 * x ? y : f(); // warning, because y has no effect
8318 * (void)x; // no warning to be able to suppress the warning
8319 * This function can NOT be used for an "expression has definitely no effect"-
8321 static bool expression_has_effect(const expression_t *const expr)
8323 switch (expr->kind) {
8324 case EXPR_ERROR: return true; /* do NOT warn */
8325 case EXPR_REFERENCE: return false;
8326 case EXPR_ENUM_CONSTANT: return false;
8327 case EXPR_LABEL_ADDRESS: return false;
8329 /* suppress the warning for microsoft __noop operations */
8330 case EXPR_LITERAL_MS_NOOP: return true;
8331 case EXPR_LITERAL_BOOLEAN:
8332 case EXPR_LITERAL_CHARACTER:
8333 case EXPR_LITERAL_WIDE_CHARACTER:
8334 case EXPR_LITERAL_INTEGER:
8335 case EXPR_LITERAL_FLOATINGPOINT:
8336 case EXPR_STRING_LITERAL: return false;
8337 case EXPR_WIDE_STRING_LITERAL: return false;
8340 const call_expression_t *const call = &expr->call;
8341 if (call->function->kind != EXPR_REFERENCE)
8344 switch (call->function->reference.entity->function.btk) {
8345 /* FIXME: which builtins have no effect? */
8346 default: return true;
8350 /* Generate the warning if either the left or right hand side of a
8351 * conditional expression has no effect */
8352 case EXPR_CONDITIONAL: {
8353 conditional_expression_t const *const cond = &expr->conditional;
8354 expression_t const *const t = cond->true_expression;
8356 (t == NULL || expression_has_effect(t)) &&
8357 expression_has_effect(cond->false_expression);
8360 case EXPR_SELECT: return false;
8361 case EXPR_ARRAY_ACCESS: return false;
8362 case EXPR_SIZEOF: return false;
8363 case EXPR_CLASSIFY_TYPE: return false;
8364 case EXPR_ALIGNOF: return false;
8366 case EXPR_FUNCNAME: return false;
8367 case EXPR_BUILTIN_CONSTANT_P: return false;
8368 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8369 case EXPR_OFFSETOF: return false;
8370 case EXPR_VA_START: return true;
8371 case EXPR_VA_ARG: return true;
8372 case EXPR_VA_COPY: return true;
8373 case EXPR_STATEMENT: return true; // TODO
8374 case EXPR_COMPOUND_LITERAL: return false;
8376 case EXPR_UNARY_NEGATE: return false;
8377 case EXPR_UNARY_PLUS: return false;
8378 case EXPR_UNARY_BITWISE_NEGATE: return false;
8379 case EXPR_UNARY_NOT: return false;
8380 case EXPR_UNARY_DEREFERENCE: return false;
8381 case EXPR_UNARY_TAKE_ADDRESS: return false;
8382 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8383 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8384 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8385 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8387 /* Treat void casts as if they have an effect in order to being able to
8388 * suppress the warning */
8389 case EXPR_UNARY_CAST: {
8390 type_t *const type = skip_typeref(expr->base.type);
8391 return is_type_void(type);
8394 case EXPR_UNARY_ASSUME: return true;
8395 case EXPR_UNARY_DELETE: return true;
8396 case EXPR_UNARY_DELETE_ARRAY: return true;
8397 case EXPR_UNARY_THROW: return true;
8399 case EXPR_BINARY_ADD: return false;
8400 case EXPR_BINARY_SUB: return false;
8401 case EXPR_BINARY_MUL: return false;
8402 case EXPR_BINARY_DIV: return false;
8403 case EXPR_BINARY_MOD: return false;
8404 case EXPR_BINARY_EQUAL: return false;
8405 case EXPR_BINARY_NOTEQUAL: return false;
8406 case EXPR_BINARY_LESS: return false;
8407 case EXPR_BINARY_LESSEQUAL: return false;
8408 case EXPR_BINARY_GREATER: return false;
8409 case EXPR_BINARY_GREATEREQUAL: return false;
8410 case EXPR_BINARY_BITWISE_AND: return false;
8411 case EXPR_BINARY_BITWISE_OR: return false;
8412 case EXPR_BINARY_BITWISE_XOR: return false;
8413 case EXPR_BINARY_SHIFTLEFT: return false;
8414 case EXPR_BINARY_SHIFTRIGHT: return false;
8415 case EXPR_BINARY_ASSIGN: return true;
8416 case EXPR_BINARY_MUL_ASSIGN: return true;
8417 case EXPR_BINARY_DIV_ASSIGN: return true;
8418 case EXPR_BINARY_MOD_ASSIGN: return true;
8419 case EXPR_BINARY_ADD_ASSIGN: return true;
8420 case EXPR_BINARY_SUB_ASSIGN: return true;
8421 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8422 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8423 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8424 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8425 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8427 /* Only examine the right hand side of && and ||, because the left hand
8428 * side already has the effect of controlling the execution of the right
8430 case EXPR_BINARY_LOGICAL_AND:
8431 case EXPR_BINARY_LOGICAL_OR:
8432 /* Only examine the right hand side of a comma expression, because the left
8433 * hand side has a separate warning */
8434 case EXPR_BINARY_COMMA:
8435 return expression_has_effect(expr->binary.right);
8437 case EXPR_BINARY_ISGREATER: return false;
8438 case EXPR_BINARY_ISGREATEREQUAL: return false;
8439 case EXPR_BINARY_ISLESS: return false;
8440 case EXPR_BINARY_ISLESSEQUAL: return false;
8441 case EXPR_BINARY_ISLESSGREATER: return false;
8442 case EXPR_BINARY_ISUNORDERED: return false;
8445 internal_errorf(HERE, "unexpected expression");
8448 static void semantic_comma(binary_expression_t *expression)
8450 const expression_t *const left = expression->left;
8451 if (!expression_has_effect(left)) {
8452 source_position_t const *const pos = &left->base.source_position;
8453 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8455 expression->base.type = expression->right->base.type;
8459 * @param prec_r precedence of the right operand
8461 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8462 static expression_t *parse_##binexpression_type(expression_t *left) \
8464 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8465 binexpr->binary.left = left; \
8468 expression_t *right = parse_subexpression(prec_r); \
8470 binexpr->binary.right = right; \
8471 sfunc(&binexpr->binary); \
8476 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8477 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8478 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8479 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8480 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8481 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8482 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8483 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8484 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8485 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8486 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8487 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8488 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8489 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8490 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8491 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8492 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8493 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8494 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8495 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8496 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8497 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8498 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8499 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8500 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8501 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8502 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8503 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8504 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8505 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8508 static expression_t *parse_subexpression(precedence_t precedence)
8510 expression_parser_function_t *parser
8511 = &expression_parsers[token.kind];
8514 if (parser->parser != NULL) {
8515 left = parser->parser();
8517 left = parse_primary_expression();
8519 assert(left != NULL);
8522 parser = &expression_parsers[token.kind];
8523 if (parser->infix_parser == NULL)
8525 if (parser->infix_precedence < precedence)
8528 left = parser->infix_parser(left);
8530 assert(left != NULL);
8537 * Parse an expression.
8539 static expression_t *parse_expression(void)
8541 return parse_subexpression(PREC_EXPRESSION);
8545 * Register a parser for a prefix-like operator.
8547 * @param parser the parser function
8548 * @param token_kind the token type of the prefix token
8550 static void register_expression_parser(parse_expression_function parser,
8553 expression_parser_function_t *entry = &expression_parsers[token_kind];
8555 if (entry->parser != NULL) {
8556 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8557 panic("trying to register multiple expression parsers for a token");
8559 entry->parser = parser;
8563 * Register a parser for an infix operator with given precedence.
8565 * @param parser the parser function
8566 * @param token_kind the token type of the infix operator
8567 * @param precedence the precedence of the operator
8569 static void register_infix_parser(parse_expression_infix_function parser,
8570 int token_kind, precedence_t precedence)
8572 expression_parser_function_t *entry = &expression_parsers[token_kind];
8574 if (entry->infix_parser != NULL) {
8575 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8576 panic("trying to register multiple infix expression parsers for a "
8579 entry->infix_parser = parser;
8580 entry->infix_precedence = precedence;
8584 * Initialize the expression parsers.
8586 static void init_expression_parsers(void)
8588 memset(&expression_parsers, 0, sizeof(expression_parsers));
8590 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8591 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8592 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8593 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8594 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8595 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8596 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8597 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8598 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8599 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8600 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8601 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8602 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8603 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8604 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8605 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8606 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8607 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8608 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8609 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8610 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8611 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8612 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8613 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8614 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8615 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8616 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8617 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8618 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8619 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8620 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8621 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8622 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8623 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8624 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8625 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8626 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8628 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8629 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8630 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8631 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8632 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8633 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8634 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8635 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8636 register_expression_parser(parse_sizeof, T_sizeof);
8637 register_expression_parser(parse_alignof, T___alignof__);
8638 register_expression_parser(parse_extension, T___extension__);
8639 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8640 register_expression_parser(parse_delete, T_delete);
8641 register_expression_parser(parse_throw, T_throw);
8645 * Parse a asm statement arguments specification.
8647 static asm_argument_t *parse_asm_arguments(bool is_out)
8649 asm_argument_t *result = NULL;
8650 asm_argument_t **anchor = &result;
8652 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8653 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8656 add_anchor_token(']');
8657 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8658 rem_anchor_token(']');
8660 if (!argument->symbol)
8664 argument->constraints = parse_string_literals();
8665 add_anchor_token(')');
8667 expression_t *expression = parse_expression();
8668 rem_anchor_token(')');
8670 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8671 * change size or type representation (e.g. int -> long is ok, but
8672 * int -> float is not) */
8673 if (expression->kind == EXPR_UNARY_CAST) {
8674 type_t *const type = expression->base.type;
8675 type_kind_t const kind = type->kind;
8676 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8679 if (kind == TYPE_ATOMIC) {
8680 atomic_type_kind_t const akind = type->atomic.akind;
8681 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8682 size = get_atomic_type_size(akind);
8684 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8685 size = get_type_size(type_void_ptr);
8689 expression_t *const value = expression->unary.value;
8690 type_t *const value_type = value->base.type;
8691 type_kind_t const value_kind = value_type->kind;
8693 unsigned value_flags;
8694 unsigned value_size;
8695 if (value_kind == TYPE_ATOMIC) {
8696 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8697 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8698 value_size = get_atomic_type_size(value_akind);
8699 } else if (value_kind == TYPE_POINTER) {
8700 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8701 value_size = get_type_size(type_void_ptr);
8706 if (value_flags != flags || value_size != size)
8710 } while (expression->kind == EXPR_UNARY_CAST);
8714 if (!is_lvalue(expression)) {
8715 errorf(&expression->base.source_position,
8716 "asm output argument is not an lvalue");
8719 if (argument->constraints.begin[0] == '=')
8720 determine_lhs_ent(expression, NULL);
8722 mark_vars_read(expression, NULL);
8724 mark_vars_read(expression, NULL);
8726 argument->expression = expression;
8729 set_address_taken(expression, true);
8732 anchor = &argument->next;
8742 * Parse a asm statement clobber specification.
8744 static asm_clobber_t *parse_asm_clobbers(void)
8746 asm_clobber_t *result = NULL;
8747 asm_clobber_t **anchor = &result;
8749 while (token.kind == T_STRING_LITERAL) {
8750 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8751 clobber->clobber = parse_string_literals();
8754 anchor = &clobber->next;
8764 * Parse an asm statement.
8766 static statement_t *parse_asm_statement(void)
8768 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8769 asm_statement_t *asm_statement = &statement->asms;
8773 if (next_if(T_volatile))
8774 asm_statement->is_volatile = true;
8777 add_anchor_token(')');
8778 if (token.kind != T_STRING_LITERAL) {
8779 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8782 asm_statement->asm_text = parse_string_literals();
8784 add_anchor_token(':');
8785 if (!next_if(':')) {
8786 rem_anchor_token(':');
8790 asm_statement->outputs = parse_asm_arguments(true);
8791 if (!next_if(':')) {
8792 rem_anchor_token(':');
8796 asm_statement->inputs = parse_asm_arguments(false);
8797 if (!next_if(':')) {
8798 rem_anchor_token(':');
8801 rem_anchor_token(':');
8803 asm_statement->clobbers = parse_asm_clobbers();
8806 rem_anchor_token(')');
8810 if (asm_statement->outputs == NULL) {
8811 /* GCC: An 'asm' instruction without any output operands will be treated
8812 * identically to a volatile 'asm' instruction. */
8813 asm_statement->is_volatile = true;
8819 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8821 statement_t *inner_stmt;
8822 switch (token.kind) {
8824 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8825 inner_stmt = create_error_statement();
8829 if (label->kind == STATEMENT_LABEL) {
8830 /* Eat an empty statement here, to avoid the warning about an empty
8831 * statement after a label. label:; is commonly used to have a label
8832 * before a closing brace. */
8833 inner_stmt = create_empty_statement();
8840 inner_stmt = parse_statement();
8841 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8842 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8843 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8844 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8852 * Parse a case statement.
8854 static statement_t *parse_case_statement(void)
8856 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8857 source_position_t *const pos = &statement->base.source_position;
8860 add_anchor_token(':');
8862 expression_t *expression = parse_expression();
8863 type_t *expression_type = expression->base.type;
8864 type_t *skipped = skip_typeref(expression_type);
8865 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8866 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8867 expression, expression_type);
8870 type_t *type = expression_type;
8871 if (current_switch != NULL) {
8872 type_t *switch_type = current_switch->expression->base.type;
8873 if (is_type_valid(switch_type)) {
8874 expression = create_implicit_cast(expression, switch_type);
8878 statement->case_label.expression = expression;
8879 expression_classification_t const expr_class = is_constant_expression(expression);
8880 if (expr_class != EXPR_CLASS_CONSTANT) {
8881 if (expr_class != EXPR_CLASS_ERROR) {
8882 errorf(pos, "case label does not reduce to an integer constant");
8884 statement->case_label.is_bad = true;
8886 long const val = fold_constant_to_int(expression);
8887 statement->case_label.first_case = val;
8888 statement->case_label.last_case = val;
8892 if (next_if(T_DOTDOTDOT)) {
8893 expression_t *end_range = parse_expression();
8894 expression_type = expression->base.type;
8895 skipped = skip_typeref(expression_type);
8896 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8897 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8898 expression, expression_type);
8901 end_range = create_implicit_cast(end_range, type);
8902 statement->case_label.end_range = end_range;
8903 expression_classification_t const end_class = is_constant_expression(end_range);
8904 if (end_class != EXPR_CLASS_CONSTANT) {
8905 if (end_class != EXPR_CLASS_ERROR) {
8906 errorf(pos, "case range does not reduce to an integer constant");
8908 statement->case_label.is_bad = true;
8910 long const val = fold_constant_to_int(end_range);
8911 statement->case_label.last_case = val;
8913 if (val < statement->case_label.first_case) {
8914 statement->case_label.is_empty_range = true;
8915 warningf(WARN_OTHER, pos, "empty range specified");
8921 PUSH_PARENT(statement);
8923 rem_anchor_token(':');
8926 if (current_switch != NULL) {
8927 if (! statement->case_label.is_bad) {
8928 /* Check for duplicate case values */
8929 case_label_statement_t *c = &statement->case_label;
8930 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8931 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8934 if (c->last_case < l->first_case || c->first_case > l->last_case)
8937 errorf(pos, "duplicate case value (previously used %P)",
8938 &l->base.source_position);
8942 /* link all cases into the switch statement */
8943 if (current_switch->last_case == NULL) {
8944 current_switch->first_case = &statement->case_label;
8946 current_switch->last_case->next = &statement->case_label;
8948 current_switch->last_case = &statement->case_label;
8950 errorf(pos, "case label not within a switch statement");
8953 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
8960 * Parse a default statement.
8962 static statement_t *parse_default_statement(void)
8964 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8968 PUSH_PARENT(statement);
8972 if (current_switch != NULL) {
8973 const case_label_statement_t *def_label = current_switch->default_label;
8974 if (def_label != NULL) {
8975 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
8977 current_switch->default_label = &statement->case_label;
8979 /* link all cases into the switch statement */
8980 if (current_switch->last_case == NULL) {
8981 current_switch->first_case = &statement->case_label;
8983 current_switch->last_case->next = &statement->case_label;
8985 current_switch->last_case = &statement->case_label;
8988 errorf(&statement->base.source_position,
8989 "'default' label not within a switch statement");
8992 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
8999 * Parse a label statement.
9001 static statement_t *parse_label_statement(void)
9003 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9004 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9005 statement->label.label = label;
9007 PUSH_PARENT(statement);
9009 /* if statement is already set then the label is defined twice,
9010 * otherwise it was just mentioned in a goto/local label declaration so far
9012 source_position_t const* const pos = &statement->base.source_position;
9013 if (label->statement != NULL) {
9014 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9016 label->base.source_position = *pos;
9017 label->statement = statement;
9022 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9023 parse_attributes(NULL); // TODO process attributes
9026 statement->label.statement = parse_label_inner_statement(statement, "label");
9028 /* remember the labels in a list for later checking */
9029 *label_anchor = &statement->label;
9030 label_anchor = &statement->label.next;
9036 static statement_t *parse_inner_statement(void)
9038 statement_t *const stmt = parse_statement();
9039 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9040 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9041 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9042 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9048 * Parse an expression in parentheses and mark its variables as read.
9050 static expression_t *parse_condition(void)
9052 add_anchor_token(')');
9054 expression_t *const expr = parse_expression();
9055 mark_vars_read(expr, NULL);
9056 rem_anchor_token(')');
9062 * Parse an if statement.
9064 static statement_t *parse_if(void)
9066 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9070 PUSH_PARENT(statement);
9071 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9073 add_anchor_token(T_else);
9075 expression_t *const expr = parse_condition();
9076 statement->ifs.condition = expr;
9077 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9079 semantic_condition(expr, "condition of 'if'-statment");
9081 statement_t *const true_stmt = parse_inner_statement();
9082 statement->ifs.true_statement = true_stmt;
9083 rem_anchor_token(T_else);
9085 if (true_stmt->kind == STATEMENT_EMPTY) {
9086 warningf(WARN_EMPTY_BODY, HERE,
9087 "suggest braces around empty body in an ‘if’ statement");
9090 if (next_if(T_else)) {
9091 statement->ifs.false_statement = parse_inner_statement();
9093 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9094 warningf(WARN_EMPTY_BODY, HERE,
9095 "suggest braces around empty body in an ‘if’ statement");
9097 } else if (true_stmt->kind == STATEMENT_IF &&
9098 true_stmt->ifs.false_statement != NULL) {
9099 source_position_t const *const pos = &true_stmt->base.source_position;
9100 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9109 * Check that all enums are handled in a switch.
9111 * @param statement the switch statement to check
9113 static void check_enum_cases(const switch_statement_t *statement)
9115 if (!is_warn_on(WARN_SWITCH_ENUM))
9117 const type_t *type = skip_typeref(statement->expression->base.type);
9118 if (! is_type_enum(type))
9120 const enum_type_t *enumt = &type->enumt;
9122 /* if we have a default, no warnings */
9123 if (statement->default_label != NULL)
9126 /* FIXME: calculation of value should be done while parsing */
9127 /* TODO: quadratic algorithm here. Change to an n log n one */
9128 long last_value = -1;
9129 const entity_t *entry = enumt->enume->base.next;
9130 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9131 entry = entry->base.next) {
9132 const expression_t *expression = entry->enum_value.value;
9133 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9135 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9136 if (l->expression == NULL)
9138 if (l->first_case <= value && value <= l->last_case) {
9144 source_position_t const *const pos = &statement->base.source_position;
9145 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9152 * Parse a switch statement.
9154 static statement_t *parse_switch(void)
9156 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9160 PUSH_PARENT(statement);
9161 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9163 expression_t *const expr = parse_condition();
9164 type_t * type = skip_typeref(expr->base.type);
9165 if (is_type_integer(type)) {
9166 type = promote_integer(type);
9167 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9168 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9170 } else if (is_type_valid(type)) {
9171 errorf(&expr->base.source_position,
9172 "switch quantity is not an integer, but '%T'", type);
9173 type = type_error_type;
9175 statement->switchs.expression = create_implicit_cast(expr, type);
9177 switch_statement_t *rem = current_switch;
9178 current_switch = &statement->switchs;
9179 statement->switchs.body = parse_inner_statement();
9180 current_switch = rem;
9182 if (statement->switchs.default_label == NULL) {
9183 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9185 check_enum_cases(&statement->switchs);
9192 static statement_t *parse_loop_body(statement_t *const loop)
9194 statement_t *const rem = current_loop;
9195 current_loop = loop;
9197 statement_t *const body = parse_inner_statement();
9204 * Parse a while statement.
9206 static statement_t *parse_while(void)
9208 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9212 PUSH_PARENT(statement);
9213 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9215 expression_t *const cond = parse_condition();
9216 statement->whiles.condition = cond;
9217 /* §6.8.5:2 The controlling expression of an iteration statement shall
9218 * have scalar type. */
9219 semantic_condition(cond, "condition of 'while'-statement");
9221 statement->whiles.body = parse_loop_body(statement);
9229 * Parse a do statement.
9231 static statement_t *parse_do(void)
9233 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9237 PUSH_PARENT(statement);
9238 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9240 add_anchor_token(T_while);
9241 statement->do_while.body = parse_loop_body(statement);
9242 rem_anchor_token(T_while);
9245 expression_t *const cond = parse_condition();
9246 statement->do_while.condition = cond;
9247 /* §6.8.5:2 The controlling expression of an iteration statement shall
9248 * have scalar type. */
9249 semantic_condition(cond, "condition of 'do-while'-statement");
9258 * Parse a for statement.
9260 static statement_t *parse_for(void)
9262 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9266 PUSH_PARENT(statement);
9267 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9269 add_anchor_token(')');
9275 } else if (is_declaration_specifier(&token)) {
9276 parse_declaration(record_entity, DECL_FLAGS_NONE);
9278 add_anchor_token(';');
9279 expression_t *const init = parse_expression();
9280 statement->fors.initialisation = init;
9281 mark_vars_read(init, ENT_ANY);
9282 if (!expression_has_effect(init)) {
9283 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9285 rem_anchor_token(';');
9291 if (token.kind != ';') {
9292 add_anchor_token(';');
9293 expression_t *const cond = parse_expression();
9294 statement->fors.condition = cond;
9295 /* §6.8.5:2 The controlling expression of an iteration statement
9296 * shall have scalar type. */
9297 semantic_condition(cond, "condition of 'for'-statement");
9298 mark_vars_read(cond, NULL);
9299 rem_anchor_token(';');
9302 if (token.kind != ')') {
9303 expression_t *const step = parse_expression();
9304 statement->fors.step = step;
9305 mark_vars_read(step, ENT_ANY);
9306 if (!expression_has_effect(step)) {
9307 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9310 rem_anchor_token(')');
9312 statement->fors.body = parse_loop_body(statement);
9320 * Parse a goto statement.
9322 static statement_t *parse_goto(void)
9324 statement_t *statement;
9325 if (GNU_MODE && look_ahead(1)->kind == '*') {
9326 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9330 expression_t *expression = parse_expression();
9331 mark_vars_read(expression, NULL);
9333 /* Argh: although documentation says the expression must be of type void*,
9334 * gcc accepts anything that can be casted into void* without error */
9335 type_t *type = expression->base.type;
9337 if (type != type_error_type) {
9338 if (!is_type_pointer(type) && !is_type_integer(type)) {
9339 errorf(&expression->base.source_position,
9340 "cannot convert to a pointer type");
9341 } else if (type != type_void_ptr) {
9342 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9344 expression = create_implicit_cast(expression, type_void_ptr);
9347 statement->computed_goto.expression = expression;
9349 statement = allocate_statement_zero(STATEMENT_GOTO);
9352 label_t *const label = get_label("while parsing goto");
9355 statement->gotos.label = label;
9357 /* remember the goto's in a list for later checking */
9358 *goto_anchor = &statement->gotos;
9359 goto_anchor = &statement->gotos.next;
9361 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9370 * Parse a continue statement.
9372 static statement_t *parse_continue(void)
9374 if (current_loop == NULL) {
9375 errorf(HERE, "continue statement not within loop");
9378 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9386 * Parse a break statement.
9388 static statement_t *parse_break(void)
9390 if (current_switch == NULL && current_loop == NULL) {
9391 errorf(HERE, "break statement not within loop or switch");
9394 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9402 * Parse a __leave statement.
9404 static statement_t *parse_leave_statement(void)
9406 if (current_try == NULL) {
9407 errorf(HERE, "__leave statement not within __try");
9410 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9418 * Check if a given entity represents a local variable.
9420 static bool is_local_variable(const entity_t *entity)
9422 if (entity->kind != ENTITY_VARIABLE)
9425 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9426 case STORAGE_CLASS_AUTO:
9427 case STORAGE_CLASS_REGISTER: {
9428 const type_t *type = skip_typeref(entity->declaration.type);
9429 if (is_type_function(type)) {
9441 * Check if a given expression represents a local variable.
9443 static bool expression_is_local_variable(const expression_t *expression)
9445 if (expression->base.kind != EXPR_REFERENCE) {
9448 const entity_t *entity = expression->reference.entity;
9449 return is_local_variable(entity);
9453 * Check if a given expression represents a local variable and
9454 * return its declaration then, else return NULL.
9456 entity_t *expression_is_variable(const expression_t *expression)
9458 if (expression->base.kind != EXPR_REFERENCE) {
9461 entity_t *entity = expression->reference.entity;
9462 if (entity->kind != ENTITY_VARIABLE)
9468 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9470 if (c_mode & _CXX || strict_mode) {
9473 warningf(WARN_OTHER, pos, msg);
9478 * Parse a return statement.
9480 static statement_t *parse_return(void)
9482 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9485 expression_t *return_value = NULL;
9486 if (token.kind != ';') {
9487 return_value = parse_expression();
9488 mark_vars_read(return_value, NULL);
9491 const type_t *const func_type = skip_typeref(current_function->base.type);
9492 assert(is_type_function(func_type));
9493 type_t *const return_type = skip_typeref(func_type->function.return_type);
9495 source_position_t const *const pos = &statement->base.source_position;
9496 if (return_value != NULL) {
9497 type_t *return_value_type = skip_typeref(return_value->base.type);
9499 if (is_type_void(return_type)) {
9500 if (!is_type_void(return_value_type)) {
9501 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9502 /* Only warn in C mode, because GCC does the same */
9503 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9504 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9505 /* Only warn in C mode, because GCC does the same */
9506 err_or_warn(pos, "'return' with expression in function returning 'void'");
9509 assign_error_t error = semantic_assign(return_type, return_value);
9510 report_assign_error(error, return_type, return_value, "'return'",
9513 return_value = create_implicit_cast(return_value, return_type);
9514 /* check for returning address of a local var */
9515 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9516 const expression_t *expression = return_value->unary.value;
9517 if (expression_is_local_variable(expression)) {
9518 warningf(WARN_OTHER, pos, "function returns address of local variable");
9521 } else if (!is_type_void(return_type)) {
9522 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9523 err_or_warn(pos, "'return' without value, in function returning non-void");
9525 statement->returns.value = return_value;
9532 * Parse a declaration statement.
9534 static statement_t *parse_declaration_statement(void)
9536 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9538 entity_t *before = current_scope->last_entity;
9540 parse_external_declaration();
9542 parse_declaration(record_entity, DECL_FLAGS_NONE);
9545 declaration_statement_t *const decl = &statement->declaration;
9546 entity_t *const begin =
9547 before != NULL ? before->base.next : current_scope->entities;
9548 decl->declarations_begin = begin;
9549 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9555 * Parse an expression statement, ie. expr ';'.
9557 static statement_t *parse_expression_statement(void)
9559 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9561 expression_t *const expr = parse_expression();
9562 statement->expression.expression = expr;
9563 mark_vars_read(expr, ENT_ANY);
9570 * Parse a microsoft __try { } __finally { } or
9571 * __try{ } __except() { }
9573 static statement_t *parse_ms_try_statment(void)
9575 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9578 PUSH_PARENT(statement);
9580 ms_try_statement_t *rem = current_try;
9581 current_try = &statement->ms_try;
9582 statement->ms_try.try_statement = parse_compound_statement(false);
9587 if (next_if(T___except)) {
9588 expression_t *const expr = parse_condition();
9589 type_t * type = skip_typeref(expr->base.type);
9590 if (is_type_integer(type)) {
9591 type = promote_integer(type);
9592 } else if (is_type_valid(type)) {
9593 errorf(&expr->base.source_position,
9594 "__expect expression is not an integer, but '%T'", type);
9595 type = type_error_type;
9597 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9598 } else if (!next_if(T__finally)) {
9599 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9601 statement->ms_try.final_statement = parse_compound_statement(false);
9605 static statement_t *parse_empty_statement(void)
9607 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9608 statement_t *const statement = create_empty_statement();
9613 static statement_t *parse_local_label_declaration(void)
9615 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9619 entity_t *begin = NULL;
9620 entity_t *end = NULL;
9621 entity_t **anchor = &begin;
9622 add_anchor_token(';');
9623 add_anchor_token(',');
9625 source_position_t pos;
9626 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9628 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9629 if (entity != NULL && entity->base.parent_scope == current_scope) {
9630 source_position_t const *const ppos = &entity->base.source_position;
9631 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9633 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9634 entity->base.parent_scope = current_scope;
9637 anchor = &entity->base.next;
9640 environment_push(entity);
9643 } while (next_if(','));
9644 rem_anchor_token(',');
9645 rem_anchor_token(';');
9647 statement->declaration.declarations_begin = begin;
9648 statement->declaration.declarations_end = end;
9652 static void parse_namespace_definition(void)
9656 entity_t *entity = NULL;
9657 symbol_t *symbol = NULL;
9659 if (token.kind == T_IDENTIFIER) {
9660 symbol = token.base.symbol;
9661 entity = get_entity(symbol, NAMESPACE_NORMAL);
9662 if (entity && entity->kind != ENTITY_NAMESPACE) {
9664 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9665 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9671 if (entity == NULL) {
9672 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9673 entity->base.parent_scope = current_scope;
9676 if (token.kind == '=') {
9677 /* TODO: parse namespace alias */
9678 panic("namespace alias definition not supported yet");
9681 environment_push(entity);
9682 append_entity(current_scope, entity);
9684 PUSH_SCOPE(&entity->namespacee.members);
9685 PUSH_CURRENT_ENTITY(entity);
9687 add_anchor_token('}');
9690 rem_anchor_token('}');
9693 POP_CURRENT_ENTITY();
9698 * Parse a statement.
9699 * There's also parse_statement() which additionally checks for
9700 * "statement has no effect" warnings
9702 static statement_t *intern_parse_statement(void)
9704 /* declaration or statement */
9705 statement_t *statement;
9706 switch (token.kind) {
9707 case T_IDENTIFIER: {
9708 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9709 if (la1_type == ':') {
9710 statement = parse_label_statement();
9711 } else if (is_typedef_symbol(token.base.symbol)) {
9712 statement = parse_declaration_statement();
9714 /* it's an identifier, the grammar says this must be an
9715 * expression statement. However it is common that users mistype
9716 * declaration types, so we guess a bit here to improve robustness
9717 * for incorrect programs */
9721 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9723 statement = parse_expression_statement();
9727 statement = parse_declaration_statement();
9735 case T___extension__: {
9736 /* This can be a prefix to a declaration or an expression statement.
9737 * We simply eat it now and parse the rest with tail recursion. */
9739 statement = intern_parse_statement();
9745 statement = parse_declaration_statement();
9749 statement = parse_local_label_declaration();
9752 case ';': statement = parse_empty_statement(); break;
9753 case '{': statement = parse_compound_statement(false); break;
9754 case T___leave: statement = parse_leave_statement(); break;
9755 case T___try: statement = parse_ms_try_statment(); break;
9756 case T_asm: statement = parse_asm_statement(); break;
9757 case T_break: statement = parse_break(); break;
9758 case T_case: statement = parse_case_statement(); break;
9759 case T_continue: statement = parse_continue(); break;
9760 case T_default: statement = parse_default_statement(); break;
9761 case T_do: statement = parse_do(); break;
9762 case T_for: statement = parse_for(); break;
9763 case T_goto: statement = parse_goto(); break;
9764 case T_if: statement = parse_if(); break;
9765 case T_return: statement = parse_return(); break;
9766 case T_switch: statement = parse_switch(); break;
9767 case T_while: statement = parse_while(); break;
9770 statement = parse_expression_statement();
9774 errorf(HERE, "unexpected token %K while parsing statement", &token);
9775 statement = create_error_statement();
9784 * parse a statement and emits "statement has no effect" warning if needed
9785 * (This is really a wrapper around intern_parse_statement with check for 1
9786 * single warning. It is needed, because for statement expressions we have
9787 * to avoid the warning on the last statement)
9789 static statement_t *parse_statement(void)
9791 statement_t *statement = intern_parse_statement();
9793 if (statement->kind == STATEMENT_EXPRESSION) {
9794 expression_t *expression = statement->expression.expression;
9795 if (!expression_has_effect(expression)) {
9796 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9804 * Parse a compound statement.
9806 static statement_t *parse_compound_statement(bool inside_expression_statement)
9808 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9810 PUSH_PARENT(statement);
9811 PUSH_SCOPE(&statement->compound.scope);
9814 add_anchor_token('}');
9815 /* tokens, which can start a statement */
9816 /* TODO MS, __builtin_FOO */
9817 add_anchor_token('!');
9818 add_anchor_token('&');
9819 add_anchor_token('(');
9820 add_anchor_token('*');
9821 add_anchor_token('+');
9822 add_anchor_token('-');
9823 add_anchor_token(';');
9824 add_anchor_token('{');
9825 add_anchor_token('~');
9826 add_anchor_token(T_CHARACTER_CONSTANT);
9827 add_anchor_token(T_COLONCOLON);
9828 add_anchor_token(T_FLOATINGPOINT);
9829 add_anchor_token(T_IDENTIFIER);
9830 add_anchor_token(T_INTEGER);
9831 add_anchor_token(T_MINUSMINUS);
9832 add_anchor_token(T_PLUSPLUS);
9833 add_anchor_token(T_STRING_LITERAL);
9834 add_anchor_token(T__Bool);
9835 add_anchor_token(T__Complex);
9836 add_anchor_token(T__Imaginary);
9837 add_anchor_token(T___FUNCTION__);
9838 add_anchor_token(T___PRETTY_FUNCTION__);
9839 add_anchor_token(T___alignof__);
9840 add_anchor_token(T___attribute__);
9841 add_anchor_token(T___builtin_va_start);
9842 add_anchor_token(T___extension__);
9843 add_anchor_token(T___func__);
9844 add_anchor_token(T___imag__);
9845 add_anchor_token(T___label__);
9846 add_anchor_token(T___real__);
9847 add_anchor_token(T___thread);
9848 add_anchor_token(T_asm);
9849 add_anchor_token(T_auto);
9850 add_anchor_token(T_bool);
9851 add_anchor_token(T_break);
9852 add_anchor_token(T_case);
9853 add_anchor_token(T_char);
9854 add_anchor_token(T_class);
9855 add_anchor_token(T_const);
9856 add_anchor_token(T_const_cast);
9857 add_anchor_token(T_continue);
9858 add_anchor_token(T_default);
9859 add_anchor_token(T_delete);
9860 add_anchor_token(T_double);
9861 add_anchor_token(T_do);
9862 add_anchor_token(T_dynamic_cast);
9863 add_anchor_token(T_enum);
9864 add_anchor_token(T_extern);
9865 add_anchor_token(T_false);
9866 add_anchor_token(T_float);
9867 add_anchor_token(T_for);
9868 add_anchor_token(T_goto);
9869 add_anchor_token(T_if);
9870 add_anchor_token(T_inline);
9871 add_anchor_token(T_int);
9872 add_anchor_token(T_long);
9873 add_anchor_token(T_new);
9874 add_anchor_token(T_operator);
9875 add_anchor_token(T_register);
9876 add_anchor_token(T_reinterpret_cast);
9877 add_anchor_token(T_restrict);
9878 add_anchor_token(T_return);
9879 add_anchor_token(T_short);
9880 add_anchor_token(T_signed);
9881 add_anchor_token(T_sizeof);
9882 add_anchor_token(T_static);
9883 add_anchor_token(T_static_cast);
9884 add_anchor_token(T_struct);
9885 add_anchor_token(T_switch);
9886 add_anchor_token(T_template);
9887 add_anchor_token(T_this);
9888 add_anchor_token(T_throw);
9889 add_anchor_token(T_true);
9890 add_anchor_token(T_try);
9891 add_anchor_token(T_typedef);
9892 add_anchor_token(T_typeid);
9893 add_anchor_token(T_typename);
9894 add_anchor_token(T_typeof);
9895 add_anchor_token(T_union);
9896 add_anchor_token(T_unsigned);
9897 add_anchor_token(T_using);
9898 add_anchor_token(T_void);
9899 add_anchor_token(T_volatile);
9900 add_anchor_token(T_wchar_t);
9901 add_anchor_token(T_while);
9903 statement_t **anchor = &statement->compound.statements;
9904 bool only_decls_so_far = true;
9905 while (token.kind != '}' && token.kind != T_EOF) {
9906 statement_t *sub_statement = intern_parse_statement();
9907 if (sub_statement->kind == STATEMENT_ERROR) {
9911 if (sub_statement->kind != STATEMENT_DECLARATION) {
9912 only_decls_so_far = false;
9913 } else if (!only_decls_so_far) {
9914 source_position_t const *const pos = &sub_statement->base.source_position;
9915 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9918 *anchor = sub_statement;
9919 anchor = &sub_statement->base.next;
9923 /* look over all statements again to produce no effect warnings */
9924 if (is_warn_on(WARN_UNUSED_VALUE)) {
9925 statement_t *sub_statement = statement->compound.statements;
9926 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9927 if (sub_statement->kind != STATEMENT_EXPRESSION)
9929 /* don't emit a warning for the last expression in an expression
9930 * statement as it has always an effect */
9931 if (inside_expression_statement && sub_statement->base.next == NULL)
9934 expression_t *expression = sub_statement->expression.expression;
9935 if (!expression_has_effect(expression)) {
9936 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9941 rem_anchor_token(T_while);
9942 rem_anchor_token(T_wchar_t);
9943 rem_anchor_token(T_volatile);
9944 rem_anchor_token(T_void);
9945 rem_anchor_token(T_using);
9946 rem_anchor_token(T_unsigned);
9947 rem_anchor_token(T_union);
9948 rem_anchor_token(T_typeof);
9949 rem_anchor_token(T_typename);
9950 rem_anchor_token(T_typeid);
9951 rem_anchor_token(T_typedef);
9952 rem_anchor_token(T_try);
9953 rem_anchor_token(T_true);
9954 rem_anchor_token(T_throw);
9955 rem_anchor_token(T_this);
9956 rem_anchor_token(T_template);
9957 rem_anchor_token(T_switch);
9958 rem_anchor_token(T_struct);
9959 rem_anchor_token(T_static_cast);
9960 rem_anchor_token(T_static);
9961 rem_anchor_token(T_sizeof);
9962 rem_anchor_token(T_signed);
9963 rem_anchor_token(T_short);
9964 rem_anchor_token(T_return);
9965 rem_anchor_token(T_restrict);
9966 rem_anchor_token(T_reinterpret_cast);
9967 rem_anchor_token(T_register);
9968 rem_anchor_token(T_operator);
9969 rem_anchor_token(T_new);
9970 rem_anchor_token(T_long);
9971 rem_anchor_token(T_int);
9972 rem_anchor_token(T_inline);
9973 rem_anchor_token(T_if);
9974 rem_anchor_token(T_goto);
9975 rem_anchor_token(T_for);
9976 rem_anchor_token(T_float);
9977 rem_anchor_token(T_false);
9978 rem_anchor_token(T_extern);
9979 rem_anchor_token(T_enum);
9980 rem_anchor_token(T_dynamic_cast);
9981 rem_anchor_token(T_do);
9982 rem_anchor_token(T_double);
9983 rem_anchor_token(T_delete);
9984 rem_anchor_token(T_default);
9985 rem_anchor_token(T_continue);
9986 rem_anchor_token(T_const_cast);
9987 rem_anchor_token(T_const);
9988 rem_anchor_token(T_class);
9989 rem_anchor_token(T_char);
9990 rem_anchor_token(T_case);
9991 rem_anchor_token(T_break);
9992 rem_anchor_token(T_bool);
9993 rem_anchor_token(T_auto);
9994 rem_anchor_token(T_asm);
9995 rem_anchor_token(T___thread);
9996 rem_anchor_token(T___real__);
9997 rem_anchor_token(T___label__);
9998 rem_anchor_token(T___imag__);
9999 rem_anchor_token(T___func__);
10000 rem_anchor_token(T___extension__);
10001 rem_anchor_token(T___builtin_va_start);
10002 rem_anchor_token(T___attribute__);
10003 rem_anchor_token(T___alignof__);
10004 rem_anchor_token(T___PRETTY_FUNCTION__);
10005 rem_anchor_token(T___FUNCTION__);
10006 rem_anchor_token(T__Imaginary);
10007 rem_anchor_token(T__Complex);
10008 rem_anchor_token(T__Bool);
10009 rem_anchor_token(T_STRING_LITERAL);
10010 rem_anchor_token(T_PLUSPLUS);
10011 rem_anchor_token(T_MINUSMINUS);
10012 rem_anchor_token(T_INTEGER);
10013 rem_anchor_token(T_IDENTIFIER);
10014 rem_anchor_token(T_FLOATINGPOINT);
10015 rem_anchor_token(T_COLONCOLON);
10016 rem_anchor_token(T_CHARACTER_CONSTANT);
10017 rem_anchor_token('~');
10018 rem_anchor_token('{');
10019 rem_anchor_token(';');
10020 rem_anchor_token('-');
10021 rem_anchor_token('+');
10022 rem_anchor_token('*');
10023 rem_anchor_token('(');
10024 rem_anchor_token('&');
10025 rem_anchor_token('!');
10026 rem_anchor_token('}');
10034 * Check for unused global static functions and variables
10036 static void check_unused_globals(void)
10038 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10041 for (const entity_t *entity = file_scope->entities; entity != NULL;
10042 entity = entity->base.next) {
10043 if (!is_declaration(entity))
10046 const declaration_t *declaration = &entity->declaration;
10047 if (declaration->used ||
10048 declaration->modifiers & DM_UNUSED ||
10049 declaration->modifiers & DM_USED ||
10050 declaration->storage_class != STORAGE_CLASS_STATIC)
10055 if (entity->kind == ENTITY_FUNCTION) {
10056 /* inhibit warning for static inline functions */
10057 if (entity->function.is_inline)
10060 why = WARN_UNUSED_FUNCTION;
10061 s = entity->function.statement != NULL ? "defined" : "declared";
10063 why = WARN_UNUSED_VARIABLE;
10067 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10071 static void parse_global_asm(void)
10073 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10076 add_anchor_token(';');
10077 add_anchor_token(')');
10078 add_anchor_token(T_STRING_LITERAL);
10081 rem_anchor_token(T_STRING_LITERAL);
10082 statement->asms.asm_text = parse_string_literals();
10083 statement->base.next = unit->global_asm;
10084 unit->global_asm = statement;
10086 rem_anchor_token(')');
10088 rem_anchor_token(';');
10092 static void parse_linkage_specification(void)
10096 source_position_t const pos = *HERE;
10097 char const *const linkage = parse_string_literals().begin;
10099 linkage_kind_t old_linkage = current_linkage;
10100 linkage_kind_t new_linkage;
10101 if (streq(linkage, "C")) {
10102 new_linkage = LINKAGE_C;
10103 } else if (streq(linkage, "C++")) {
10104 new_linkage = LINKAGE_CXX;
10106 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10107 new_linkage = LINKAGE_C;
10109 current_linkage = new_linkage;
10111 if (next_if('{')) {
10118 assert(current_linkage == new_linkage);
10119 current_linkage = old_linkage;
10122 static void parse_external(void)
10124 switch (token.kind) {
10126 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10127 parse_linkage_specification();
10129 DECLARATION_START_NO_EXTERN
10131 case T___extension__:
10132 /* tokens below are for implicit int */
10133 case '&': /* & x; -> int& x; (and error later, because C++ has no
10135 case '*': /* * x; -> int* x; */
10136 case '(': /* (x); -> int (x); */
10138 parse_external_declaration();
10144 parse_global_asm();
10148 parse_namespace_definition();
10152 if (!strict_mode) {
10153 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10160 errorf(HERE, "stray %K outside of function", &token);
10161 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10162 eat_until_matching_token(token.kind);
10168 static void parse_externals(void)
10170 add_anchor_token('}');
10171 add_anchor_token(T_EOF);
10174 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10175 unsigned short token_anchor_copy[T_LAST_TOKEN];
10176 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10179 while (token.kind != T_EOF && token.kind != '}') {
10181 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10182 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10184 /* the anchor set and its copy differs */
10185 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10188 if (in_gcc_extension) {
10189 /* an gcc extension scope was not closed */
10190 internal_errorf(HERE, "Leaked __extension__");
10197 rem_anchor_token(T_EOF);
10198 rem_anchor_token('}');
10202 * Parse a translation unit.
10204 static void parse_translation_unit(void)
10206 add_anchor_token(T_EOF);
10211 if (token.kind == T_EOF)
10214 errorf(HERE, "stray %K outside of function", &token);
10215 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10216 eat_until_matching_token(token.kind);
10221 void set_default_visibility(elf_visibility_tag_t visibility)
10223 default_visibility = visibility;
10229 * @return the translation unit or NULL if errors occurred.
10231 void start_parsing(void)
10233 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10234 label_stack = NEW_ARR_F(stack_entry_t, 0);
10235 diagnostic_count = 0;
10239 print_to_file(stderr);
10241 assert(unit == NULL);
10242 unit = allocate_ast_zero(sizeof(unit[0]));
10244 assert(file_scope == NULL);
10245 file_scope = &unit->scope;
10247 assert(current_scope == NULL);
10248 scope_push(&unit->scope);
10250 create_gnu_builtins();
10252 create_microsoft_intrinsics();
10255 translation_unit_t *finish_parsing(void)
10257 assert(current_scope == &unit->scope);
10260 assert(file_scope == &unit->scope);
10261 check_unused_globals();
10264 DEL_ARR_F(environment_stack);
10265 DEL_ARR_F(label_stack);
10267 translation_unit_t *result = unit;
10272 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10273 * are given length one. */
10274 static void complete_incomplete_arrays(void)
10276 size_t n = ARR_LEN(incomplete_arrays);
10277 for (size_t i = 0; i != n; ++i) {
10278 declaration_t *const decl = incomplete_arrays[i];
10279 type_t *const type = skip_typeref(decl->type);
10281 if (!is_type_incomplete(type))
10284 source_position_t const *const pos = &decl->base.source_position;
10285 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10287 type_t *const new_type = duplicate_type(type);
10288 new_type->array.size_constant = true;
10289 new_type->array.has_implicit_size = true;
10290 new_type->array.size = 1;
10292 type_t *const result = identify_new_type(new_type);
10294 decl->type = result;
10298 static void prepare_main_collect2(entity_t *const entity)
10300 PUSH_SCOPE(&entity->function.statement->compound.scope);
10302 // create call to __main
10303 symbol_t *symbol = symbol_table_insert("__main");
10304 entity_t *subsubmain_ent
10305 = create_implicit_function(symbol, &builtin_source_position);
10307 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10308 type_t *ftype = subsubmain_ent->declaration.type;
10309 ref->base.source_position = builtin_source_position;
10310 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10311 ref->reference.entity = subsubmain_ent;
10313 expression_t *call = allocate_expression_zero(EXPR_CALL);
10314 call->base.source_position = builtin_source_position;
10315 call->base.type = type_void;
10316 call->call.function = ref;
10318 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10319 expr_statement->base.source_position = builtin_source_position;
10320 expr_statement->expression.expression = call;
10322 statement_t *statement = entity->function.statement;
10323 assert(statement->kind == STATEMENT_COMPOUND);
10324 compound_statement_t *compounds = &statement->compound;
10326 expr_statement->base.next = compounds->statements;
10327 compounds->statements = expr_statement;
10334 lookahead_bufpos = 0;
10335 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10338 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10339 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10340 parse_translation_unit();
10341 complete_incomplete_arrays();
10342 DEL_ARR_F(incomplete_arrays);
10343 incomplete_arrays = NULL;
10347 * Initialize the parser.
10349 void init_parser(void)
10351 sym_anonymous = symbol_table_insert("<anonymous>");
10353 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10355 init_expression_parsers();
10356 obstack_init(&temp_obst);
10360 * Terminate the parser.
10362 void exit_parser(void)
10364 obstack_free(&temp_obst, NULL);