2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 2
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool have_arguments; /**< True, if this attribute has arguments. */
68 atomic_type_kind_t akind;
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
102 * Capture a MS __base extension.
104 typedef struct based_spec_t {
105 source_position_t source_position;
106 variable_t *base_variable;
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
111 /** The current token. */
112 static token_t token;
113 /** The lookahead ring-buffer. */
114 static token_t lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static int lookahead_bufpos;
117 static stack_entry_t *environment_stack = NULL;
118 static stack_entry_t *label_stack = NULL;
119 static scope_t *file_scope = NULL;
120 static scope_t *current_scope = NULL;
121 /** Point to the current function declaration if inside a function. */
122 static function_t *current_function = NULL;
123 static entity_t *current_init_decl = NULL;
124 static switch_statement_t *current_switch = NULL;
125 static statement_t *current_loop = NULL;
126 static statement_t *current_parent = NULL;
127 static ms_try_statement_t *current_try = NULL;
128 static linkage_kind_t current_linkage = LINKAGE_INVALID;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t **goto_anchor = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t **label_anchor = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
140 static entity_t *anonymous_entity;
141 static declaration_t **incomplete_arrays;
144 #define PUSH_PARENT(stmt) \
145 statement_t *const prev_parent = current_parent; \
146 ((void)(current_parent = (stmt)))
147 #define POP_PARENT ((void)(current_parent = prev_parent))
149 /** special symbol used for anonymous entities. */
150 static const symbol_t *sym_anonymous = NULL;
152 /* symbols for Microsoft extended-decl-modifier */
153 static const symbol_t *sym_align = NULL;
154 static const symbol_t *sym_allocate = NULL;
155 static const symbol_t *sym_dllimport = NULL;
156 static const symbol_t *sym_dllexport = NULL;
157 static const symbol_t *sym_naked = NULL;
158 static const symbol_t *sym_noinline = NULL;
159 static const symbol_t *sym_returns_twice = NULL;
160 static const symbol_t *sym_noreturn = NULL;
161 static const symbol_t *sym_nothrow = NULL;
162 static const symbol_t *sym_novtable = NULL;
163 static const symbol_t *sym_property = NULL;
164 static const symbol_t *sym_get = NULL;
165 static const symbol_t *sym_put = NULL;
166 static const symbol_t *sym_selectany = NULL;
167 static const symbol_t *sym_thread = NULL;
168 static const symbol_t *sym_uuid = NULL;
169 static const symbol_t *sym_deprecated = NULL;
170 static const symbol_t *sym_restrict = NULL;
171 static const symbol_t *sym_noalias = NULL;
173 /** The token anchor set */
174 static unsigned char token_anchor_set[T_LAST_TOKEN];
176 /** The current source position. */
177 #define HERE (&token.source_position)
179 /** true if we are in GCC mode. */
180 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
182 static type_t *type_valist;
184 static statement_t *parse_compound_statement(bool inside_expression_statement);
185 static statement_t *parse_statement(void);
187 static expression_t *parse_sub_expression(precedence_t);
188 static expression_t *parse_expression(void);
189 static type_t *parse_typename(void);
190 static void parse_externals(void);
191 static void parse_external(void);
193 static void parse_compound_type_entries(compound_t *compound_declaration);
195 typedef enum declarator_flags_t {
197 DECL_MAY_BE_ABSTRACT = 1U << 0,
198 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
199 DECL_IS_PARAMETER = 1U << 2
200 } declarator_flags_t;
202 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
203 declarator_flags_t flags);
205 static entity_t *record_entity(entity_t *entity, bool is_definition);
207 static void semantic_comparison(binary_expression_t *expression);
209 #define STORAGE_CLASSES \
210 STORAGE_CLASSES_NO_EXTERN \
213 #define STORAGE_CLASSES_NO_EXTERN \
220 #define TYPE_QUALIFIERS \
225 case T__forceinline: \
226 case T___attribute__:
228 #define COMPLEX_SPECIFIERS \
230 #define IMAGINARY_SPECIFIERS \
233 #define TYPE_SPECIFIERS \
235 case T___builtin_va_list: \
255 #define DECLARATION_START \
260 #define DECLARATION_START_NO_EXTERN \
261 STORAGE_CLASSES_NO_EXTERN \
265 #define TYPENAME_START \
269 #define EXPRESSION_START \
278 case T_CHARACTER_CONSTANT: \
279 case T_FLOATINGPOINT: \
283 case T_STRING_LITERAL: \
284 case T_WIDE_CHARACTER_CONSTANT: \
285 case T_WIDE_STRING_LITERAL: \
286 case T___FUNCDNAME__: \
287 case T___FUNCSIG__: \
288 case T___FUNCTION__: \
289 case T___PRETTY_FUNCTION__: \
290 case T___alignof__: \
291 case T___builtin_alloca: \
292 case T___builtin_classify_type: \
293 case T___builtin_constant_p: \
294 case T___builtin_expect: \
295 case T___builtin_huge_val: \
296 case T___builtin_inf: \
297 case T___builtin_inff: \
298 case T___builtin_infl: \
299 case T___builtin_isgreater: \
300 case T___builtin_isgreaterequal: \
301 case T___builtin_isless: \
302 case T___builtin_islessequal: \
303 case T___builtin_islessgreater: \
304 case T___builtin_isunordered: \
305 case T___builtin_nan: \
306 case T___builtin_nanf: \
307 case T___builtin_nanl: \
308 case T___builtin_offsetof: \
309 case T___builtin_prefetch: \
310 case T___builtin_va_arg: \
311 case T___builtin_va_end: \
312 case T___builtin_va_start: \
323 * Allocate an AST node with given size and
324 * initialize all fields with zero.
326 static void *allocate_ast_zero(size_t size)
328 void *res = allocate_ast(size);
329 memset(res, 0, size);
334 * Returns the size of an entity node.
336 * @param kind the entity kind
338 static size_t get_entity_struct_size(entity_kind_t kind)
340 static const size_t sizes[] = {
341 [ENTITY_VARIABLE] = sizeof(variable_t),
342 [ENTITY_PARAMETER] = sizeof(parameter_t),
343 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
344 [ENTITY_FUNCTION] = sizeof(function_t),
345 [ENTITY_TYPEDEF] = sizeof(typedef_t),
346 [ENTITY_STRUCT] = sizeof(compound_t),
347 [ENTITY_UNION] = sizeof(compound_t),
348 [ENTITY_ENUM] = sizeof(enum_t),
349 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
350 [ENTITY_LABEL] = sizeof(label_t),
351 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
352 [ENTITY_NAMESPACE] = sizeof(namespace_t)
354 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
355 assert(sizes[kind] != 0);
360 * Allocate an entity of given kind and initialize all
363 static entity_t *allocate_entity_zero(entity_kind_t kind)
365 size_t size = get_entity_struct_size(kind);
366 entity_t *entity = allocate_ast_zero(size);
372 * Returns the size of a statement node.
374 * @param kind the statement kind
376 static size_t get_statement_struct_size(statement_kind_t kind)
378 static const size_t sizes[] = {
379 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
380 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
381 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
382 [STATEMENT_RETURN] = sizeof(return_statement_t),
383 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
384 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
385 [STATEMENT_IF] = sizeof(if_statement_t),
386 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
387 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
388 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
389 [STATEMENT_BREAK] = sizeof(statement_base_t),
390 [STATEMENT_GOTO] = sizeof(goto_statement_t),
391 [STATEMENT_LABEL] = sizeof(label_statement_t),
392 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
393 [STATEMENT_WHILE] = sizeof(while_statement_t),
394 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
395 [STATEMENT_FOR] = sizeof(for_statement_t),
396 [STATEMENT_ASM] = sizeof(asm_statement_t),
397 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
398 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
400 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
401 assert(sizes[kind] != 0);
406 * Returns the size of an expression node.
408 * @param kind the expression kind
410 static size_t get_expression_struct_size(expression_kind_t kind)
412 static const size_t sizes[] = {
413 [EXPR_INVALID] = sizeof(expression_base_t),
414 [EXPR_REFERENCE] = sizeof(reference_expression_t),
415 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
416 [EXPR_CONST] = sizeof(const_expression_t),
417 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
418 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
419 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
420 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
421 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
422 [EXPR_CALL] = sizeof(call_expression_t),
423 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
424 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
425 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
426 [EXPR_SELECT] = sizeof(select_expression_t),
427 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
428 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
429 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
430 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
431 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
432 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
433 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
434 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
435 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
436 [EXPR_VA_START] = sizeof(va_start_expression_t),
437 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
438 [EXPR_STATEMENT] = sizeof(statement_expression_t),
439 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
441 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
442 return sizes[EXPR_UNARY_FIRST];
444 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
445 return sizes[EXPR_BINARY_FIRST];
447 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
448 assert(sizes[kind] != 0);
453 * Allocate a statement node of given kind and initialize all
454 * fields with zero. Sets its source position to the position
455 * of the current token.
457 static statement_t *allocate_statement_zero(statement_kind_t kind)
459 size_t size = get_statement_struct_size(kind);
460 statement_t *res = allocate_ast_zero(size);
462 res->base.kind = kind;
463 res->base.parent = current_parent;
464 res->base.source_position = token.source_position;
469 * Allocate an expression node of given kind and initialize all
472 static expression_t *allocate_expression_zero(expression_kind_t kind)
474 size_t size = get_expression_struct_size(kind);
475 expression_t *res = allocate_ast_zero(size);
477 res->base.kind = kind;
478 res->base.type = type_error_type;
479 res->base.source_position = token.source_position;
484 * Creates a new invalid expression at the source position
485 * of the current token.
487 static expression_t *create_invalid_expression(void)
489 return allocate_expression_zero(EXPR_INVALID);
493 * Creates a new invalid statement.
495 static statement_t *create_invalid_statement(void)
497 return allocate_statement_zero(STATEMENT_INVALID);
501 * Allocate a new empty statement.
503 static statement_t *create_empty_statement(void)
505 return allocate_statement_zero(STATEMENT_EMPTY);
509 * Returns the size of a type node.
511 * @param kind the type kind
513 static size_t get_type_struct_size(type_kind_t kind)
515 static const size_t sizes[] = {
516 [TYPE_ATOMIC] = sizeof(atomic_type_t),
517 [TYPE_COMPLEX] = sizeof(complex_type_t),
518 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
519 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
520 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
521 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
522 [TYPE_ENUM] = sizeof(enum_type_t),
523 [TYPE_FUNCTION] = sizeof(function_type_t),
524 [TYPE_POINTER] = sizeof(pointer_type_t),
525 [TYPE_ARRAY] = sizeof(array_type_t),
526 [TYPE_BUILTIN] = sizeof(builtin_type_t),
527 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
528 [TYPE_TYPEOF] = sizeof(typeof_type_t),
530 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
531 assert(kind <= TYPE_TYPEOF);
532 assert(sizes[kind] != 0);
537 * Allocate a type node of given kind and initialize all
540 * @param kind type kind to allocate
542 static type_t *allocate_type_zero(type_kind_t kind)
544 size_t size = get_type_struct_size(kind);
545 type_t *res = obstack_alloc(type_obst, size);
546 memset(res, 0, size);
547 res->base.kind = kind;
553 * Returns the size of an initializer node.
555 * @param kind the initializer kind
557 static size_t get_initializer_size(initializer_kind_t kind)
559 static const size_t sizes[] = {
560 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
561 [INITIALIZER_STRING] = sizeof(initializer_string_t),
562 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
563 [INITIALIZER_LIST] = sizeof(initializer_list_t),
564 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
566 assert(kind < sizeof(sizes) / sizeof(*sizes));
567 assert(sizes[kind] != 0);
572 * Allocate an initializer node of given kind and initialize all
575 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
577 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
584 * Free a type from the type obstack.
586 static void free_type(void *type)
588 obstack_free(type_obst, type);
592 * Returns the index of the top element of the environment stack.
594 static size_t environment_top(void)
596 return ARR_LEN(environment_stack);
600 * Returns the index of the top element of the global label stack.
602 static size_t label_top(void)
604 return ARR_LEN(label_stack);
608 * Return the next token.
610 static inline void next_token(void)
612 token = lookahead_buffer[lookahead_bufpos];
613 lookahead_buffer[lookahead_bufpos] = lexer_token;
616 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
619 print_token(stderr, &token);
620 fprintf(stderr, "\n");
625 * Return the next token with a given lookahead.
627 static inline const token_t *look_ahead(int num)
629 assert(num > 0 && num <= MAX_LOOKAHEAD);
630 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
631 return &lookahead_buffer[pos];
635 * Adds a token type to the token type anchor set (a multi-set).
637 static void add_anchor_token(int token_type)
639 assert(0 <= token_type && token_type < T_LAST_TOKEN);
640 ++token_anchor_set[token_type];
644 * Set the number of tokens types of the given type
645 * to zero and return the old count.
647 static int save_and_reset_anchor_state(int token_type)
649 assert(0 <= token_type && token_type < T_LAST_TOKEN);
650 int count = token_anchor_set[token_type];
651 token_anchor_set[token_type] = 0;
656 * Restore the number of token types to the given count.
658 static void restore_anchor_state(int token_type, int count)
660 assert(0 <= token_type && token_type < T_LAST_TOKEN);
661 token_anchor_set[token_type] = count;
665 * Remove a token type from the token type anchor set (a multi-set).
667 static void rem_anchor_token(int token_type)
669 assert(0 <= token_type && token_type < T_LAST_TOKEN);
670 assert(token_anchor_set[token_type] != 0);
671 --token_anchor_set[token_type];
675 * Return true if the token type of the current token is
678 static bool at_anchor(void)
682 return token_anchor_set[token.type];
686 * Eat tokens until a matching token type is found.
688 static void eat_until_matching_token(int type)
692 case '(': end_token = ')'; break;
693 case '{': end_token = '}'; break;
694 case '[': end_token = ']'; break;
695 default: end_token = type; break;
698 unsigned parenthesis_count = 0;
699 unsigned brace_count = 0;
700 unsigned bracket_count = 0;
701 while (token.type != end_token ||
702 parenthesis_count != 0 ||
704 bracket_count != 0) {
705 switch (token.type) {
707 case '(': ++parenthesis_count; break;
708 case '{': ++brace_count; break;
709 case '[': ++bracket_count; break;
712 if (parenthesis_count > 0)
722 if (bracket_count > 0)
725 if (token.type == end_token &&
726 parenthesis_count == 0 &&
740 * Eat input tokens until an anchor is found.
742 static void eat_until_anchor(void)
744 while (token_anchor_set[token.type] == 0) {
745 if (token.type == '(' || token.type == '{' || token.type == '[')
746 eat_until_matching_token(token.type);
752 * Eat a whole block from input tokens.
754 static void eat_block(void)
756 eat_until_matching_token('{');
757 if (token.type == '}')
761 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
764 * Report a parse error because an expected token was not found.
767 #if defined __GNUC__ && __GNUC__ >= 4
768 __attribute__((sentinel))
770 void parse_error_expected(const char *message, ...)
772 if (message != NULL) {
773 errorf(HERE, "%s", message);
776 va_start(ap, message);
777 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
782 * Report an incompatible type.
784 static void type_error_incompatible(const char *msg,
785 const source_position_t *source_position, type_t *type1, type_t *type2)
787 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
792 * Expect the current token is the expected token.
793 * If not, generate an error, eat the current statement,
794 * and goto the end_error label.
796 #define expect(expected, error_label) \
798 if (UNLIKELY(token.type != (expected))) { \
799 parse_error_expected(NULL, (expected), NULL); \
800 add_anchor_token(expected); \
801 eat_until_anchor(); \
802 if (token.type == expected) \
804 rem_anchor_token(expected); \
811 * Push a given scope on the scope stack and make it the
814 static scope_t *scope_push(scope_t *new_scope)
816 if (current_scope != NULL) {
817 new_scope->depth = current_scope->depth + 1;
820 scope_t *old_scope = current_scope;
821 current_scope = new_scope;
826 * Pop the current scope from the scope stack.
828 static void scope_pop(scope_t *old_scope)
830 current_scope = old_scope;
834 * Search an entity by its symbol in a given namespace.
836 static entity_t *get_entity(const symbol_t *const symbol,
837 namespace_tag_t namespc)
839 entity_t *entity = symbol->entity;
840 for (; entity != NULL; entity = entity->base.symbol_next) {
841 if (entity->base.namespc == namespc)
849 * pushs an entity on the environment stack and links the corresponding symbol
852 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
854 symbol_t *symbol = entity->base.symbol;
855 entity_namespace_t namespc = entity->base.namespc;
856 assert(namespc != NAMESPACE_INVALID);
858 /* replace/add entity into entity list of the symbol */
861 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
866 /* replace an entry? */
867 if (iter->base.namespc == namespc) {
868 entity->base.symbol_next = iter->base.symbol_next;
874 /* remember old declaration */
876 entry.symbol = symbol;
877 entry.old_entity = iter;
878 entry.namespc = namespc;
879 ARR_APP1(stack_entry_t, *stack_ptr, entry);
883 * Push an entity on the environment stack.
885 static void environment_push(entity_t *entity)
887 assert(entity->base.source_position.input_name != NULL);
888 assert(entity->base.parent_scope != NULL);
889 stack_push(&environment_stack, entity);
893 * Push a declaration on the global label stack.
895 * @param declaration the declaration
897 static void label_push(entity_t *label)
899 /* we abuse the parameters scope as parent for the labels */
900 label->base.parent_scope = ¤t_function->parameters;
901 stack_push(&label_stack, label);
905 * pops symbols from the environment stack until @p new_top is the top element
907 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
909 stack_entry_t *stack = *stack_ptr;
910 size_t top = ARR_LEN(stack);
913 assert(new_top <= top);
917 for (i = top; i > new_top; --i) {
918 stack_entry_t *entry = &stack[i - 1];
920 entity_t *old_entity = entry->old_entity;
921 symbol_t *symbol = entry->symbol;
922 entity_namespace_t namespc = entry->namespc;
924 /* replace with old_entity/remove */
927 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
929 assert(iter != NULL);
930 /* replace an entry? */
931 if (iter->base.namespc == namespc)
935 /* restore definition from outer scopes (if there was one) */
936 if (old_entity != NULL) {
937 old_entity->base.symbol_next = iter->base.symbol_next;
938 *anchor = old_entity;
940 /* remove entry from list */
941 *anchor = iter->base.symbol_next;
945 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
949 * Pop all entries from the environment stack until the new_top
952 * @param new_top the new stack top
954 static void environment_pop_to(size_t new_top)
956 stack_pop_to(&environment_stack, new_top);
960 * Pop all entries from the global label stack until the new_top
963 * @param new_top the new stack top
965 static void label_pop_to(size_t new_top)
967 stack_pop_to(&label_stack, new_top);
970 static int get_akind_rank(atomic_type_kind_t akind)
976 * Return the type rank for an atomic type.
978 static int get_rank(const type_t *type)
980 assert(!is_typeref(type));
981 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
982 * and esp. footnote 108). However we can't fold constants (yet), so we
983 * can't decide whether unsigned int is possible, while int always works.
984 * (unsigned int would be preferable when possible... for stuff like
985 * struct { enum { ... } bla : 4; } ) */
986 if (type->kind == TYPE_ENUM)
987 return get_akind_rank(ATOMIC_TYPE_INT);
989 assert(type->kind == TYPE_ATOMIC);
990 return get_akind_rank(type->atomic.akind);
994 * Do integer promotion for a given type.
996 * @param type the type to promote
997 * @return the promoted type
999 static type_t *promote_integer(type_t *type)
1001 if (type->kind == TYPE_BITFIELD)
1002 type = type->bitfield.base_type;
1004 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
1011 * Create a cast expression.
1013 * @param expression the expression to cast
1014 * @param dest_type the destination type
1016 static expression_t *create_cast_expression(expression_t *expression,
1019 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1021 cast->unary.value = expression;
1022 cast->base.type = dest_type;
1028 * Check if a given expression represents a null pointer constant.
1030 * @param expression the expression to check
1032 static bool is_null_pointer_constant(const expression_t *expression)
1034 /* skip void* cast */
1035 if (expression->kind == EXPR_UNARY_CAST
1036 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1037 expression = expression->unary.value;
1040 /* TODO: not correct yet, should be any constant integer expression
1041 * which evaluates to 0 */
1042 if (expression->kind != EXPR_CONST)
1045 type_t *const type = skip_typeref(expression->base.type);
1046 if (!is_type_integer(type))
1049 return expression->conste.v.int_value == 0;
1053 * Create an implicit cast expression.
1055 * @param expression the expression to cast
1056 * @param dest_type the destination type
1058 static expression_t *create_implicit_cast(expression_t *expression,
1061 type_t *const source_type = expression->base.type;
1063 if (source_type == dest_type)
1066 return create_cast_expression(expression, dest_type);
1069 typedef enum assign_error_t {
1071 ASSIGN_ERROR_INCOMPATIBLE,
1072 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1073 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1074 ASSIGN_WARNING_POINTER_FROM_INT,
1075 ASSIGN_WARNING_INT_FROM_POINTER
1078 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1079 const expression_t *const right,
1080 const char *context,
1081 const source_position_t *source_position)
1083 type_t *const orig_type_right = right->base.type;
1084 type_t *const type_left = skip_typeref(orig_type_left);
1085 type_t *const type_right = skip_typeref(orig_type_right);
1088 case ASSIGN_SUCCESS:
1090 case ASSIGN_ERROR_INCOMPATIBLE:
1091 errorf(source_position,
1092 "destination type '%T' in %s is incompatible with type '%T'",
1093 orig_type_left, context, orig_type_right);
1096 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1097 if (warning.other) {
1098 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1099 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1101 /* the left type has all qualifiers from the right type */
1102 unsigned missing_qualifiers
1103 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1104 warningf(source_position,
1105 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1106 orig_type_left, context, orig_type_right, missing_qualifiers);
1111 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1112 if (warning.other) {
1113 warningf(source_position,
1114 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1115 orig_type_left, context, right, orig_type_right);
1119 case ASSIGN_WARNING_POINTER_FROM_INT:
1120 if (warning.other) {
1121 warningf(source_position,
1122 "%s makes pointer '%T' from integer '%T' without a cast",
1123 context, orig_type_left, orig_type_right);
1127 case ASSIGN_WARNING_INT_FROM_POINTER:
1128 if (warning.other) {
1129 warningf(source_position,
1130 "%s makes integer '%T' from pointer '%T' without a cast",
1131 context, orig_type_left, orig_type_right);
1136 panic("invalid error value");
1140 /** Implements the rules from § 6.5.16.1 */
1141 static assign_error_t semantic_assign(type_t *orig_type_left,
1142 const expression_t *const right)
1144 type_t *const orig_type_right = right->base.type;
1145 type_t *const type_left = skip_typeref(orig_type_left);
1146 type_t *const type_right = skip_typeref(orig_type_right);
1148 if (is_type_pointer(type_left)) {
1149 if (is_null_pointer_constant(right)) {
1150 return ASSIGN_SUCCESS;
1151 } else if (is_type_pointer(type_right)) {
1152 type_t *points_to_left
1153 = skip_typeref(type_left->pointer.points_to);
1154 type_t *points_to_right
1155 = skip_typeref(type_right->pointer.points_to);
1156 assign_error_t res = ASSIGN_SUCCESS;
1158 /* the left type has all qualifiers from the right type */
1159 unsigned missing_qualifiers
1160 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1161 if (missing_qualifiers != 0) {
1162 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1165 points_to_left = get_unqualified_type(points_to_left);
1166 points_to_right = get_unqualified_type(points_to_right);
1168 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1171 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1172 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1173 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1176 if (!types_compatible(points_to_left, points_to_right)) {
1177 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1181 } else if (is_type_integer(type_right)) {
1182 return ASSIGN_WARNING_POINTER_FROM_INT;
1184 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1185 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1186 && is_type_pointer(type_right))) {
1187 return ASSIGN_SUCCESS;
1188 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1189 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1190 type_t *const unqual_type_left = get_unqualified_type(type_left);
1191 type_t *const unqual_type_right = get_unqualified_type(type_right);
1192 if (types_compatible(unqual_type_left, unqual_type_right)) {
1193 return ASSIGN_SUCCESS;
1195 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1196 return ASSIGN_WARNING_INT_FROM_POINTER;
1199 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1200 return ASSIGN_SUCCESS;
1202 return ASSIGN_ERROR_INCOMPATIBLE;
1205 static expression_t *parse_constant_expression(void)
1207 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1209 if (!is_constant_expression(result)) {
1210 errorf(&result->base.source_position,
1211 "expression '%E' is not constant", result);
1217 static expression_t *parse_assignment_expression(void)
1219 return parse_sub_expression(PREC_ASSIGNMENT);
1222 static string_t parse_string_literals(void)
1224 assert(token.type == T_STRING_LITERAL);
1225 string_t result = token.v.string;
1229 while (token.type == T_STRING_LITERAL) {
1230 result = concat_strings(&result, &token.v.string);
1237 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1238 [GNU_AK_CONST] = "const",
1239 [GNU_AK_VOLATILE] = "volatile",
1240 [GNU_AK_CDECL] = "cdecl",
1241 [GNU_AK_STDCALL] = "stdcall",
1242 [GNU_AK_FASTCALL] = "fastcall",
1243 [GNU_AK_DEPRECATED] = "deprecated",
1244 [GNU_AK_NOINLINE] = "noinline",
1245 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1246 [GNU_AK_NORETURN] = "noreturn",
1247 [GNU_AK_NAKED] = "naked",
1248 [GNU_AK_PURE] = "pure",
1249 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1250 [GNU_AK_MALLOC] = "malloc",
1251 [GNU_AK_WEAK] = "weak",
1252 [GNU_AK_CONSTRUCTOR] = "constructor",
1253 [GNU_AK_DESTRUCTOR] = "destructor",
1254 [GNU_AK_NOTHROW] = "nothrow",
1255 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1256 [GNU_AK_COMMON] = "common",
1257 [GNU_AK_NOCOMMON] = "nocommon",
1258 [GNU_AK_PACKED] = "packed",
1259 [GNU_AK_SHARED] = "shared",
1260 [GNU_AK_NOTSHARED] = "notshared",
1261 [GNU_AK_USED] = "used",
1262 [GNU_AK_UNUSED] = "unused",
1263 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1264 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1265 [GNU_AK_LONGCALL] = "longcall",
1266 [GNU_AK_SHORTCALL] = "shortcall",
1267 [GNU_AK_LONG_CALL] = "long_call",
1268 [GNU_AK_SHORT_CALL] = "short_call",
1269 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1270 [GNU_AK_INTERRUPT] = "interrupt",
1271 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1272 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1273 [GNU_AK_NESTING] = "nesting",
1274 [GNU_AK_NEAR] = "near",
1275 [GNU_AK_FAR] = "far",
1276 [GNU_AK_SIGNAL] = "signal",
1277 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1278 [GNU_AK_TINY_DATA] = "tiny_data",
1279 [GNU_AK_SAVEALL] = "saveall",
1280 [GNU_AK_FLATTEN] = "flatten",
1281 [GNU_AK_SSEREGPARM] = "sseregparm",
1282 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1283 [GNU_AK_RETURN_TWICE] = "return_twice",
1284 [GNU_AK_MAY_ALIAS] = "may_alias",
1285 [GNU_AK_MS_STRUCT] = "ms_struct",
1286 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1287 [GNU_AK_DLLIMPORT] = "dllimport",
1288 [GNU_AK_DLLEXPORT] = "dllexport",
1289 [GNU_AK_ALIGNED] = "aligned",
1290 [GNU_AK_ALIAS] = "alias",
1291 [GNU_AK_SECTION] = "section",
1292 [GNU_AK_FORMAT] = "format",
1293 [GNU_AK_FORMAT_ARG] = "format_arg",
1294 [GNU_AK_WEAKREF] = "weakref",
1295 [GNU_AK_NONNULL] = "nonnull",
1296 [GNU_AK_TLS_MODEL] = "tls_model",
1297 [GNU_AK_VISIBILITY] = "visibility",
1298 [GNU_AK_REGPARM] = "regparm",
1299 [GNU_AK_MODE] = "mode",
1300 [GNU_AK_MODEL] = "model",
1301 [GNU_AK_TRAP_EXIT] = "trap_exit",
1302 [GNU_AK_SP_SWITCH] = "sp_switch",
1303 [GNU_AK_SENTINEL] = "sentinel"
1307 * compare two string, ignoring double underscores on the second.
1309 static int strcmp_underscore(const char *s1, const char *s2)
1311 if (s2[0] == '_' && s2[1] == '_') {
1312 size_t len2 = strlen(s2);
1313 size_t len1 = strlen(s1);
1314 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1315 return strncmp(s1, s2+2, len2-4);
1319 return strcmp(s1, s2);
1323 * Allocate a new gnu temporal attribute of given kind.
1325 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1327 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1328 attribute->kind = kind;
1329 attribute->next = NULL;
1330 attribute->invalid = false;
1331 attribute->have_arguments = false;
1337 * Parse one constant expression argument of the given attribute.
1339 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1341 expression_t *expression;
1342 add_anchor_token(')');
1343 expression = parse_constant_expression();
1344 rem_anchor_token(')');
1345 expect(')', end_error);
1346 attribute->u.argument = fold_constant(expression);
1349 attribute->invalid = true;
1353 * Parse a list of constant expressions arguments of the given attribute.
1355 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1357 argument_list_t **list = &attribute->u.arguments;
1358 argument_list_t *entry;
1359 expression_t *expression;
1360 add_anchor_token(')');
1361 add_anchor_token(',');
1363 expression = parse_constant_expression();
1364 entry = obstack_alloc(&temp_obst, sizeof(entry));
1365 entry->argument = fold_constant(expression);
1368 list = &entry->next;
1369 if (token.type != ',')
1373 rem_anchor_token(',');
1374 rem_anchor_token(')');
1375 expect(')', end_error);
1378 attribute->invalid = true;
1382 * Parse one string literal argument of the given attribute.
1384 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1387 add_anchor_token('(');
1388 if (token.type != T_STRING_LITERAL) {
1389 parse_error_expected("while parsing attribute directive",
1390 T_STRING_LITERAL, NULL);
1393 *string = parse_string_literals();
1394 rem_anchor_token('(');
1395 expect(')', end_error);
1398 attribute->invalid = true;
1402 * Parse one tls model of the given attribute.
1404 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1406 static const char *const tls_models[] = {
1412 string_t string = { NULL, 0 };
1413 parse_gnu_attribute_string_arg(attribute, &string);
1414 if (string.begin != NULL) {
1415 for (size_t i = 0; i < 4; ++i) {
1416 if (strcmp(tls_models[i], string.begin) == 0) {
1417 attribute->u.value = i;
1421 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1423 attribute->invalid = true;
1427 * Parse one tls model of the given attribute.
1429 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1431 static const char *const visibilities[] = {
1437 string_t string = { NULL, 0 };
1438 parse_gnu_attribute_string_arg(attribute, &string);
1439 if (string.begin != NULL) {
1440 for (size_t i = 0; i < 4; ++i) {
1441 if (strcmp(visibilities[i], string.begin) == 0) {
1442 attribute->u.value = i;
1446 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1448 attribute->invalid = true;
1452 * Parse one (code) model of the given attribute.
1454 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1456 static const char *const visibilities[] = {
1461 string_t string = { NULL, 0 };
1462 parse_gnu_attribute_string_arg(attribute, &string);
1463 if (string.begin != NULL) {
1464 for (int i = 0; i < 3; ++i) {
1465 if (strcmp(visibilities[i], string.begin) == 0) {
1466 attribute->u.value = i;
1470 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1472 attribute->invalid = true;
1476 * Parse one mode of the given attribute.
1478 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1480 /* TODO: find out what is allowed here... */
1482 /* at least: byte, word, pointer, list of machine modes
1483 * __XXX___ is interpreted as XXX */
1484 add_anchor_token(')');
1486 if (token.type != T_IDENTIFIER) {
1487 expect(T_IDENTIFIER, end_error);
1490 /* This isn't really correct, the backend should provide a list of machine
1491 * specific modes (according to gcc philosophy that is...) */
1492 const char *symbol_str = token.v.symbol->string;
1493 if (strcmp_underscore("QI", symbol_str) == 0 ||
1494 strcmp_underscore("byte", symbol_str) == 0) {
1495 attribute->u.akind = ATOMIC_TYPE_CHAR;
1496 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1497 attribute->u.akind = ATOMIC_TYPE_SHORT;
1498 } else if (strcmp_underscore("SI", symbol_str) == 0
1499 || strcmp_underscore("word", symbol_str) == 0
1500 || strcmp_underscore("pointer", symbol_str) == 0) {
1501 attribute->u.akind = ATOMIC_TYPE_INT;
1502 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1503 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1506 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1507 attribute->invalid = true;
1511 rem_anchor_token(')');
1512 expect(')', end_error);
1515 attribute->invalid = true;
1519 * Parse one interrupt argument of the given attribute.
1521 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1523 static const char *const interrupts[] = {
1530 string_t string = { NULL, 0 };
1531 parse_gnu_attribute_string_arg(attribute, &string);
1532 if (string.begin != NULL) {
1533 for (size_t i = 0; i < 5; ++i) {
1534 if (strcmp(interrupts[i], string.begin) == 0) {
1535 attribute->u.value = i;
1539 errorf(HERE, "'%s' is not an interrupt", string.begin);
1541 attribute->invalid = true;
1545 * Parse ( identifier, const expression, const expression )
1547 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1549 static const char *const format_names[] = {
1557 if (token.type != T_IDENTIFIER) {
1558 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1561 const char *name = token.v.symbol->string;
1562 for (i = 0; i < 4; ++i) {
1563 if (strcmp_underscore(format_names[i], name) == 0)
1567 if (warning.attribute)
1568 warningf(HERE, "'%s' is an unrecognized format function type", name);
1572 expect(',', end_error);
1573 add_anchor_token(')');
1574 add_anchor_token(',');
1575 parse_constant_expression();
1576 rem_anchor_token(',');
1577 rem_anchor_token(')');
1579 expect(',', end_error);
1580 add_anchor_token(')');
1581 parse_constant_expression();
1582 rem_anchor_token(')');
1583 expect(')', end_error);
1586 attribute->u.value = true;
1590 * Check that a given GNU attribute has no arguments.
1592 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1594 if (!attribute->have_arguments)
1597 /* should have no arguments */
1598 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1599 eat_until_matching_token('(');
1600 /* we have already consumed '(', so we stop before ')', eat it */
1602 attribute->invalid = true;
1606 * Parse one GNU attribute.
1608 * Note that attribute names can be specified WITH or WITHOUT
1609 * double underscores, ie const or __const__.
1611 * The following attributes are parsed without arguments
1636 * no_instrument_function
1637 * warn_unused_result
1654 * externally_visible
1662 * The following attributes are parsed with arguments
1663 * aligned( const expression )
1664 * alias( string literal )
1665 * section( string literal )
1666 * format( identifier, const expression, const expression )
1667 * format_arg( const expression )
1668 * tls_model( string literal )
1669 * visibility( string literal )
1670 * regparm( const expression )
1671 * model( string leteral )
1672 * trap_exit( const expression )
1673 * sp_switch( string literal )
1675 * The following attributes might have arguments
1676 * weak_ref( string literal )
1677 * non_null( const expression // ',' )
1678 * interrupt( string literal )
1679 * sentinel( constant expression )
1681 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1683 gnu_attribute_t *head = *attributes;
1684 gnu_attribute_t *last = *attributes;
1685 decl_modifiers_t modifiers = 0;
1686 gnu_attribute_t *attribute;
1688 eat(T___attribute__);
1689 expect('(', end_error);
1690 expect('(', end_error);
1692 if (token.type != ')') {
1693 /* find the end of the list */
1695 while (last->next != NULL)
1699 /* non-empty attribute list */
1702 if (token.type == T_const) {
1704 } else if (token.type == T_volatile) {
1706 } else if (token.type == T_cdecl) {
1707 /* __attribute__((cdecl)), WITH ms mode */
1709 } else if (token.type == T_IDENTIFIER) {
1710 const symbol_t *sym = token.v.symbol;
1713 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1720 for (i = 0; i < GNU_AK_LAST; ++i) {
1721 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1724 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1727 if (kind == GNU_AK_LAST) {
1728 if (warning.attribute)
1729 warningf(HERE, "'%s' attribute directive ignored", name);
1731 /* skip possible arguments */
1732 if (token.type == '(') {
1733 eat_until_matching_token(')');
1736 /* check for arguments */
1737 attribute = allocate_gnu_attribute(kind);
1738 if (token.type == '(') {
1740 if (token.type == ')') {
1741 /* empty args are allowed */
1744 attribute->have_arguments = true;
1748 case GNU_AK_VOLATILE:
1753 case GNU_AK_NOCOMMON:
1755 case GNU_AK_NOTSHARED:
1756 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1757 case GNU_AK_WARN_UNUSED_RESULT:
1758 case GNU_AK_LONGCALL:
1759 case GNU_AK_SHORTCALL:
1760 case GNU_AK_LONG_CALL:
1761 case GNU_AK_SHORT_CALL:
1762 case GNU_AK_FUNCTION_VECTOR:
1763 case GNU_AK_INTERRUPT_HANDLER:
1764 case GNU_AK_NMI_HANDLER:
1765 case GNU_AK_NESTING:
1769 case GNU_AK_EIGTHBIT_DATA:
1770 case GNU_AK_TINY_DATA:
1771 case GNU_AK_SAVEALL:
1772 case GNU_AK_FLATTEN:
1773 case GNU_AK_SSEREGPARM:
1774 case GNU_AK_EXTERNALLY_VISIBLE:
1775 case GNU_AK_RETURN_TWICE:
1776 case GNU_AK_MAY_ALIAS:
1777 case GNU_AK_MS_STRUCT:
1778 case GNU_AK_GCC_STRUCT:
1781 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1782 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1783 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1784 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1785 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1786 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1787 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1788 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1789 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1790 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1791 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1792 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1793 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1794 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1795 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1796 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1797 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1798 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1799 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1801 case GNU_AK_ALIGNED:
1802 /* __align__ may be used without an argument */
1803 if (attribute->have_arguments) {
1804 parse_gnu_attribute_const_arg(attribute);
1808 case GNU_AK_FORMAT_ARG:
1809 case GNU_AK_REGPARM:
1810 case GNU_AK_TRAP_EXIT:
1811 if (!attribute->have_arguments) {
1812 /* should have arguments */
1813 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1814 attribute->invalid = true;
1816 parse_gnu_attribute_const_arg(attribute);
1819 case GNU_AK_SECTION:
1820 case GNU_AK_SP_SWITCH:
1821 if (!attribute->have_arguments) {
1822 /* should have arguments */
1823 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1824 attribute->invalid = true;
1826 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1829 if (!attribute->have_arguments) {
1830 /* should have arguments */
1831 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1832 attribute->invalid = true;
1834 parse_gnu_attribute_format_args(attribute);
1836 case GNU_AK_WEAKREF:
1837 /* may have one string argument */
1838 if (attribute->have_arguments)
1839 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1841 case GNU_AK_NONNULL:
1842 if (attribute->have_arguments)
1843 parse_gnu_attribute_const_arg_list(attribute);
1845 case GNU_AK_TLS_MODEL:
1846 if (!attribute->have_arguments) {
1847 /* should have arguments */
1848 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1850 parse_gnu_attribute_tls_model_arg(attribute);
1852 case GNU_AK_VISIBILITY:
1853 if (!attribute->have_arguments) {
1854 /* should have arguments */
1855 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1857 parse_gnu_attribute_visibility_arg(attribute);
1860 if (!attribute->have_arguments) {
1861 /* should have arguments */
1862 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1864 parse_gnu_attribute_model_arg(attribute);
1868 if (!attribute->have_arguments) {
1869 /* should have arguments */
1870 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1872 parse_gnu_attribute_mode_arg(attribute);
1875 case GNU_AK_INTERRUPT:
1876 /* may have one string argument */
1877 if (attribute->have_arguments)
1878 parse_gnu_attribute_interrupt_arg(attribute);
1880 case GNU_AK_SENTINEL:
1881 /* may have one string argument */
1882 if (attribute->have_arguments)
1883 parse_gnu_attribute_const_arg(attribute);
1886 /* already handled */
1890 check_no_argument(attribute, name);
1893 if (attribute != NULL) {
1895 last->next = attribute;
1898 head = last = attribute;
1902 if (token.type != ',')
1907 expect(')', end_error);
1908 expect(')', end_error);
1916 * Parse GNU attributes.
1918 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1920 decl_modifiers_t modifiers = 0;
1923 switch (token.type) {
1924 case T___attribute__:
1925 modifiers |= parse_gnu_attribute(attributes);
1930 expect('(', end_error);
1931 if (token.type != T_STRING_LITERAL) {
1932 parse_error_expected("while parsing assembler attribute",
1933 T_STRING_LITERAL, NULL);
1934 eat_until_matching_token('(');
1937 parse_string_literals();
1939 expect(')', end_error);
1942 case T_cdecl: modifiers |= DM_CDECL; break;
1943 case T__fastcall: modifiers |= DM_FASTCALL; break;
1944 case T__stdcall: modifiers |= DM_STDCALL; break;
1947 /* TODO record modifier */
1949 warningf(HERE, "Ignoring declaration modifier %K", &token);
1953 default: return modifiers;
1960 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1962 static entity_t *determine_lhs_ent(expression_t *const expr,
1965 switch (expr->kind) {
1966 case EXPR_REFERENCE: {
1967 entity_t *const entity = expr->reference.entity;
1968 /* we should only find variables as lvalues... */
1969 if (entity->base.kind != ENTITY_VARIABLE
1970 && entity->base.kind != ENTITY_PARAMETER)
1976 case EXPR_ARRAY_ACCESS: {
1977 expression_t *const ref = expr->array_access.array_ref;
1978 entity_t * ent = NULL;
1979 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1980 ent = determine_lhs_ent(ref, lhs_ent);
1983 mark_vars_read(expr->select.compound, lhs_ent);
1985 mark_vars_read(expr->array_access.index, lhs_ent);
1990 if (is_type_compound(skip_typeref(expr->base.type))) {
1991 return determine_lhs_ent(expr->select.compound, lhs_ent);
1993 mark_vars_read(expr->select.compound, lhs_ent);
1998 case EXPR_UNARY_DEREFERENCE: {
1999 expression_t *const val = expr->unary.value;
2000 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
2002 return determine_lhs_ent(val->unary.value, lhs_ent);
2004 mark_vars_read(val, NULL);
2010 mark_vars_read(expr, NULL);
2015 #define ENT_ANY ((entity_t*)-1)
2018 * Mark declarations, which are read. This is used to detect variables, which
2022 * x is not marked as "read", because it is only read to calculate its own new
2026 * x and y are not detected as "not read", because multiple variables are
2029 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2031 switch (expr->kind) {
2032 case EXPR_REFERENCE: {
2033 entity_t *const entity = expr->reference.entity;
2034 if (entity->kind != ENTITY_VARIABLE
2035 && entity->kind != ENTITY_PARAMETER)
2038 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2039 if (entity->kind == ENTITY_VARIABLE) {
2040 entity->variable.read = true;
2042 entity->parameter.read = true;
2049 // TODO respect pure/const
2050 mark_vars_read(expr->call.function, NULL);
2051 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2052 mark_vars_read(arg->expression, NULL);
2056 case EXPR_CONDITIONAL:
2057 // TODO lhs_decl should depend on whether true/false have an effect
2058 mark_vars_read(expr->conditional.condition, NULL);
2059 if (expr->conditional.true_expression != NULL)
2060 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2061 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2065 if (lhs_ent == ENT_ANY
2066 && !is_type_compound(skip_typeref(expr->base.type)))
2068 mark_vars_read(expr->select.compound, lhs_ent);
2071 case EXPR_ARRAY_ACCESS: {
2072 expression_t *const ref = expr->array_access.array_ref;
2073 mark_vars_read(ref, lhs_ent);
2074 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2075 mark_vars_read(expr->array_access.index, lhs_ent);
2080 mark_vars_read(expr->va_arge.ap, lhs_ent);
2083 case EXPR_UNARY_CAST:
2084 /* Special case: Use void cast to mark a variable as "read" */
2085 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2090 case EXPR_UNARY_THROW:
2091 if (expr->unary.value == NULL)
2094 case EXPR_UNARY_DEREFERENCE:
2095 case EXPR_UNARY_DELETE:
2096 case EXPR_UNARY_DELETE_ARRAY:
2097 if (lhs_ent == ENT_ANY)
2101 case EXPR_UNARY_NEGATE:
2102 case EXPR_UNARY_PLUS:
2103 case EXPR_UNARY_BITWISE_NEGATE:
2104 case EXPR_UNARY_NOT:
2105 case EXPR_UNARY_TAKE_ADDRESS:
2106 case EXPR_UNARY_POSTFIX_INCREMENT:
2107 case EXPR_UNARY_POSTFIX_DECREMENT:
2108 case EXPR_UNARY_PREFIX_INCREMENT:
2109 case EXPR_UNARY_PREFIX_DECREMENT:
2110 case EXPR_UNARY_CAST_IMPLICIT:
2111 case EXPR_UNARY_ASSUME:
2113 mark_vars_read(expr->unary.value, lhs_ent);
2116 case EXPR_BINARY_ADD:
2117 case EXPR_BINARY_SUB:
2118 case EXPR_BINARY_MUL:
2119 case EXPR_BINARY_DIV:
2120 case EXPR_BINARY_MOD:
2121 case EXPR_BINARY_EQUAL:
2122 case EXPR_BINARY_NOTEQUAL:
2123 case EXPR_BINARY_LESS:
2124 case EXPR_BINARY_LESSEQUAL:
2125 case EXPR_BINARY_GREATER:
2126 case EXPR_BINARY_GREATEREQUAL:
2127 case EXPR_BINARY_BITWISE_AND:
2128 case EXPR_BINARY_BITWISE_OR:
2129 case EXPR_BINARY_BITWISE_XOR:
2130 case EXPR_BINARY_LOGICAL_AND:
2131 case EXPR_BINARY_LOGICAL_OR:
2132 case EXPR_BINARY_SHIFTLEFT:
2133 case EXPR_BINARY_SHIFTRIGHT:
2134 case EXPR_BINARY_COMMA:
2135 case EXPR_BINARY_ISGREATER:
2136 case EXPR_BINARY_ISGREATEREQUAL:
2137 case EXPR_BINARY_ISLESS:
2138 case EXPR_BINARY_ISLESSEQUAL:
2139 case EXPR_BINARY_ISLESSGREATER:
2140 case EXPR_BINARY_ISUNORDERED:
2141 mark_vars_read(expr->binary.left, lhs_ent);
2142 mark_vars_read(expr->binary.right, lhs_ent);
2145 case EXPR_BINARY_ASSIGN:
2146 case EXPR_BINARY_MUL_ASSIGN:
2147 case EXPR_BINARY_DIV_ASSIGN:
2148 case EXPR_BINARY_MOD_ASSIGN:
2149 case EXPR_BINARY_ADD_ASSIGN:
2150 case EXPR_BINARY_SUB_ASSIGN:
2151 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2152 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2153 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2154 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2155 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2156 if (lhs_ent == ENT_ANY)
2158 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2159 mark_vars_read(expr->binary.right, lhs_ent);
2164 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2170 case EXPR_CHARACTER_CONSTANT:
2171 case EXPR_WIDE_CHARACTER_CONSTANT:
2172 case EXPR_STRING_LITERAL:
2173 case EXPR_WIDE_STRING_LITERAL:
2174 case EXPR_COMPOUND_LITERAL: // TODO init?
2176 case EXPR_CLASSIFY_TYPE:
2179 case EXPR_BUILTIN_SYMBOL:
2180 case EXPR_BUILTIN_CONSTANT_P:
2181 case EXPR_BUILTIN_PREFETCH:
2183 case EXPR_STATEMENT: // TODO
2184 case EXPR_LABEL_ADDRESS:
2185 case EXPR_REFERENCE_ENUM_VALUE:
2189 panic("unhandled expression");
2192 static designator_t *parse_designation(void)
2194 designator_t *result = NULL;
2195 designator_t *last = NULL;
2198 designator_t *designator;
2199 switch (token.type) {
2201 designator = allocate_ast_zero(sizeof(designator[0]));
2202 designator->source_position = token.source_position;
2204 add_anchor_token(']');
2205 designator->array_index = parse_constant_expression();
2206 rem_anchor_token(']');
2207 expect(']', end_error);
2210 designator = allocate_ast_zero(sizeof(designator[0]));
2211 designator->source_position = token.source_position;
2213 if (token.type != T_IDENTIFIER) {
2214 parse_error_expected("while parsing designator",
2215 T_IDENTIFIER, NULL);
2218 designator->symbol = token.v.symbol;
2222 expect('=', end_error);
2226 assert(designator != NULL);
2228 last->next = designator;
2230 result = designator;
2238 static initializer_t *initializer_from_string(array_type_t *type,
2239 const string_t *const string)
2241 /* TODO: check len vs. size of array type */
2244 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2245 initializer->string.string = *string;
2250 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2251 wide_string_t *const string)
2253 /* TODO: check len vs. size of array type */
2256 initializer_t *const initializer =
2257 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2258 initializer->wide_string.string = *string;
2264 * Build an initializer from a given expression.
2266 static initializer_t *initializer_from_expression(type_t *orig_type,
2267 expression_t *expression)
2269 /* TODO check that expression is a constant expression */
2271 /* § 6.7.8.14/15 char array may be initialized by string literals */
2272 type_t *type = skip_typeref(orig_type);
2273 type_t *expr_type_orig = expression->base.type;
2274 type_t *expr_type = skip_typeref(expr_type_orig);
2275 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2276 array_type_t *const array_type = &type->array;
2277 type_t *const element_type = skip_typeref(array_type->element_type);
2279 if (element_type->kind == TYPE_ATOMIC) {
2280 atomic_type_kind_t akind = element_type->atomic.akind;
2281 switch (expression->kind) {
2282 case EXPR_STRING_LITERAL:
2283 if (akind == ATOMIC_TYPE_CHAR
2284 || akind == ATOMIC_TYPE_SCHAR
2285 || akind == ATOMIC_TYPE_UCHAR) {
2286 return initializer_from_string(array_type,
2287 &expression->string.value);
2290 case EXPR_WIDE_STRING_LITERAL: {
2291 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2292 if (get_unqualified_type(element_type) == bare_wchar_type) {
2293 return initializer_from_wide_string(array_type,
2294 &expression->wide_string.value);
2304 assign_error_t error = semantic_assign(type, expression);
2305 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2307 report_assign_error(error, type, expression, "initializer",
2308 &expression->base.source_position);
2310 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2312 if (type->kind == TYPE_BITFIELD) {
2313 type = type->bitfield.base_type;
2316 result->value.value = create_implicit_cast(expression, type);
2322 * Checks if a given expression can be used as an constant initializer.
2324 static bool is_initializer_constant(const expression_t *expression)
2326 return is_constant_expression(expression)
2327 || is_address_constant(expression);
2331 * Parses an scalar initializer.
2333 * § 6.7.8.11; eat {} without warning
2335 static initializer_t *parse_scalar_initializer(type_t *type,
2336 bool must_be_constant)
2338 /* there might be extra {} hierarchies */
2340 if (token.type == '{') {
2342 warningf(HERE, "extra curly braces around scalar initializer");
2346 } while (token.type == '{');
2349 expression_t *expression = parse_assignment_expression();
2350 mark_vars_read(expression, NULL);
2351 if (must_be_constant && !is_initializer_constant(expression)) {
2352 errorf(&expression->base.source_position,
2353 "Initialisation expression '%E' is not constant",
2357 initializer_t *initializer = initializer_from_expression(type, expression);
2359 if (initializer == NULL) {
2360 errorf(&expression->base.source_position,
2361 "expression '%E' (type '%T') doesn't match expected type '%T'",
2362 expression, expression->base.type, type);
2367 bool additional_warning_displayed = false;
2368 while (braces > 0) {
2369 if (token.type == ',') {
2372 if (token.type != '}') {
2373 if (!additional_warning_displayed && warning.other) {
2374 warningf(HERE, "additional elements in scalar initializer");
2375 additional_warning_displayed = true;
2386 * An entry in the type path.
2388 typedef struct type_path_entry_t type_path_entry_t;
2389 struct type_path_entry_t {
2390 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2392 size_t index; /**< For array types: the current index. */
2393 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2398 * A type path expression a position inside compound or array types.
2400 typedef struct type_path_t type_path_t;
2401 struct type_path_t {
2402 type_path_entry_t *path; /**< An flexible array containing the current path. */
2403 type_t *top_type; /**< type of the element the path points */
2404 size_t max_index; /**< largest index in outermost array */
2408 * Prints a type path for debugging.
2410 static __attribute__((unused)) void debug_print_type_path(
2411 const type_path_t *path)
2413 size_t len = ARR_LEN(path->path);
2415 for (size_t i = 0; i < len; ++i) {
2416 const type_path_entry_t *entry = & path->path[i];
2418 type_t *type = skip_typeref(entry->type);
2419 if (is_type_compound(type)) {
2420 /* in gcc mode structs can have no members */
2421 if (entry->v.compound_entry == NULL) {
2425 fprintf(stderr, ".%s",
2426 entry->v.compound_entry->base.symbol->string);
2427 } else if (is_type_array(type)) {
2428 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2430 fprintf(stderr, "-INVALID-");
2433 if (path->top_type != NULL) {
2434 fprintf(stderr, " (");
2435 print_type(path->top_type);
2436 fprintf(stderr, ")");
2441 * Return the top type path entry, ie. in a path
2442 * (type).a.b returns the b.
2444 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2446 size_t len = ARR_LEN(path->path);
2448 return &path->path[len-1];
2452 * Enlarge the type path by an (empty) element.
2454 static type_path_entry_t *append_to_type_path(type_path_t *path)
2456 size_t len = ARR_LEN(path->path);
2457 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2459 type_path_entry_t *result = & path->path[len];
2460 memset(result, 0, sizeof(result[0]));
2465 * Descending into a sub-type. Enter the scope of the current top_type.
2467 static void descend_into_subtype(type_path_t *path)
2469 type_t *orig_top_type = path->top_type;
2470 type_t *top_type = skip_typeref(orig_top_type);
2472 type_path_entry_t *top = append_to_type_path(path);
2473 top->type = top_type;
2475 if (is_type_compound(top_type)) {
2476 compound_t *compound = top_type->compound.compound;
2477 entity_t *entry = compound->members.entities;
2479 if (entry != NULL) {
2480 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2481 top->v.compound_entry = &entry->declaration;
2482 path->top_type = entry->declaration.type;
2484 path->top_type = NULL;
2486 } else if (is_type_array(top_type)) {
2488 path->top_type = top_type->array.element_type;
2490 assert(!is_type_valid(top_type));
2495 * Pop an entry from the given type path, ie. returning from
2496 * (type).a.b to (type).a
2498 static void ascend_from_subtype(type_path_t *path)
2500 type_path_entry_t *top = get_type_path_top(path);
2502 path->top_type = top->type;
2504 size_t len = ARR_LEN(path->path);
2505 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2509 * Pop entries from the given type path until the given
2510 * path level is reached.
2512 static void ascend_to(type_path_t *path, size_t top_path_level)
2514 size_t len = ARR_LEN(path->path);
2516 while (len > top_path_level) {
2517 ascend_from_subtype(path);
2518 len = ARR_LEN(path->path);
2522 static bool walk_designator(type_path_t *path, const designator_t *designator,
2523 bool used_in_offsetof)
2525 for (; designator != NULL; designator = designator->next) {
2526 type_path_entry_t *top = get_type_path_top(path);
2527 type_t *orig_type = top->type;
2529 type_t *type = skip_typeref(orig_type);
2531 if (designator->symbol != NULL) {
2532 symbol_t *symbol = designator->symbol;
2533 if (!is_type_compound(type)) {
2534 if (is_type_valid(type)) {
2535 errorf(&designator->source_position,
2536 "'.%Y' designator used for non-compound type '%T'",
2540 top->type = type_error_type;
2541 top->v.compound_entry = NULL;
2542 orig_type = type_error_type;
2544 compound_t *compound = type->compound.compound;
2545 entity_t *iter = compound->members.entities;
2546 for (; iter != NULL; iter = iter->base.next) {
2547 if (iter->base.symbol == symbol) {
2552 errorf(&designator->source_position,
2553 "'%T' has no member named '%Y'", orig_type, symbol);
2556 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2557 if (used_in_offsetof) {
2558 type_t *real_type = skip_typeref(iter->declaration.type);
2559 if (real_type->kind == TYPE_BITFIELD) {
2560 errorf(&designator->source_position,
2561 "offsetof designator '%Y' may not specify bitfield",
2567 top->type = orig_type;
2568 top->v.compound_entry = &iter->declaration;
2569 orig_type = iter->declaration.type;
2572 expression_t *array_index = designator->array_index;
2573 assert(designator->array_index != NULL);
2575 if (!is_type_array(type)) {
2576 if (is_type_valid(type)) {
2577 errorf(&designator->source_position,
2578 "[%E] designator used for non-array type '%T'",
2579 array_index, orig_type);
2584 long index = fold_constant(array_index);
2585 if (!used_in_offsetof) {
2587 errorf(&designator->source_position,
2588 "array index [%E] must be positive", array_index);
2589 } else if (type->array.size_constant) {
2590 long array_size = type->array.size;
2591 if (index >= array_size) {
2592 errorf(&designator->source_position,
2593 "designator [%E] (%d) exceeds array size %d",
2594 array_index, index, array_size);
2599 top->type = orig_type;
2600 top->v.index = (size_t) index;
2601 orig_type = type->array.element_type;
2603 path->top_type = orig_type;
2605 if (designator->next != NULL) {
2606 descend_into_subtype(path);
2615 static void advance_current_object(type_path_t *path, size_t top_path_level)
2617 type_path_entry_t *top = get_type_path_top(path);
2619 type_t *type = skip_typeref(top->type);
2620 if (is_type_union(type)) {
2621 /* in unions only the first element is initialized */
2622 top->v.compound_entry = NULL;
2623 } else if (is_type_struct(type)) {
2624 declaration_t *entry = top->v.compound_entry;
2626 entity_t *next_entity = entry->base.next;
2627 if (next_entity != NULL) {
2628 assert(is_declaration(next_entity));
2629 entry = &next_entity->declaration;
2634 top->v.compound_entry = entry;
2635 if (entry != NULL) {
2636 path->top_type = entry->type;
2639 } else if (is_type_array(type)) {
2640 assert(is_type_array(type));
2644 if (!type->array.size_constant || top->v.index < type->array.size) {
2648 assert(!is_type_valid(type));
2652 /* we're past the last member of the current sub-aggregate, try if we
2653 * can ascend in the type hierarchy and continue with another subobject */
2654 size_t len = ARR_LEN(path->path);
2656 if (len > top_path_level) {
2657 ascend_from_subtype(path);
2658 advance_current_object(path, top_path_level);
2660 path->top_type = NULL;
2665 * skip until token is found.
2667 static void skip_until(int type)
2669 while (token.type != type) {
2670 if (token.type == T_EOF)
2677 * skip any {...} blocks until a closing bracket is reached.
2679 static void skip_initializers(void)
2681 if (token.type == '{')
2684 while (token.type != '}') {
2685 if (token.type == T_EOF)
2687 if (token.type == '{') {
2695 static initializer_t *create_empty_initializer(void)
2697 static initializer_t empty_initializer
2698 = { .list = { { INITIALIZER_LIST }, 0 } };
2699 return &empty_initializer;
2703 * Parse a part of an initialiser for a struct or union,
2705 static initializer_t *parse_sub_initializer(type_path_t *path,
2706 type_t *outer_type, size_t top_path_level,
2707 parse_initializer_env_t *env)
2709 if (token.type == '}') {
2710 /* empty initializer */
2711 return create_empty_initializer();
2714 type_t *orig_type = path->top_type;
2715 type_t *type = NULL;
2717 if (orig_type == NULL) {
2718 /* We are initializing an empty compound. */
2720 type = skip_typeref(orig_type);
2723 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2726 designator_t *designator = NULL;
2727 if (token.type == '.' || token.type == '[') {
2728 designator = parse_designation();
2729 goto finish_designator;
2730 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2731 /* GNU-style designator ("identifier: value") */
2732 designator = allocate_ast_zero(sizeof(designator[0]));
2733 designator->source_position = token.source_position;
2734 designator->symbol = token.v.symbol;
2739 /* reset path to toplevel, evaluate designator from there */
2740 ascend_to(path, top_path_level);
2741 if (!walk_designator(path, designator, false)) {
2742 /* can't continue after designation error */
2746 initializer_t *designator_initializer
2747 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2748 designator_initializer->designator.designator = designator;
2749 ARR_APP1(initializer_t*, initializers, designator_initializer);
2751 orig_type = path->top_type;
2752 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2757 if (token.type == '{') {
2758 if (type != NULL && is_type_scalar(type)) {
2759 sub = parse_scalar_initializer(type, env->must_be_constant);
2763 if (env->entity != NULL) {
2765 "extra brace group at end of initializer for '%Y'",
2766 env->entity->base.symbol);
2768 errorf(HERE, "extra brace group at end of initializer");
2771 descend_into_subtype(path);
2773 add_anchor_token('}');
2774 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2776 rem_anchor_token('}');
2779 ascend_from_subtype(path);
2780 expect('}', end_error);
2782 expect('}', end_error);
2783 goto error_parse_next;
2787 /* must be an expression */
2788 expression_t *expression = parse_assignment_expression();
2789 mark_vars_read(expression, NULL);
2791 if (env->must_be_constant && !is_initializer_constant(expression)) {
2792 errorf(&expression->base.source_position,
2793 "Initialisation expression '%E' is not constant",
2798 /* we are already outside, ... */
2799 type_t *const outer_type_skip = skip_typeref(outer_type);
2800 if (is_type_compound(outer_type_skip) &&
2801 !outer_type_skip->compound.compound->complete) {
2802 goto error_parse_next;
2807 /* handle { "string" } special case */
2808 if ((expression->kind == EXPR_STRING_LITERAL
2809 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2810 && outer_type != NULL) {
2811 sub = initializer_from_expression(outer_type, expression);
2813 if (token.type == ',') {
2816 if (token.type != '}' && warning.other) {
2817 warningf(HERE, "excessive elements in initializer for type '%T'",
2820 /* TODO: eat , ... */
2825 /* descend into subtypes until expression matches type */
2827 orig_type = path->top_type;
2828 type = skip_typeref(orig_type);
2830 sub = initializer_from_expression(orig_type, expression);
2834 if (!is_type_valid(type)) {
2837 if (is_type_scalar(type)) {
2838 errorf(&expression->base.source_position,
2839 "expression '%E' doesn't match expected type '%T'",
2840 expression, orig_type);
2844 descend_into_subtype(path);
2848 /* update largest index of top array */
2849 const type_path_entry_t *first = &path->path[0];
2850 type_t *first_type = first->type;
2851 first_type = skip_typeref(first_type);
2852 if (is_type_array(first_type)) {
2853 size_t index = first->v.index;
2854 if (index > path->max_index)
2855 path->max_index = index;
2859 /* append to initializers list */
2860 ARR_APP1(initializer_t*, initializers, sub);
2863 if (warning.other) {
2864 if (env->entity != NULL) {
2865 warningf(HERE, "excess elements in struct initializer for '%Y'",
2866 env->entity->base.symbol);
2868 warningf(HERE, "excess elements in struct initializer");
2874 if (token.type == '}') {
2877 expect(',', end_error);
2878 if (token.type == '}') {
2883 /* advance to the next declaration if we are not at the end */
2884 advance_current_object(path, top_path_level);
2885 orig_type = path->top_type;
2886 if (orig_type != NULL)
2887 type = skip_typeref(orig_type);
2893 size_t len = ARR_LEN(initializers);
2894 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2895 initializer_t *result = allocate_ast_zero(size);
2896 result->kind = INITIALIZER_LIST;
2897 result->list.len = len;
2898 memcpy(&result->list.initializers, initializers,
2899 len * sizeof(initializers[0]));
2901 DEL_ARR_F(initializers);
2902 ascend_to(path, top_path_level+1);
2907 skip_initializers();
2908 DEL_ARR_F(initializers);
2909 ascend_to(path, top_path_level+1);
2914 * Parses an initializer. Parsers either a compound literal
2915 * (env->declaration == NULL) or an initializer of a declaration.
2917 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2919 type_t *type = skip_typeref(env->type);
2920 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2921 initializer_t *result;
2923 if (is_type_scalar(type)) {
2924 result = parse_scalar_initializer(type, env->must_be_constant);
2925 } else if (token.type == '{') {
2929 memset(&path, 0, sizeof(path));
2930 path.top_type = env->type;
2931 path.path = NEW_ARR_F(type_path_entry_t, 0);
2933 descend_into_subtype(&path);
2935 add_anchor_token('}');
2936 result = parse_sub_initializer(&path, env->type, 1, env);
2937 rem_anchor_token('}');
2939 max_index = path.max_index;
2940 DEL_ARR_F(path.path);
2942 expect('}', end_error);
2944 /* parse_scalar_initializer() also works in this case: we simply
2945 * have an expression without {} around it */
2946 result = parse_scalar_initializer(type, env->must_be_constant);
2949 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2950 * the array type size */
2951 if (is_type_array(type) && type->array.size_expression == NULL
2952 && result != NULL) {
2954 switch (result->kind) {
2955 case INITIALIZER_LIST:
2956 assert(max_index != 0xdeadbeaf);
2957 size = max_index + 1;
2960 case INITIALIZER_STRING:
2961 size = result->string.string.size;
2964 case INITIALIZER_WIDE_STRING:
2965 size = result->wide_string.string.size;
2968 case INITIALIZER_DESIGNATOR:
2969 case INITIALIZER_VALUE:
2970 /* can happen for parse errors */
2975 internal_errorf(HERE, "invalid initializer type");
2978 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2979 cnst->base.type = type_size_t;
2980 cnst->conste.v.int_value = size;
2982 type_t *new_type = duplicate_type(type);
2984 new_type->array.size_expression = cnst;
2985 new_type->array.size_constant = true;
2986 new_type->array.has_implicit_size = true;
2987 new_type->array.size = size;
2988 env->type = new_type;
2996 static void append_entity(scope_t *scope, entity_t *entity)
2998 if (scope->last_entity != NULL) {
2999 scope->last_entity->base.next = entity;
3001 scope->entities = entity;
3003 scope->last_entity = entity;
3007 static compound_t *parse_compound_type_specifier(bool is_struct)
3009 gnu_attribute_t *attributes = NULL;
3010 decl_modifiers_t modifiers = 0;
3017 symbol_t *symbol = NULL;
3018 compound_t *compound = NULL;
3020 if (token.type == T___attribute__) {
3021 modifiers |= parse_attributes(&attributes);
3024 if (token.type == T_IDENTIFIER) {
3025 symbol = token.v.symbol;
3028 namespace_tag_t const namespc =
3029 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3030 entity_t *entity = get_entity(symbol, namespc);
3031 if (entity != NULL) {
3032 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3033 compound = &entity->compound;
3034 if (compound->base.parent_scope != current_scope &&
3035 (token.type == '{' || token.type == ';')) {
3036 /* we're in an inner scope and have a definition. Override
3037 existing definition in outer scope */
3039 } else if (compound->complete && token.type == '{') {
3040 assert(symbol != NULL);
3041 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3042 is_struct ? "struct" : "union", symbol,
3043 &compound->base.source_position);
3044 /* clear members in the hope to avoid further errors */
3045 compound->members.entities = NULL;
3048 } else if (token.type != '{') {
3050 parse_error_expected("while parsing struct type specifier",
3051 T_IDENTIFIER, '{', NULL);
3053 parse_error_expected("while parsing union type specifier",
3054 T_IDENTIFIER, '{', NULL);
3060 if (compound == NULL) {
3061 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3062 entity_t *entity = allocate_entity_zero(kind);
3063 compound = &entity->compound;
3065 compound->base.namespc =
3066 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3067 compound->base.source_position = token.source_position;
3068 compound->base.symbol = symbol;
3069 compound->base.parent_scope = current_scope;
3070 if (symbol != NULL) {
3071 environment_push(entity);
3073 append_entity(current_scope, entity);
3076 if (token.type == '{') {
3077 parse_compound_type_entries(compound);
3078 modifiers |= parse_attributes(&attributes);
3080 if (symbol == NULL) {
3081 assert(anonymous_entity == NULL);
3082 anonymous_entity = (entity_t*)compound;
3086 compound->modifiers |= modifiers;
3090 static void parse_enum_entries(type_t *const enum_type)
3094 if (token.type == '}') {
3095 errorf(HERE, "empty enum not allowed");
3100 add_anchor_token('}');
3102 if (token.type != T_IDENTIFIER) {
3103 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3105 rem_anchor_token('}');
3109 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3110 entity->enum_value.enum_type = enum_type;
3111 entity->base.symbol = token.v.symbol;
3112 entity->base.source_position = token.source_position;
3115 if (token.type == '=') {
3117 expression_t *value = parse_constant_expression();
3119 value = create_implicit_cast(value, enum_type);
3120 entity->enum_value.value = value;
3125 record_entity(entity, false);
3127 if (token.type != ',')
3130 } while (token.type != '}');
3131 rem_anchor_token('}');
3133 expect('}', end_error);
3139 static type_t *parse_enum_specifier(void)
3141 gnu_attribute_t *attributes = NULL;
3146 if (token.type == T_IDENTIFIER) {
3147 symbol = token.v.symbol;
3150 entity = get_entity(symbol, NAMESPACE_ENUM);
3151 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3152 } else if (token.type != '{') {
3153 parse_error_expected("while parsing enum type specifier",
3154 T_IDENTIFIER, '{', NULL);
3161 if (entity == NULL) {
3162 entity = allocate_entity_zero(ENTITY_ENUM);
3163 entity->base.namespc = NAMESPACE_ENUM;
3164 entity->base.source_position = token.source_position;
3165 entity->base.symbol = symbol;
3166 entity->base.parent_scope = current_scope;
3169 type_t *const type = allocate_type_zero(TYPE_ENUM);
3170 type->enumt.enume = &entity->enume;
3172 if (token.type == '{') {
3173 if (entity->enume.complete) {
3174 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3175 symbol, &entity->base.source_position);
3177 if (symbol != NULL) {
3178 environment_push(entity);
3180 append_entity(current_scope, entity);
3181 entity->enume.complete = true;
3183 parse_enum_entries(type);
3184 parse_attributes(&attributes);
3186 if (symbol == NULL) {
3187 assert(anonymous_entity == NULL);
3188 anonymous_entity = entity;
3190 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3191 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3199 * if a symbol is a typedef to another type, return true
3201 static bool is_typedef_symbol(symbol_t *symbol)
3203 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3204 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3207 static type_t *parse_typeof(void)
3213 expect('(', end_error);
3214 add_anchor_token(')');
3216 expression_t *expression = NULL;
3218 bool old_type_prop = in_type_prop;
3219 bool old_gcc_extension = in_gcc_extension;
3220 in_type_prop = true;
3222 while (token.type == T___extension__) {
3223 /* This can be a prefix to a typename or an expression. */
3225 in_gcc_extension = true;
3227 switch (token.type) {
3229 if (is_typedef_symbol(token.v.symbol)) {
3230 type = parse_typename();
3232 expression = parse_expression();
3233 type = expression->base.type;
3238 type = parse_typename();
3242 expression = parse_expression();
3243 type = expression->base.type;
3246 in_type_prop = old_type_prop;
3247 in_gcc_extension = old_gcc_extension;
3249 rem_anchor_token(')');
3250 expect(')', end_error);
3252 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3253 typeof_type->typeoft.expression = expression;
3254 typeof_type->typeoft.typeof_type = type;
3261 typedef enum specifiers_t {
3262 SPECIFIER_SIGNED = 1 << 0,
3263 SPECIFIER_UNSIGNED = 1 << 1,
3264 SPECIFIER_LONG = 1 << 2,
3265 SPECIFIER_INT = 1 << 3,
3266 SPECIFIER_DOUBLE = 1 << 4,
3267 SPECIFIER_CHAR = 1 << 5,
3268 SPECIFIER_WCHAR_T = 1 << 6,
3269 SPECIFIER_SHORT = 1 << 7,
3270 SPECIFIER_LONG_LONG = 1 << 8,
3271 SPECIFIER_FLOAT = 1 << 9,
3272 SPECIFIER_BOOL = 1 << 10,
3273 SPECIFIER_VOID = 1 << 11,
3274 SPECIFIER_INT8 = 1 << 12,
3275 SPECIFIER_INT16 = 1 << 13,
3276 SPECIFIER_INT32 = 1 << 14,
3277 SPECIFIER_INT64 = 1 << 15,
3278 SPECIFIER_INT128 = 1 << 16,
3279 SPECIFIER_COMPLEX = 1 << 17,
3280 SPECIFIER_IMAGINARY = 1 << 18,
3283 static type_t *create_builtin_type(symbol_t *const symbol,
3284 type_t *const real_type)
3286 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3287 type->builtin.symbol = symbol;
3288 type->builtin.real_type = real_type;
3290 type_t *result = typehash_insert(type);
3291 if (type != result) {
3298 static type_t *get_typedef_type(symbol_t *symbol)
3300 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3301 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3304 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3305 type->typedeft.typedefe = &entity->typedefe;
3311 * check for the allowed MS alignment values.
3313 static bool check_alignment_value(long long intvalue)
3315 if (intvalue < 1 || intvalue > 8192) {
3316 errorf(HERE, "illegal alignment value");
3319 unsigned v = (unsigned)intvalue;
3320 for (unsigned i = 1; i <= 8192; i += i) {
3324 errorf(HERE, "alignment must be power of two");
3328 #define DET_MOD(name, tag) do { \
3329 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3330 *modifiers |= tag; \
3333 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3335 decl_modifiers_t *modifiers = &specifiers->modifiers;
3338 if (token.type == T_restrict) {
3340 DET_MOD(restrict, DM_RESTRICT);
3342 } else if (token.type != T_IDENTIFIER)
3344 symbol_t *symbol = token.v.symbol;
3345 if (symbol == sym_align) {
3347 expect('(', end_error);
3348 if (token.type != T_INTEGER)
3350 if (check_alignment_value(token.v.intvalue)) {
3351 if (specifiers->alignment != 0 && warning.other)
3352 warningf(HERE, "align used more than once");
3353 specifiers->alignment = (unsigned char)token.v.intvalue;
3356 expect(')', end_error);
3357 } else if (symbol == sym_allocate) {
3359 expect('(', end_error);
3360 if (token.type != T_IDENTIFIER)
3362 (void)token.v.symbol;
3363 expect(')', end_error);
3364 } else if (symbol == sym_dllimport) {
3366 DET_MOD(dllimport, DM_DLLIMPORT);
3367 } else if (symbol == sym_dllexport) {
3369 DET_MOD(dllexport, DM_DLLEXPORT);
3370 } else if (symbol == sym_thread) {
3372 DET_MOD(thread, DM_THREAD);
3373 } else if (symbol == sym_naked) {
3375 DET_MOD(naked, DM_NAKED);
3376 } else if (symbol == sym_noinline) {
3378 DET_MOD(noinline, DM_NOINLINE);
3379 } else if (symbol == sym_returns_twice) {
3381 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3382 } else if (symbol == sym_noreturn) {
3384 DET_MOD(noreturn, DM_NORETURN);
3385 } else if (symbol == sym_nothrow) {
3387 DET_MOD(nothrow, DM_NOTHROW);
3388 } else if (symbol == sym_novtable) {
3390 DET_MOD(novtable, DM_NOVTABLE);
3391 } else if (symbol == sym_property) {
3393 expect('(', end_error);
3395 bool is_get = false;
3396 if (token.type != T_IDENTIFIER)
3398 if (token.v.symbol == sym_get) {
3400 } else if (token.v.symbol == sym_put) {
3402 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3406 expect('=', end_error);
3407 if (token.type != T_IDENTIFIER)
3410 if (specifiers->get_property_sym != NULL) {
3411 errorf(HERE, "get property name already specified");
3413 specifiers->get_property_sym = token.v.symbol;
3416 if (specifiers->put_property_sym != NULL) {
3417 errorf(HERE, "put property name already specified");
3419 specifiers->put_property_sym = token.v.symbol;
3423 if (token.type == ',') {
3429 expect(')', end_error);
3430 } else if (symbol == sym_selectany) {
3432 DET_MOD(selectany, DM_SELECTANY);
3433 } else if (symbol == sym_uuid) {
3435 expect('(', end_error);
3436 if (token.type != T_STRING_LITERAL)
3439 expect(')', end_error);
3440 } else if (symbol == sym_deprecated) {
3442 if (specifiers->deprecated != 0 && warning.other)
3443 warningf(HERE, "deprecated used more than once");
3444 specifiers->deprecated = true;
3445 if (token.type == '(') {
3447 if (token.type == T_STRING_LITERAL) {
3448 specifiers->deprecated_string = token.v.string.begin;
3451 errorf(HERE, "string literal expected");
3453 expect(')', end_error);
3455 } else if (symbol == sym_noalias) {
3457 DET_MOD(noalias, DM_NOALIAS);
3460 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3462 if (token.type == '(')
3466 if (token.type == ',')
3473 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3475 entity_t *entity = allocate_entity_zero(kind);
3476 entity->base.source_position = *HERE;
3477 entity->base.symbol = symbol;
3478 if (is_declaration(entity)) {
3479 entity->declaration.type = type_error_type;
3480 entity->declaration.implicit = true;
3481 } else if (kind == ENTITY_TYPEDEF) {
3482 entity->typedefe.type = type_error_type;
3483 entity->typedefe.builtin = true;
3485 record_entity(entity, false);
3489 static void parse_microsoft_based(based_spec_t *based_spec)
3491 if (token.type != T_IDENTIFIER) {
3492 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3495 symbol_t *symbol = token.v.symbol;
3496 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3498 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3499 errorf(HERE, "'%Y' is not a variable name.", symbol);
3500 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3502 variable_t *variable = &entity->variable;
3504 if (based_spec->base_variable != NULL) {
3505 errorf(HERE, "__based type qualifier specified more than once");
3507 based_spec->source_position = token.source_position;
3508 based_spec->base_variable = variable;
3510 type_t *const type = variable->base.type;
3512 if (is_type_valid(type)) {
3513 if (! is_type_pointer(skip_typeref(type))) {
3514 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3516 if (variable->base.base.parent_scope != file_scope) {
3517 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3525 * Finish the construction of a struct type by calculating
3526 * its size, offsets, alignment.
3528 static void finish_struct_type(compound_type_t *type)
3530 assert(type->compound != NULL);
3532 compound_t *compound = type->compound;
3533 if (!compound->complete)
3538 il_alignment_t alignment = 1;
3539 bool need_pad = false;
3541 entity_t *entry = compound->members.entities;
3542 for (; entry != NULL; entry = entry->base.next) {
3543 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3546 type_t *m_type = skip_typeref(entry->declaration.type);
3547 if (! is_type_valid(m_type)) {
3548 /* simply ignore errors here */
3551 il_alignment_t m_alignment = m_type->base.alignment;
3552 if (m_alignment > alignment)
3553 alignment = m_alignment;
3555 offset = (size + m_alignment - 1) & -m_alignment;
3559 entry->compound_member.offset = offset;
3560 size = offset + m_type->base.size;
3562 if (type->base.alignment != 0) {
3563 alignment = type->base.alignment;
3566 offset = (size + alignment - 1) & -alignment;
3571 if (warning.padded) {
3572 warningf(&compound->base.source_position, "'%T' needs padding", type);
3575 if (compound->modifiers & DM_PACKED && warning.packed) {
3576 warningf(&compound->base.source_position,
3577 "superfluous packed attribute on '%T'", type);
3581 type->base.size = offset;
3582 type->base.alignment = alignment;
3586 * Finish the construction of an union type by calculating
3587 * its size and alignment.
3589 static void finish_union_type(compound_type_t *type)
3591 assert(type->compound != NULL);
3593 compound_t *compound = type->compound;
3594 if (! compound->complete)
3598 il_alignment_t alignment = 1;
3600 entity_t *entry = compound->members.entities;
3601 for (; entry != NULL; entry = entry->base.next) {
3602 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3605 type_t *m_type = skip_typeref(entry->declaration.type);
3606 if (! is_type_valid(m_type))
3609 entry->compound_member.offset = 0;
3610 if (m_type->base.size > size)
3611 size = m_type->base.size;
3612 if (m_type->base.alignment > alignment)
3613 alignment = m_type->base.alignment;
3615 if (type->base.alignment != 0) {
3616 alignment = type->base.alignment;
3618 size = (size + alignment - 1) & -alignment;
3619 type->base.size = size;
3620 type->base.alignment = alignment;
3623 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3625 type_t *type = NULL;
3626 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3627 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3628 unsigned type_specifiers = 0;
3629 bool newtype = false;
3630 bool saw_error = false;
3631 bool old_gcc_extension = in_gcc_extension;
3633 specifiers->source_position = token.source_position;
3636 specifiers->modifiers
3637 |= parse_attributes(&specifiers->gnu_attributes);
3638 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3639 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3641 switch (token.type) {
3643 #define MATCH_STORAGE_CLASS(token, class) \
3645 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3646 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3648 specifiers->storage_class = class; \
3649 if (specifiers->thread_local) \
3650 goto check_thread_storage_class; \
3654 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3655 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3656 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3657 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3658 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3662 expect('(', end_error);
3663 add_anchor_token(')');
3664 parse_microsoft_extended_decl_modifier(specifiers);
3665 rem_anchor_token(')');
3666 expect(')', end_error);
3670 if (specifiers->thread_local) {
3671 errorf(HERE, "duplicate '__thread'");
3673 specifiers->thread_local = true;
3674 check_thread_storage_class:
3675 switch (specifiers->storage_class) {
3676 case STORAGE_CLASS_EXTERN:
3677 case STORAGE_CLASS_NONE:
3678 case STORAGE_CLASS_STATIC:
3682 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3683 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3684 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3685 wrong_thread_stoarge_class:
3686 errorf(HERE, "'__thread' used with '%s'", wrong);
3693 /* type qualifiers */
3694 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3696 qualifiers |= qualifier; \
3700 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3701 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3702 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3703 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3704 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3705 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3706 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3707 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3709 case T___extension__:
3711 in_gcc_extension = true;
3714 /* type specifiers */
3715 #define MATCH_SPECIFIER(token, specifier, name) \
3717 if (type_specifiers & specifier) { \
3718 errorf(HERE, "multiple " name " type specifiers given"); \
3720 type_specifiers |= specifier; \
3725 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3726 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3727 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3728 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3729 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3730 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3731 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3732 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3733 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3734 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3735 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3736 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3737 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3738 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3739 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3740 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3741 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3742 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3744 case T__forceinline:
3745 /* only in microsoft mode */
3746 specifiers->modifiers |= DM_FORCEINLINE;
3751 specifiers->is_inline = true;
3755 if (type_specifiers & SPECIFIER_LONG_LONG) {
3756 errorf(HERE, "multiple type specifiers given");
3757 } else if (type_specifiers & SPECIFIER_LONG) {
3758 type_specifiers |= SPECIFIER_LONG_LONG;
3760 type_specifiers |= SPECIFIER_LONG;
3766 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3768 type->compound.compound = parse_compound_type_specifier(true);
3769 finish_struct_type(&type->compound);
3773 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3774 type->compound.compound = parse_compound_type_specifier(false);
3775 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3776 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3777 finish_union_type(&type->compound);
3781 type = parse_enum_specifier();
3784 type = parse_typeof();
3786 case T___builtin_va_list:
3787 type = duplicate_type(type_valist);
3791 case T_IDENTIFIER: {
3792 /* only parse identifier if we haven't found a type yet */
3793 if (type != NULL || type_specifiers != 0) {
3794 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3795 * declaration, so it doesn't generate errors about expecting '(' or
3797 switch (look_ahead(1)->type) {
3804 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3808 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3813 goto finish_specifiers;
3817 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3818 if (typedef_type == NULL) {
3819 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3820 * declaration, so it doesn't generate 'implicit int' followed by more
3821 * errors later on. */
3822 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3828 errorf(HERE, "%K does not name a type", &token);
3831 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3833 type = allocate_type_zero(TYPE_TYPEDEF);
3834 type->typedeft.typedefe = &entity->typedefe;
3838 if (la1_type == '&' || la1_type == '*')
3839 goto finish_specifiers;
3844 goto finish_specifiers;
3849 type = typedef_type;
3853 /* function specifier */
3855 goto finish_specifiers;
3860 in_gcc_extension = old_gcc_extension;
3862 if (type == NULL || (saw_error && type_specifiers != 0)) {
3863 atomic_type_kind_t atomic_type;
3865 /* match valid basic types */
3866 switch (type_specifiers) {
3867 case SPECIFIER_VOID:
3868 atomic_type = ATOMIC_TYPE_VOID;
3870 case SPECIFIER_WCHAR_T:
3871 atomic_type = ATOMIC_TYPE_WCHAR_T;
3873 case SPECIFIER_CHAR:
3874 atomic_type = ATOMIC_TYPE_CHAR;
3876 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3877 atomic_type = ATOMIC_TYPE_SCHAR;
3879 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3880 atomic_type = ATOMIC_TYPE_UCHAR;
3882 case SPECIFIER_SHORT:
3883 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3884 case SPECIFIER_SHORT | SPECIFIER_INT:
3885 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3886 atomic_type = ATOMIC_TYPE_SHORT;
3888 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3889 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3890 atomic_type = ATOMIC_TYPE_USHORT;
3893 case SPECIFIER_SIGNED:
3894 case SPECIFIER_SIGNED | SPECIFIER_INT:
3895 atomic_type = ATOMIC_TYPE_INT;
3897 case SPECIFIER_UNSIGNED:
3898 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3899 atomic_type = ATOMIC_TYPE_UINT;
3901 case SPECIFIER_LONG:
3902 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3903 case SPECIFIER_LONG | SPECIFIER_INT:
3904 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3905 atomic_type = ATOMIC_TYPE_LONG;
3907 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3908 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3909 atomic_type = ATOMIC_TYPE_ULONG;
3912 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3913 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3914 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3915 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3917 atomic_type = ATOMIC_TYPE_LONGLONG;
3918 goto warn_about_long_long;
3920 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3921 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3923 atomic_type = ATOMIC_TYPE_ULONGLONG;
3924 warn_about_long_long:
3925 if (warning.long_long) {
3926 warningf(&specifiers->source_position,
3927 "ISO C90 does not support 'long long'");
3931 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3932 atomic_type = unsigned_int8_type_kind;
3935 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3936 atomic_type = unsigned_int16_type_kind;
3939 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3940 atomic_type = unsigned_int32_type_kind;
3943 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3944 atomic_type = unsigned_int64_type_kind;
3947 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3948 atomic_type = unsigned_int128_type_kind;
3951 case SPECIFIER_INT8:
3952 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3953 atomic_type = int8_type_kind;
3956 case SPECIFIER_INT16:
3957 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3958 atomic_type = int16_type_kind;
3961 case SPECIFIER_INT32:
3962 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3963 atomic_type = int32_type_kind;
3966 case SPECIFIER_INT64:
3967 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3968 atomic_type = int64_type_kind;
3971 case SPECIFIER_INT128:
3972 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3973 atomic_type = int128_type_kind;
3976 case SPECIFIER_FLOAT:
3977 atomic_type = ATOMIC_TYPE_FLOAT;
3979 case SPECIFIER_DOUBLE:
3980 atomic_type = ATOMIC_TYPE_DOUBLE;
3982 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3983 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3985 case SPECIFIER_BOOL:
3986 atomic_type = ATOMIC_TYPE_BOOL;
3988 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3989 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3990 atomic_type = ATOMIC_TYPE_FLOAT;
3992 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3993 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3994 atomic_type = ATOMIC_TYPE_DOUBLE;
3996 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3997 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3998 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4001 /* invalid specifier combination, give an error message */
4002 if (type_specifiers == 0) {
4006 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4007 if (!(c_mode & _CXX) && !strict_mode) {
4008 if (warning.implicit_int) {
4009 warningf(HERE, "no type specifiers in declaration, using 'int'");
4011 atomic_type = ATOMIC_TYPE_INT;
4014 errorf(HERE, "no type specifiers given in declaration");
4016 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4017 (type_specifiers & SPECIFIER_UNSIGNED)) {
4018 errorf(HERE, "signed and unsigned specifiers given");
4019 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4020 errorf(HERE, "only integer types can be signed or unsigned");
4022 errorf(HERE, "multiple datatypes in declaration");
4027 if (type_specifiers & SPECIFIER_COMPLEX) {
4028 type = allocate_type_zero(TYPE_COMPLEX);
4029 type->complex.akind = atomic_type;
4030 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4031 type = allocate_type_zero(TYPE_IMAGINARY);
4032 type->imaginary.akind = atomic_type;
4034 type = allocate_type_zero(TYPE_ATOMIC);
4035 type->atomic.akind = atomic_type;
4038 } else if (type_specifiers != 0) {
4039 errorf(HERE, "multiple datatypes in declaration");
4042 /* FIXME: check type qualifiers here */
4044 type->base.qualifiers = qualifiers;
4045 type->base.modifiers = modifiers;
4047 type_t *result = typehash_insert(type);
4048 if (newtype && result != type) {
4052 specifiers->type = result;
4056 specifiers->type = type_error_type;
4060 static type_qualifiers_t parse_type_qualifiers(void)
4062 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4065 switch (token.type) {
4066 /* type qualifiers */
4067 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4068 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4069 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4070 /* microsoft extended type modifiers */
4071 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4072 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4073 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4074 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4075 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4084 * Parses an K&R identifier list
4086 static void parse_identifier_list(scope_t *scope)
4089 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4090 entity->base.source_position = token.source_position;
4091 entity->base.namespc = NAMESPACE_NORMAL;
4092 entity->base.symbol = token.v.symbol;
4093 /* a K&R parameter has no type, yet */
4097 append_entity(scope, entity);
4099 if (token.type != ',') {
4103 } while (token.type == T_IDENTIFIER);
4106 static entity_t *parse_parameter(void)
4108 declaration_specifiers_t specifiers;
4109 memset(&specifiers, 0, sizeof(specifiers));
4111 parse_declaration_specifiers(&specifiers);
4113 entity_t *entity = parse_declarator(&specifiers,
4114 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4115 anonymous_entity = NULL;
4119 static void semantic_parameter_incomplete(const entity_t *entity)
4121 assert(entity->kind == ENTITY_PARAMETER);
4123 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4124 * list in a function declarator that is part of a
4125 * definition of that function shall not have
4126 * incomplete type. */
4127 type_t *type = skip_typeref(entity->declaration.type);
4128 if (is_type_incomplete(type)) {
4129 errorf(&entity->base.source_position,
4130 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4131 entity->declaration.type);
4136 * Parses function type parameters (and optionally creates variable_t entities
4137 * for them in a scope)
4139 static void parse_parameters(function_type_t *type, scope_t *scope)
4142 add_anchor_token(')');
4143 int saved_comma_state = save_and_reset_anchor_state(',');
4145 if (token.type == T_IDENTIFIER &&
4146 !is_typedef_symbol(token.v.symbol)) {
4147 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4148 if (la1_type == ',' || la1_type == ')') {
4149 type->kr_style_parameters = true;
4150 type->unspecified_parameters = true;
4151 parse_identifier_list(scope);
4152 goto parameters_finished;
4156 if (token.type == ')') {
4157 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4158 if (!(c_mode & _CXX))
4159 type->unspecified_parameters = true;
4160 goto parameters_finished;
4163 function_parameter_t *parameter;
4164 function_parameter_t *last_parameter = NULL;
4167 switch (token.type) {
4170 type->variadic = true;
4171 goto parameters_finished;
4174 case T___extension__:
4177 entity_t *entity = parse_parameter();
4178 if (entity->kind == ENTITY_TYPEDEF) {
4179 errorf(&entity->base.source_position,
4180 "typedef not allowed as function parameter");
4183 assert(is_declaration(entity));
4185 /* func(void) is not a parameter */
4186 if (last_parameter == NULL
4187 && token.type == ')'
4188 && entity->base.symbol == NULL
4189 && skip_typeref(entity->declaration.type) == type_void) {
4190 goto parameters_finished;
4192 semantic_parameter_incomplete(entity);
4194 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4195 memset(parameter, 0, sizeof(parameter[0]));
4196 parameter->type = entity->declaration.type;
4198 if (scope != NULL) {
4199 append_entity(scope, entity);
4202 if (last_parameter != NULL) {
4203 last_parameter->next = parameter;
4205 type->parameters = parameter;
4207 last_parameter = parameter;
4212 goto parameters_finished;
4214 if (token.type != ',') {
4215 goto parameters_finished;
4221 parameters_finished:
4222 rem_anchor_token(')');
4223 expect(')', end_error);
4226 restore_anchor_state(',', saved_comma_state);
4229 typedef enum construct_type_kind_t {
4232 CONSTRUCT_REFERENCE,
4235 } construct_type_kind_t;
4237 typedef struct construct_type_t construct_type_t;
4238 struct construct_type_t {
4239 construct_type_kind_t kind;
4240 construct_type_t *next;
4243 typedef struct parsed_pointer_t parsed_pointer_t;
4244 struct parsed_pointer_t {
4245 construct_type_t construct_type;
4246 type_qualifiers_t type_qualifiers;
4247 variable_t *base_variable; /**< MS __based extension. */
4250 typedef struct parsed_reference_t parsed_reference_t;
4251 struct parsed_reference_t {
4252 construct_type_t construct_type;
4255 typedef struct construct_function_type_t construct_function_type_t;
4256 struct construct_function_type_t {
4257 construct_type_t construct_type;
4258 type_t *function_type;
4261 typedef struct parsed_array_t parsed_array_t;
4262 struct parsed_array_t {
4263 construct_type_t construct_type;
4264 type_qualifiers_t type_qualifiers;
4270 typedef struct construct_base_type_t construct_base_type_t;
4271 struct construct_base_type_t {
4272 construct_type_t construct_type;
4276 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4280 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4281 memset(pointer, 0, sizeof(pointer[0]));
4282 pointer->construct_type.kind = CONSTRUCT_POINTER;
4283 pointer->type_qualifiers = parse_type_qualifiers();
4284 pointer->base_variable = base_variable;
4286 return &pointer->construct_type;
4289 static construct_type_t *parse_reference_declarator(void)
4293 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4294 memset(reference, 0, sizeof(reference[0]));
4295 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4297 return (construct_type_t*)reference;
4300 static construct_type_t *parse_array_declarator(void)
4303 add_anchor_token(']');
4305 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4306 memset(array, 0, sizeof(array[0]));
4307 array->construct_type.kind = CONSTRUCT_ARRAY;
4309 if (token.type == T_static) {
4310 array->is_static = true;
4314 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4315 if (type_qualifiers != 0) {
4316 if (token.type == T_static) {
4317 array->is_static = true;
4321 array->type_qualifiers = type_qualifiers;
4323 if (token.type == '*' && look_ahead(1)->type == ']') {
4324 array->is_variable = true;
4326 } else if (token.type != ']') {
4327 array->size = parse_assignment_expression();
4330 rem_anchor_token(']');
4331 expect(']', end_error);
4334 return &array->construct_type;
4337 static construct_type_t *parse_function_declarator(scope_t *scope,
4338 decl_modifiers_t modifiers)
4340 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4341 function_type_t *ftype = &type->function;
4343 ftype->linkage = current_linkage;
4345 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4346 case DM_NONE: break;
4347 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4348 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4349 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4350 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4353 errorf(HERE, "multiple calling conventions in declaration");
4357 parse_parameters(ftype, scope);
4359 construct_function_type_t *construct_function_type =
4360 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4361 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4362 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4363 construct_function_type->function_type = type;
4365 return &construct_function_type->construct_type;
4368 typedef struct parse_declarator_env_t {
4369 decl_modifiers_t modifiers;
4371 source_position_t source_position;
4373 } parse_declarator_env_t;
4375 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4376 bool may_be_abstract)
4378 /* construct a single linked list of construct_type_t's which describe
4379 * how to construct the final declarator type */
4380 construct_type_t *first = NULL;
4381 construct_type_t *last = NULL;
4382 gnu_attribute_t *attributes = NULL;
4384 decl_modifiers_t modifiers = parse_attributes(&attributes);
4386 /* MS __based extension */
4387 based_spec_t base_spec;
4388 base_spec.base_variable = NULL;
4391 construct_type_t *type;
4392 switch (token.type) {
4394 if (!(c_mode & _CXX))
4395 errorf(HERE, "references are only available for C++");
4396 if (base_spec.base_variable != NULL && warning.other) {
4397 warningf(&base_spec.source_position,
4398 "__based does not precede a pointer operator, ignored");
4400 type = parse_reference_declarator();
4402 base_spec.base_variable = NULL;
4406 type = parse_pointer_declarator(base_spec.base_variable);
4408 base_spec.base_variable = NULL;
4413 expect('(', end_error);
4414 add_anchor_token(')');
4415 parse_microsoft_based(&base_spec);
4416 rem_anchor_token(')');
4417 expect(')', end_error);
4421 goto ptr_operator_end;
4432 /* TODO: find out if this is correct */
4433 modifiers |= parse_attributes(&attributes);
4436 if (base_spec.base_variable != NULL && warning.other) {
4437 warningf(&base_spec.source_position,
4438 "__based does not precede a pointer operator, ignored");
4442 modifiers |= env->modifiers;
4443 env->modifiers = modifiers;
4446 construct_type_t *inner_types = NULL;
4448 switch (token.type) {
4451 errorf(HERE, "no identifier expected in typename");
4453 env->symbol = token.v.symbol;
4454 env->source_position = token.source_position;
4459 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4460 * interpreted as ``function with no parameter specification'', rather
4461 * than redundant parentheses around the omitted identifier. */
4462 if (look_ahead(1)->type != ')') {
4464 add_anchor_token(')');
4465 inner_types = parse_inner_declarator(env, may_be_abstract);
4466 if (inner_types != NULL) {
4467 /* All later declarators only modify the return type */
4470 rem_anchor_token(')');
4471 expect(')', end_error);
4475 if (may_be_abstract)
4477 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4482 construct_type_t *p = last;
4485 construct_type_t *type;
4486 switch (token.type) {
4488 scope_t *scope = NULL;
4490 scope = &env->parameters;
4492 type = parse_function_declarator(scope, modifiers);
4496 type = parse_array_declarator();
4499 goto declarator_finished;
4502 /* insert in the middle of the list (behind p) */
4504 type->next = p->next;
4515 declarator_finished:
4516 /* append inner_types at the end of the list, we don't to set last anymore
4517 * as it's not needed anymore */
4519 assert(first == NULL);
4520 first = inner_types;
4522 last->next = inner_types;
4530 static void parse_declaration_attributes(entity_t *entity)
4532 gnu_attribute_t *attributes = NULL;
4533 decl_modifiers_t modifiers = parse_attributes(&attributes);
4539 if (entity->kind == ENTITY_TYPEDEF) {
4540 modifiers |= entity->typedefe.modifiers;
4541 type = entity->typedefe.type;
4543 assert(is_declaration(entity));
4544 modifiers |= entity->declaration.modifiers;
4545 type = entity->declaration.type;
4550 /* handle these strange/stupid mode attributes */
4551 gnu_attribute_t *attribute = attributes;
4552 for ( ; attribute != NULL; attribute = attribute->next) {
4553 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4556 atomic_type_kind_t akind = attribute->u.akind;
4557 if (!is_type_signed(type)) {
4559 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4560 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4561 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4562 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4564 panic("invalid akind in mode attribute");
4568 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4569 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4570 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4571 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4573 panic("invalid akind in mode attribute");
4577 type = make_atomic_type(akind, type->base.qualifiers);
4580 type_modifiers_t type_modifiers = type->base.modifiers;
4581 if (modifiers & DM_TRANSPARENT_UNION)
4582 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4584 if (type->base.modifiers != type_modifiers) {
4585 type_t *copy = duplicate_type(type);
4586 copy->base.modifiers = type_modifiers;
4588 type = typehash_insert(copy);
4590 obstack_free(type_obst, copy);
4594 if (entity->kind == ENTITY_TYPEDEF) {
4595 entity->typedefe.type = type;
4596 entity->typedefe.modifiers = modifiers;
4598 entity->declaration.type = type;
4599 entity->declaration.modifiers = modifiers;
4603 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4605 construct_type_t *iter = construct_list;
4606 for (; iter != NULL; iter = iter->next) {
4607 switch (iter->kind) {
4608 case CONSTRUCT_INVALID:
4609 internal_errorf(HERE, "invalid type construction found");
4610 case CONSTRUCT_FUNCTION: {
4611 construct_function_type_t *construct_function_type
4612 = (construct_function_type_t*) iter;
4614 type_t *function_type = construct_function_type->function_type;
4616 function_type->function.return_type = type;
4618 type_t *skipped_return_type = skip_typeref(type);
4620 if (is_type_function(skipped_return_type)) {
4621 errorf(HERE, "function returning function is not allowed");
4622 } else if (is_type_array(skipped_return_type)) {
4623 errorf(HERE, "function returning array is not allowed");
4625 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4627 "type qualifiers in return type of function type are meaningless");
4631 type = function_type;
4635 case CONSTRUCT_POINTER: {
4636 if (is_type_reference(skip_typeref(type)))
4637 errorf(HERE, "cannot declare a pointer to reference");
4639 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4640 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4644 case CONSTRUCT_REFERENCE:
4645 if (is_type_reference(skip_typeref(type)))
4646 errorf(HERE, "cannot declare a reference to reference");
4648 type = make_reference_type(type);
4651 case CONSTRUCT_ARRAY: {
4652 if (is_type_reference(skip_typeref(type)))
4653 errorf(HERE, "cannot declare an array of references");
4655 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4656 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4658 expression_t *size_expression = parsed_array->size;
4659 if (size_expression != NULL) {
4661 = create_implicit_cast(size_expression, type_size_t);
4664 array_type->base.qualifiers = parsed_array->type_qualifiers;
4665 array_type->array.element_type = type;
4666 array_type->array.is_static = parsed_array->is_static;
4667 array_type->array.is_variable = parsed_array->is_variable;
4668 array_type->array.size_expression = size_expression;
4670 if (size_expression != NULL) {
4671 if (is_constant_expression(size_expression)) {
4672 array_type->array.size_constant = true;
4673 array_type->array.size
4674 = fold_constant(size_expression);
4676 array_type->array.is_vla = true;
4680 type_t *skipped_type = skip_typeref(type);
4682 if (is_type_incomplete(skipped_type)) {
4683 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4684 } else if (is_type_function(skipped_type)) {
4685 errorf(HERE, "array of functions is not allowed");
4692 type_t *hashed_type = typehash_insert(type);
4693 if (hashed_type != type) {
4694 /* the function type was constructed earlier freeing it here will
4695 * destroy other types... */
4696 if (iter->kind != CONSTRUCT_FUNCTION) {
4706 static type_t *automatic_type_conversion(type_t *orig_type);
4708 static type_t *semantic_parameter(const source_position_t *pos,
4710 const declaration_specifiers_t *specifiers,
4713 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4714 * shall be adjusted to ``qualified pointer to type'',
4716 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4717 * type'' shall be adjusted to ``pointer to function
4718 * returning type'', as in 6.3.2.1. */
4719 type = automatic_type_conversion(type);
4721 if (specifiers->is_inline && is_type_valid(type)) {
4722 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4725 /* §6.9.1:6 The declarations in the declaration list shall contain
4726 * no storage-class specifier other than register and no
4727 * initializations. */
4728 if (specifiers->thread_local || (
4729 specifiers->storage_class != STORAGE_CLASS_NONE &&
4730 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4732 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4735 /* delay test for incomplete type, because we might have (void)
4736 * which is legal but incomplete... */
4741 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4742 declarator_flags_t flags)
4744 parse_declarator_env_t env;
4745 memset(&env, 0, sizeof(env));
4746 env.modifiers = specifiers->modifiers;
4748 construct_type_t *construct_type =
4749 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4751 construct_declarator_type(construct_type, specifiers->type);
4752 type_t *type = skip_typeref(orig_type);
4754 if (construct_type != NULL) {
4755 obstack_free(&temp_obst, construct_type);
4759 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4760 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4761 entity->base.symbol = env.symbol;
4762 entity->base.source_position = env.source_position;
4763 entity->typedefe.type = orig_type;
4765 if (anonymous_entity != NULL) {
4766 if (is_type_compound(type)) {
4767 assert(anonymous_entity->compound.alias == NULL);
4768 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4769 anonymous_entity->kind == ENTITY_UNION);
4770 anonymous_entity->compound.alias = entity;
4771 anonymous_entity = NULL;
4772 } else if (is_type_enum(type)) {
4773 assert(anonymous_entity->enume.alias == NULL);
4774 assert(anonymous_entity->kind == ENTITY_ENUM);
4775 anonymous_entity->enume.alias = entity;
4776 anonymous_entity = NULL;
4780 /* create a declaration type entity */
4781 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4782 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4784 if (specifiers->is_inline && is_type_valid(type)) {
4785 errorf(&env.source_position,
4786 "compound member '%Y' declared 'inline'", env.symbol);
4789 if (specifiers->thread_local ||
4790 specifiers->storage_class != STORAGE_CLASS_NONE) {
4791 errorf(&env.source_position,
4792 "compound member '%Y' must have no storage class",
4795 } else if (flags & DECL_IS_PARAMETER) {
4796 orig_type = semantic_parameter(&env.source_position, orig_type,
4797 specifiers, env.symbol);
4799 entity = allocate_entity_zero(ENTITY_PARAMETER);
4800 } else if (is_type_function(type)) {
4801 entity = allocate_entity_zero(ENTITY_FUNCTION);
4803 entity->function.is_inline = specifiers->is_inline;
4804 entity->function.parameters = env.parameters;
4806 if (specifiers->thread_local || (
4807 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4808 specifiers->storage_class != STORAGE_CLASS_NONE &&
4809 specifiers->storage_class != STORAGE_CLASS_STATIC)
4811 errorf(&env.source_position,
4812 "invalid storage class for function '%Y'", env.symbol);
4815 entity = allocate_entity_zero(ENTITY_VARIABLE);
4817 entity->variable.get_property_sym = specifiers->get_property_sym;
4818 entity->variable.put_property_sym = specifiers->put_property_sym;
4819 if (specifiers->alignment != 0) {
4820 /* TODO: add checks here */
4821 entity->variable.alignment = specifiers->alignment;
4824 if (specifiers->is_inline && is_type_valid(type)) {
4825 errorf(&env.source_position,
4826 "variable '%Y' declared 'inline'", env.symbol);
4829 entity->variable.thread_local = specifiers->thread_local;
4831 bool invalid_storage_class = false;
4832 if (current_scope == file_scope) {
4833 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4834 specifiers->storage_class != STORAGE_CLASS_NONE &&
4835 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4836 invalid_storage_class = true;
4839 if (specifiers->thread_local &&
4840 specifiers->storage_class == STORAGE_CLASS_NONE) {
4841 invalid_storage_class = true;
4844 if (invalid_storage_class) {
4845 errorf(&env.source_position,
4846 "invalid storage class for variable '%Y'", env.symbol);
4850 entity->base.source_position = env.source_position;
4851 entity->base.symbol = env.symbol;
4852 entity->base.namespc = NAMESPACE_NORMAL;
4853 entity->declaration.type = orig_type;
4854 entity->declaration.modifiers = env.modifiers;
4855 entity->declaration.deprecated_string = specifiers->deprecated_string;
4857 storage_class_t storage_class = specifiers->storage_class;
4858 entity->declaration.declared_storage_class = storage_class;
4860 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4861 storage_class = STORAGE_CLASS_AUTO;
4862 entity->declaration.storage_class = storage_class;
4865 parse_declaration_attributes(entity);
4870 static type_t *parse_abstract_declarator(type_t *base_type)
4872 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4874 type_t *result = construct_declarator_type(construct_type, base_type);
4875 if (construct_type != NULL) {
4876 obstack_free(&temp_obst, construct_type);
4883 * Check if the declaration of main is suspicious. main should be a
4884 * function with external linkage, returning int, taking either zero
4885 * arguments, two, or three arguments of appropriate types, ie.
4887 * int main([ int argc, char **argv [, char **env ] ]).
4889 * @param decl the declaration to check
4890 * @param type the function type of the declaration
4892 static void check_type_of_main(const entity_t *entity)
4894 const source_position_t *pos = &entity->base.source_position;
4895 if (entity->kind != ENTITY_FUNCTION) {
4896 warningf(pos, "'main' is not a function");
4900 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4901 warningf(pos, "'main' is normally a non-static function");
4904 type_t *type = skip_typeref(entity->declaration.type);
4905 assert(is_type_function(type));
4907 function_type_t *func_type = &type->function;
4908 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4909 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4910 func_type->return_type);
4912 const function_parameter_t *parm = func_type->parameters;
4914 type_t *const first_type = parm->type;
4915 if (!types_compatible(skip_typeref(first_type), type_int)) {
4917 "first argument of 'main' should be 'int', but is '%T'",
4922 type_t *const second_type = parm->type;
4923 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4924 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4928 type_t *const third_type = parm->type;
4929 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4930 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4934 goto warn_arg_count;
4938 warningf(pos, "'main' takes only zero, two or three arguments");
4944 * Check if a symbol is the equal to "main".
4946 static bool is_sym_main(const symbol_t *const sym)
4948 return strcmp(sym->string, "main") == 0;
4951 static void error_redefined_as_different_kind(const source_position_t *pos,
4952 const entity_t *old, entity_kind_t new_kind)
4954 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4955 get_entity_kind_name(old->kind), old->base.symbol,
4956 get_entity_kind_name(new_kind), &old->base.source_position);
4960 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4961 * for various problems that occur for multiple definitions
4963 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4965 const symbol_t *const symbol = entity->base.symbol;
4966 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4967 const source_position_t *pos = &entity->base.source_position;
4969 /* can happen in error cases */
4973 entity_t *previous_entity = get_entity(symbol, namespc);
4974 /* pushing the same entity twice will break the stack structure */
4975 assert(previous_entity != entity);
4977 if (entity->kind == ENTITY_FUNCTION) {
4978 type_t *const orig_type = entity->declaration.type;
4979 type_t *const type = skip_typeref(orig_type);
4981 assert(is_type_function(type));
4982 if (type->function.unspecified_parameters &&
4983 warning.strict_prototypes &&
4984 previous_entity == NULL) {
4985 warningf(pos, "function declaration '%#T' is not a prototype",
4989 if (warning.main && current_scope == file_scope
4990 && is_sym_main(symbol)) {
4991 check_type_of_main(entity);
4995 if (is_declaration(entity) &&
4996 warning.nested_externs &&
4997 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4998 current_scope != file_scope) {
4999 warningf(pos, "nested extern declaration of '%#T'",
5000 entity->declaration.type, symbol);
5003 if (previous_entity != NULL &&
5004 previous_entity->base.parent_scope == ¤t_function->parameters &&
5005 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5006 assert(previous_entity->kind == ENTITY_PARAMETER);
5008 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5009 entity->declaration.type, symbol,
5010 previous_entity->declaration.type, symbol,
5011 &previous_entity->base.source_position);
5015 if (previous_entity != NULL &&
5016 previous_entity->base.parent_scope == current_scope) {
5017 if (previous_entity->kind != entity->kind) {
5018 error_redefined_as_different_kind(pos, previous_entity,
5022 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5023 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5024 symbol, &previous_entity->base.source_position);
5027 if (previous_entity->kind == ENTITY_TYPEDEF) {
5028 /* TODO: C++ allows this for exactly the same type */
5029 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5030 symbol, &previous_entity->base.source_position);
5034 /* at this point we should have only VARIABLES or FUNCTIONS */
5035 assert(is_declaration(previous_entity) && is_declaration(entity));
5037 declaration_t *const prev_decl = &previous_entity->declaration;
5038 declaration_t *const decl = &entity->declaration;
5040 /* can happen for K&R style declarations */
5041 if (prev_decl->type == NULL &&
5042 previous_entity->kind == ENTITY_PARAMETER &&
5043 entity->kind == ENTITY_PARAMETER) {
5044 prev_decl->type = decl->type;
5045 prev_decl->storage_class = decl->storage_class;
5046 prev_decl->declared_storage_class = decl->declared_storage_class;
5047 prev_decl->modifiers = decl->modifiers;
5048 prev_decl->deprecated_string = decl->deprecated_string;
5049 return previous_entity;
5052 type_t *const orig_type = decl->type;
5053 assert(orig_type != NULL);
5054 type_t *const type = skip_typeref(orig_type);
5055 type_t * prev_type = skip_typeref(prev_decl->type);
5057 if (!types_compatible(type, prev_type)) {
5059 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5060 orig_type, symbol, prev_decl->type, symbol,
5061 &previous_entity->base.source_position);
5063 unsigned old_storage_class = prev_decl->storage_class;
5064 if (warning.redundant_decls &&
5067 !(prev_decl->modifiers & DM_USED) &&
5068 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5069 warningf(&previous_entity->base.source_position,
5070 "unnecessary static forward declaration for '%#T'",
5071 prev_decl->type, symbol);
5074 unsigned new_storage_class = decl->storage_class;
5075 if (is_type_incomplete(prev_type)) {
5076 prev_decl->type = type;
5080 /* pretend no storage class means extern for function
5081 * declarations (except if the previous declaration is neither
5082 * none nor extern) */
5083 if (entity->kind == ENTITY_FUNCTION) {
5084 if (prev_type->function.unspecified_parameters) {
5085 prev_decl->type = type;
5089 switch (old_storage_class) {
5090 case STORAGE_CLASS_NONE:
5091 old_storage_class = STORAGE_CLASS_EXTERN;
5094 case STORAGE_CLASS_EXTERN:
5095 if (is_definition) {
5096 if (warning.missing_prototypes &&
5097 prev_type->function.unspecified_parameters &&
5098 !is_sym_main(symbol)) {
5099 warningf(pos, "no previous prototype for '%#T'",
5102 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5103 new_storage_class = STORAGE_CLASS_EXTERN;
5112 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5113 new_storage_class == STORAGE_CLASS_EXTERN) {
5114 warn_redundant_declaration:
5115 if (!is_definition &&
5116 warning.redundant_decls &&
5117 is_type_valid(prev_type) &&
5118 strcmp(previous_entity->base.source_position.input_name,
5119 "<builtin>") != 0) {
5121 "redundant declaration for '%Y' (declared %P)",
5122 symbol, &previous_entity->base.source_position);
5124 } else if (current_function == NULL) {
5125 if (old_storage_class != STORAGE_CLASS_STATIC &&
5126 new_storage_class == STORAGE_CLASS_STATIC) {
5128 "static declaration of '%Y' follows non-static declaration (declared %P)",
5129 symbol, &previous_entity->base.source_position);
5130 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5131 prev_decl->storage_class = STORAGE_CLASS_NONE;
5132 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5134 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5136 goto error_redeclaration;
5137 goto warn_redundant_declaration;
5139 } else if (is_type_valid(prev_type)) {
5140 if (old_storage_class == new_storage_class) {
5141 error_redeclaration:
5142 errorf(pos, "redeclaration of '%Y' (declared %P)",
5143 symbol, &previous_entity->base.source_position);
5146 "redeclaration of '%Y' with different linkage (declared %P)",
5147 symbol, &previous_entity->base.source_position);
5152 prev_decl->modifiers |= decl->modifiers;
5153 if (entity->kind == ENTITY_FUNCTION) {
5154 previous_entity->function.is_inline |= entity->function.is_inline;
5156 return previous_entity;
5159 if (entity->kind == ENTITY_FUNCTION) {
5160 if (is_definition &&
5161 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5162 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5163 warningf(pos, "no previous prototype for '%#T'",
5164 entity->declaration.type, symbol);
5165 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5166 warningf(pos, "no previous declaration for '%#T'",
5167 entity->declaration.type, symbol);
5170 } else if (warning.missing_declarations &&
5171 entity->kind == ENTITY_VARIABLE &&
5172 current_scope == file_scope) {
5173 declaration_t *declaration = &entity->declaration;
5174 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5175 warningf(pos, "no previous declaration for '%#T'",
5176 declaration->type, symbol);
5181 assert(entity->base.parent_scope == NULL);
5182 assert(current_scope != NULL);
5184 entity->base.parent_scope = current_scope;
5185 entity->base.namespc = NAMESPACE_NORMAL;
5186 environment_push(entity);
5187 append_entity(current_scope, entity);
5192 static void parser_error_multiple_definition(entity_t *entity,
5193 const source_position_t *source_position)
5195 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5196 entity->base.symbol, &entity->base.source_position);
5199 static bool is_declaration_specifier(const token_t *token,
5200 bool only_specifiers_qualifiers)
5202 switch (token->type) {
5207 return is_typedef_symbol(token->v.symbol);
5209 case T___extension__:
5211 return !only_specifiers_qualifiers;
5218 static void parse_init_declarator_rest(entity_t *entity)
5220 assert(is_declaration(entity));
5221 declaration_t *const declaration = &entity->declaration;
5225 type_t *orig_type = declaration->type;
5226 type_t *type = skip_typeref(orig_type);
5228 if (entity->kind == ENTITY_VARIABLE
5229 && entity->variable.initializer != NULL) {
5230 parser_error_multiple_definition(entity, HERE);
5233 bool must_be_constant = false;
5234 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5235 entity->base.parent_scope == file_scope) {
5236 must_be_constant = true;
5239 if (is_type_function(type)) {
5240 errorf(&entity->base.source_position,
5241 "function '%#T' is initialized like a variable",
5242 orig_type, entity->base.symbol);
5243 orig_type = type_error_type;
5246 parse_initializer_env_t env;
5247 env.type = orig_type;
5248 env.must_be_constant = must_be_constant;
5249 env.entity = entity;
5250 current_init_decl = entity;
5252 initializer_t *initializer = parse_initializer(&env);
5253 current_init_decl = NULL;
5255 if (entity->kind == ENTITY_VARIABLE) {
5256 /* § 6.7.5 (22) array initializers for arrays with unknown size
5257 * determine the array type size */
5258 declaration->type = env.type;
5259 entity->variable.initializer = initializer;
5263 /* parse rest of a declaration without any declarator */
5264 static void parse_anonymous_declaration_rest(
5265 const declaration_specifiers_t *specifiers)
5268 anonymous_entity = NULL;
5270 if (warning.other) {
5271 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5272 specifiers->thread_local) {
5273 warningf(&specifiers->source_position,
5274 "useless storage class in empty declaration");
5277 type_t *type = specifiers->type;
5278 switch (type->kind) {
5279 case TYPE_COMPOUND_STRUCT:
5280 case TYPE_COMPOUND_UNION: {
5281 if (type->compound.compound->base.symbol == NULL) {
5282 warningf(&specifiers->source_position,
5283 "unnamed struct/union that defines no instances");
5292 warningf(&specifiers->source_position, "empty declaration");
5298 static void check_variable_type_complete(entity_t *ent)
5300 if (ent->kind != ENTITY_VARIABLE)
5303 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5304 * type for the object shall be complete [...] */
5305 declaration_t *decl = &ent->declaration;
5306 if (decl->storage_class != STORAGE_CLASS_NONE)
5309 type_t *const orig_type = decl->type;
5310 type_t *const type = skip_typeref(orig_type);
5311 if (!is_type_incomplete(type))
5314 /* GCC allows global arrays without size and assigns them a length of one,
5315 * if no different declaration follows */
5316 if (is_type_array(type) &&
5318 ent->base.parent_scope == file_scope) {
5319 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5323 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5324 orig_type, ent->base.symbol);
5328 static void parse_declaration_rest(entity_t *ndeclaration,
5329 const declaration_specifiers_t *specifiers,
5330 parsed_declaration_func finished_declaration,
5331 declarator_flags_t flags)
5333 add_anchor_token(';');
5334 add_anchor_token(',');
5336 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5338 if (token.type == '=') {
5339 parse_init_declarator_rest(entity);
5340 } else if (entity->kind == ENTITY_VARIABLE) {
5341 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5342 * [...] where the extern specifier is explicitly used. */
5343 declaration_t *decl = &entity->declaration;
5344 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5345 type_t *type = decl->type;
5346 if (is_type_reference(skip_typeref(type))) {
5347 errorf(&entity->base.source_position,
5348 "reference '%#T' must be initialized",
5349 type, entity->base.symbol);
5354 check_variable_type_complete(entity);
5356 if (token.type != ',')
5360 add_anchor_token('=');
5361 ndeclaration = parse_declarator(specifiers, flags);
5362 rem_anchor_token('=');
5364 expect(';', end_error);
5367 anonymous_entity = NULL;
5368 rem_anchor_token(';');
5369 rem_anchor_token(',');
5372 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5374 symbol_t *symbol = entity->base.symbol;
5375 if (symbol == NULL) {
5376 errorf(HERE, "anonymous declaration not valid as function parameter");
5380 assert(entity->base.namespc == NAMESPACE_NORMAL);
5381 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5382 if (previous_entity == NULL
5383 || previous_entity->base.parent_scope != current_scope) {
5384 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5389 if (is_definition) {
5390 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5393 return record_entity(entity, false);
5396 static void parse_declaration(parsed_declaration_func finished_declaration,
5397 declarator_flags_t flags)
5399 declaration_specifiers_t specifiers;
5400 memset(&specifiers, 0, sizeof(specifiers));
5402 add_anchor_token(';');
5403 parse_declaration_specifiers(&specifiers);
5404 rem_anchor_token(';');
5406 if (token.type == ';') {
5407 parse_anonymous_declaration_rest(&specifiers);
5409 entity_t *entity = parse_declarator(&specifiers, flags);
5410 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5414 static type_t *get_default_promoted_type(type_t *orig_type)
5416 type_t *result = orig_type;
5418 type_t *type = skip_typeref(orig_type);
5419 if (is_type_integer(type)) {
5420 result = promote_integer(type);
5421 } else if (type == type_float) {
5422 result = type_double;
5428 static void parse_kr_declaration_list(entity_t *entity)
5430 if (entity->kind != ENTITY_FUNCTION)
5433 type_t *type = skip_typeref(entity->declaration.type);
5434 assert(is_type_function(type));
5435 if (!type->function.kr_style_parameters)
5439 add_anchor_token('{');
5441 /* push function parameters */
5442 size_t const top = environment_top();
5443 scope_t *old_scope = scope_push(&entity->function.parameters);
5445 entity_t *parameter = entity->function.parameters.entities;
5446 for ( ; parameter != NULL; parameter = parameter->base.next) {
5447 assert(parameter->base.parent_scope == NULL);
5448 parameter->base.parent_scope = current_scope;
5449 environment_push(parameter);
5452 /* parse declaration list */
5454 switch (token.type) {
5456 case T___extension__:
5457 /* This covers symbols, which are no type, too, and results in
5458 * better error messages. The typical cases are misspelled type
5459 * names and missing includes. */
5461 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5469 /* pop function parameters */
5470 assert(current_scope == &entity->function.parameters);
5471 scope_pop(old_scope);
5472 environment_pop_to(top);
5474 /* update function type */
5475 type_t *new_type = duplicate_type(type);
5477 function_parameter_t *parameters = NULL;
5478 function_parameter_t *last_parameter = NULL;
5480 parameter = entity->function.parameters.entities;
5481 for (; parameter != NULL; parameter = parameter->base.next) {
5482 type_t *parameter_type = parameter->declaration.type;
5483 if (parameter_type == NULL) {
5485 errorf(HERE, "no type specified for function parameter '%Y'",
5486 parameter->base.symbol);
5488 if (warning.implicit_int) {
5489 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5490 parameter->base.symbol);
5492 parameter_type = type_int;
5493 parameter->declaration.type = parameter_type;
5497 semantic_parameter_incomplete(parameter);
5498 parameter_type = parameter->declaration.type;
5501 * we need the default promoted types for the function type
5503 parameter_type = get_default_promoted_type(parameter_type);
5505 function_parameter_t *function_parameter
5506 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5507 memset(function_parameter, 0, sizeof(function_parameter[0]));
5509 function_parameter->type = parameter_type;
5510 if (last_parameter != NULL) {
5511 last_parameter->next = function_parameter;
5513 parameters = function_parameter;
5515 last_parameter = function_parameter;
5518 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5520 new_type->function.parameters = parameters;
5521 new_type->function.unspecified_parameters = true;
5523 type = typehash_insert(new_type);
5524 if (type != new_type) {
5525 obstack_free(type_obst, new_type);
5528 entity->declaration.type = type;
5530 rem_anchor_token('{');
5533 static bool first_err = true;
5536 * When called with first_err set, prints the name of the current function,
5539 static void print_in_function(void)
5543 diagnosticf("%s: In function '%Y':\n",
5544 current_function->base.base.source_position.input_name,
5545 current_function->base.base.symbol);
5550 * Check if all labels are defined in the current function.
5551 * Check if all labels are used in the current function.
5553 static void check_labels(void)
5555 for (const goto_statement_t *goto_statement = goto_first;
5556 goto_statement != NULL;
5557 goto_statement = goto_statement->next) {
5558 /* skip computed gotos */
5559 if (goto_statement->expression != NULL)
5562 label_t *label = goto_statement->label;
5565 if (label->base.source_position.input_name == NULL) {
5566 print_in_function();
5567 errorf(&goto_statement->base.source_position,
5568 "label '%Y' used but not defined", label->base.symbol);
5572 if (warning.unused_label) {
5573 for (const label_statement_t *label_statement = label_first;
5574 label_statement != NULL;
5575 label_statement = label_statement->next) {
5576 label_t *label = label_statement->label;
5578 if (! label->used) {
5579 print_in_function();
5580 warningf(&label_statement->base.source_position,
5581 "label '%Y' defined but not used", label->base.symbol);
5587 static void warn_unused_entity(entity_t *entity, entity_t *last)
5589 entity_t const *const end = last != NULL ? last->base.next : NULL;
5590 for (; entity != end; entity = entity->base.next) {
5591 if (!is_declaration(entity))
5594 declaration_t *declaration = &entity->declaration;
5595 if (declaration->implicit)
5598 if (!declaration->used) {
5599 print_in_function();
5600 const char *what = get_entity_kind_name(entity->kind);
5601 warningf(&entity->base.source_position, "%s '%Y' is unused",
5602 what, entity->base.symbol);
5603 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5604 print_in_function();
5605 const char *what = get_entity_kind_name(entity->kind);
5606 warningf(&entity->base.source_position, "%s '%Y' is never read",
5607 what, entity->base.symbol);
5612 static void check_unused_variables(statement_t *const stmt, void *const env)
5616 switch (stmt->kind) {
5617 case STATEMENT_DECLARATION: {
5618 declaration_statement_t const *const decls = &stmt->declaration;
5619 warn_unused_entity(decls->declarations_begin,
5620 decls->declarations_end);
5625 warn_unused_entity(stmt->fors.scope.entities, NULL);
5634 * Check declarations of current_function for unused entities.
5636 static void check_declarations(void)
5638 if (warning.unused_parameter) {
5639 const scope_t *scope = ¤t_function->parameters;
5641 /* do not issue unused warnings for main */
5642 if (!is_sym_main(current_function->base.base.symbol)) {
5643 warn_unused_entity(scope->entities, NULL);
5646 if (warning.unused_variable) {
5647 walk_statements(current_function->statement, check_unused_variables,
5652 static int determine_truth(expression_t const* const cond)
5655 !is_constant_expression(cond) ? 0 :
5656 fold_constant(cond) != 0 ? 1 :
5660 static void check_reachable(statement_t *);
5661 static bool reaches_end;
5663 static bool expression_returns(expression_t const *const expr)
5665 switch (expr->kind) {
5667 expression_t const *const func = expr->call.function;
5668 if (func->kind == EXPR_REFERENCE) {
5669 entity_t *entity = func->reference.entity;
5670 if (entity->kind == ENTITY_FUNCTION
5671 && entity->declaration.modifiers & DM_NORETURN)
5675 if (!expression_returns(func))
5678 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5679 if (!expression_returns(arg->expression))
5686 case EXPR_REFERENCE:
5687 case EXPR_REFERENCE_ENUM_VALUE:
5689 case EXPR_CHARACTER_CONSTANT:
5690 case EXPR_WIDE_CHARACTER_CONSTANT:
5691 case EXPR_STRING_LITERAL:
5692 case EXPR_WIDE_STRING_LITERAL:
5693 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5694 case EXPR_LABEL_ADDRESS:
5695 case EXPR_CLASSIFY_TYPE:
5696 case EXPR_SIZEOF: // TODO handle obscure VLA case
5699 case EXPR_BUILTIN_SYMBOL:
5700 case EXPR_BUILTIN_CONSTANT_P:
5701 case EXPR_BUILTIN_PREFETCH:
5706 case EXPR_STATEMENT: {
5707 bool old_reaches_end = reaches_end;
5708 reaches_end = false;
5709 check_reachable(expr->statement.statement);
5710 bool returns = reaches_end;
5711 reaches_end = old_reaches_end;
5715 case EXPR_CONDITIONAL:
5716 // TODO handle constant expression
5718 if (!expression_returns(expr->conditional.condition))
5721 if (expr->conditional.true_expression != NULL
5722 && expression_returns(expr->conditional.true_expression))
5725 return expression_returns(expr->conditional.false_expression);
5728 return expression_returns(expr->select.compound);
5730 case EXPR_ARRAY_ACCESS:
5732 expression_returns(expr->array_access.array_ref) &&
5733 expression_returns(expr->array_access.index);
5736 return expression_returns(expr->va_starte.ap);
5739 return expression_returns(expr->va_arge.ap);
5741 EXPR_UNARY_CASES_MANDATORY
5742 return expression_returns(expr->unary.value);
5744 case EXPR_UNARY_THROW:
5748 // TODO handle constant lhs of && and ||
5750 expression_returns(expr->binary.left) &&
5751 expression_returns(expr->binary.right);
5757 panic("unhandled expression");
5760 static bool initializer_returns(initializer_t const *const init)
5762 switch (init->kind) {
5763 case INITIALIZER_VALUE:
5764 return expression_returns(init->value.value);
5766 case INITIALIZER_LIST: {
5767 initializer_t * const* i = init->list.initializers;
5768 initializer_t * const* const end = i + init->list.len;
5769 bool returns = true;
5770 for (; i != end; ++i) {
5771 if (!initializer_returns(*i))
5777 case INITIALIZER_STRING:
5778 case INITIALIZER_WIDE_STRING:
5779 case INITIALIZER_DESIGNATOR: // designators have no payload
5782 panic("unhandled initializer");
5785 static bool noreturn_candidate;
5787 static void check_reachable(statement_t *const stmt)
5789 if (stmt->base.reachable)
5791 if (stmt->kind != STATEMENT_DO_WHILE)
5792 stmt->base.reachable = true;
5794 statement_t *last = stmt;
5796 switch (stmt->kind) {
5797 case STATEMENT_INVALID:
5798 case STATEMENT_EMPTY:
5799 case STATEMENT_LOCAL_LABEL:
5801 next = stmt->base.next;
5804 case STATEMENT_DECLARATION: {
5805 declaration_statement_t const *const decl = &stmt->declaration;
5806 entity_t const * ent = decl->declarations_begin;
5807 entity_t const *const last = decl->declarations_end;
5809 for (;; ent = ent->base.next) {
5810 if (ent->kind == ENTITY_VARIABLE &&
5811 ent->variable.initializer != NULL &&
5812 !initializer_returns(ent->variable.initializer)) {
5819 next = stmt->base.next;
5823 case STATEMENT_COMPOUND:
5824 next = stmt->compound.statements;
5827 case STATEMENT_RETURN: {
5828 expression_t const *const val = stmt->returns.value;
5829 if (val == NULL || expression_returns(val))
5830 noreturn_candidate = false;
5834 case STATEMENT_IF: {
5835 if_statement_t const *const ifs = &stmt->ifs;
5836 expression_t const *const cond = ifs->condition;
5838 if (!expression_returns(cond))
5841 int const val = determine_truth(cond);
5844 check_reachable(ifs->true_statement);
5849 if (ifs->false_statement != NULL) {
5850 check_reachable(ifs->false_statement);
5854 next = stmt->base.next;
5858 case STATEMENT_SWITCH: {
5859 switch_statement_t const *const switchs = &stmt->switchs;
5860 expression_t const *const expr = switchs->expression;
5862 if (!expression_returns(expr))
5865 if (is_constant_expression(expr)) {
5866 long const val = fold_constant(expr);
5867 case_label_statement_t * defaults = NULL;
5868 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5869 if (i->expression == NULL) {
5874 if (i->first_case <= val && val <= i->last_case) {
5875 check_reachable((statement_t*)i);
5880 if (defaults != NULL) {
5881 check_reachable((statement_t*)defaults);
5885 bool has_default = false;
5886 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5887 if (i->expression == NULL)
5890 check_reachable((statement_t*)i);
5897 next = stmt->base.next;
5901 case STATEMENT_EXPRESSION: {
5902 /* Check for noreturn function call */
5903 expression_t const *const expr = stmt->expression.expression;
5904 if (!expression_returns(expr))
5907 next = stmt->base.next;
5911 case STATEMENT_CONTINUE: {
5912 statement_t *parent = stmt;
5914 parent = parent->base.parent;
5915 if (parent == NULL) /* continue not within loop */
5919 switch (parent->kind) {
5920 case STATEMENT_WHILE: goto continue_while;
5921 case STATEMENT_DO_WHILE: goto continue_do_while;
5922 case STATEMENT_FOR: goto continue_for;
5929 case STATEMENT_BREAK: {
5930 statement_t *parent = stmt;
5932 parent = parent->base.parent;
5933 if (parent == NULL) /* break not within loop/switch */
5936 switch (parent->kind) {
5937 case STATEMENT_SWITCH:
5938 case STATEMENT_WHILE:
5939 case STATEMENT_DO_WHILE:
5942 next = parent->base.next;
5943 goto found_break_parent;
5952 case STATEMENT_GOTO:
5953 if (stmt->gotos.expression) {
5954 if (!expression_returns(stmt->gotos.expression))
5957 statement_t *parent = stmt->base.parent;
5958 if (parent == NULL) /* top level goto */
5962 next = stmt->gotos.label->statement;
5963 if (next == NULL) /* missing label */
5968 case STATEMENT_LABEL:
5969 next = stmt->label.statement;
5972 case STATEMENT_CASE_LABEL:
5973 next = stmt->case_label.statement;
5976 case STATEMENT_WHILE: {
5977 while_statement_t const *const whiles = &stmt->whiles;
5978 expression_t const *const cond = whiles->condition;
5980 if (!expression_returns(cond))
5983 int const val = determine_truth(cond);
5986 check_reachable(whiles->body);
5991 next = stmt->base.next;
5995 case STATEMENT_DO_WHILE:
5996 next = stmt->do_while.body;
5999 case STATEMENT_FOR: {
6000 for_statement_t *const fors = &stmt->fors;
6002 if (fors->condition_reachable)
6004 fors->condition_reachable = true;
6006 expression_t const *const cond = fors->condition;
6011 } else if (expression_returns(cond)) {
6012 val = determine_truth(cond);
6018 check_reachable(fors->body);
6023 next = stmt->base.next;
6027 case STATEMENT_MS_TRY: {
6028 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6029 check_reachable(ms_try->try_statement);
6030 next = ms_try->final_statement;
6034 case STATEMENT_LEAVE: {
6035 statement_t *parent = stmt;
6037 parent = parent->base.parent;
6038 if (parent == NULL) /* __leave not within __try */
6041 if (parent->kind == STATEMENT_MS_TRY) {
6043 next = parent->ms_try.final_statement;
6051 panic("invalid statement kind");
6054 while (next == NULL) {
6055 next = last->base.parent;
6057 noreturn_candidate = false;
6059 type_t *const type = current_function->base.type;
6060 assert(is_type_function(type));
6061 type_t *const ret = skip_typeref(type->function.return_type);
6062 if (warning.return_type &&
6063 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6064 is_type_valid(ret) &&
6065 !is_sym_main(current_function->base.base.symbol)) {
6066 warningf(&stmt->base.source_position,
6067 "control reaches end of non-void function");
6072 switch (next->kind) {
6073 case STATEMENT_INVALID:
6074 case STATEMENT_EMPTY:
6075 case STATEMENT_DECLARATION:
6076 case STATEMENT_LOCAL_LABEL:
6077 case STATEMENT_EXPRESSION:
6079 case STATEMENT_RETURN:
6080 case STATEMENT_CONTINUE:
6081 case STATEMENT_BREAK:
6082 case STATEMENT_GOTO:
6083 case STATEMENT_LEAVE:
6084 panic("invalid control flow in function");
6086 case STATEMENT_COMPOUND:
6087 if (next->compound.stmt_expr) {
6093 case STATEMENT_SWITCH:
6094 case STATEMENT_LABEL:
6095 case STATEMENT_CASE_LABEL:
6097 next = next->base.next;
6100 case STATEMENT_WHILE: {
6102 if (next->base.reachable)
6104 next->base.reachable = true;
6106 while_statement_t const *const whiles = &next->whiles;
6107 expression_t const *const cond = whiles->condition;
6109 if (!expression_returns(cond))
6112 int const val = determine_truth(cond);
6115 check_reachable(whiles->body);
6121 next = next->base.next;
6125 case STATEMENT_DO_WHILE: {
6127 if (next->base.reachable)
6129 next->base.reachable = true;
6131 do_while_statement_t const *const dw = &next->do_while;
6132 expression_t const *const cond = dw->condition;
6134 if (!expression_returns(cond))
6137 int const val = determine_truth(cond);
6140 check_reachable(dw->body);
6146 next = next->base.next;
6150 case STATEMENT_FOR: {
6152 for_statement_t *const fors = &next->fors;
6154 fors->step_reachable = true;
6156 if (fors->condition_reachable)
6158 fors->condition_reachable = true;
6160 expression_t const *const cond = fors->condition;
6165 } else if (expression_returns(cond)) {
6166 val = determine_truth(cond);
6172 check_reachable(fors->body);
6178 next = next->base.next;
6182 case STATEMENT_MS_TRY:
6184 next = next->ms_try.final_statement;
6189 check_reachable(next);
6192 static void check_unreachable(statement_t* const stmt, void *const env)
6196 switch (stmt->kind) {
6197 case STATEMENT_DO_WHILE:
6198 if (!stmt->base.reachable) {
6199 expression_t const *const cond = stmt->do_while.condition;
6200 if (determine_truth(cond) >= 0) {
6201 warningf(&cond->base.source_position,
6202 "condition of do-while-loop is unreachable");
6207 case STATEMENT_FOR: {
6208 for_statement_t const* const fors = &stmt->fors;
6210 // if init and step are unreachable, cond is unreachable, too
6211 if (!stmt->base.reachable && !fors->step_reachable) {
6212 warningf(&stmt->base.source_position, "statement is unreachable");
6214 if (!stmt->base.reachable && fors->initialisation != NULL) {
6215 warningf(&fors->initialisation->base.source_position,
6216 "initialisation of for-statement is unreachable");
6219 if (!fors->condition_reachable && fors->condition != NULL) {
6220 warningf(&fors->condition->base.source_position,
6221 "condition of for-statement is unreachable");
6224 if (!fors->step_reachable && fors->step != NULL) {
6225 warningf(&fors->step->base.source_position,
6226 "step of for-statement is unreachable");
6232 case STATEMENT_COMPOUND:
6233 if (stmt->compound.statements != NULL)
6235 goto warn_unreachable;
6237 case STATEMENT_DECLARATION: {
6238 /* Only warn if there is at least one declarator with an initializer.
6239 * This typically occurs in switch statements. */
6240 declaration_statement_t const *const decl = &stmt->declaration;
6241 entity_t const * ent = decl->declarations_begin;
6242 entity_t const *const last = decl->declarations_end;
6244 for (;; ent = ent->base.next) {
6245 if (ent->kind == ENTITY_VARIABLE &&
6246 ent->variable.initializer != NULL) {
6247 goto warn_unreachable;
6257 if (!stmt->base.reachable)
6258 warningf(&stmt->base.source_position, "statement is unreachable");
6263 static void parse_external_declaration(void)
6265 /* function-definitions and declarations both start with declaration
6267 declaration_specifiers_t specifiers;
6268 memset(&specifiers, 0, sizeof(specifiers));
6270 add_anchor_token(';');
6271 parse_declaration_specifiers(&specifiers);
6272 rem_anchor_token(';');
6274 /* must be a declaration */
6275 if (token.type == ';') {
6276 parse_anonymous_declaration_rest(&specifiers);
6280 add_anchor_token(',');
6281 add_anchor_token('=');
6282 add_anchor_token(';');
6283 add_anchor_token('{');
6285 /* declarator is common to both function-definitions and declarations */
6286 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6288 rem_anchor_token('{');
6289 rem_anchor_token(';');
6290 rem_anchor_token('=');
6291 rem_anchor_token(',');
6293 /* must be a declaration */
6294 switch (token.type) {
6298 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6303 /* must be a function definition */
6304 parse_kr_declaration_list(ndeclaration);
6306 if (token.type != '{') {
6307 parse_error_expected("while parsing function definition", '{', NULL);
6308 eat_until_matching_token(';');
6312 assert(is_declaration(ndeclaration));
6313 type_t *type = skip_typeref(ndeclaration->declaration.type);
6315 if (!is_type_function(type)) {
6316 if (is_type_valid(type)) {
6317 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6318 type, ndeclaration->base.symbol);
6324 if (warning.aggregate_return &&
6325 is_type_compound(skip_typeref(type->function.return_type))) {
6326 warningf(HERE, "function '%Y' returns an aggregate",
6327 ndeclaration->base.symbol);
6329 if (warning.traditional && !type->function.unspecified_parameters) {
6330 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6331 ndeclaration->base.symbol);
6333 if (warning.old_style_definition && type->function.unspecified_parameters) {
6334 warningf(HERE, "old-style function definition '%Y'",
6335 ndeclaration->base.symbol);
6338 /* § 6.7.5.3 (14) a function definition with () means no
6339 * parameters (and not unspecified parameters) */
6340 if (type->function.unspecified_parameters
6341 && type->function.parameters == NULL
6342 && !type->function.kr_style_parameters) {
6343 type_t *duplicate = duplicate_type(type);
6344 duplicate->function.unspecified_parameters = false;
6346 type = typehash_insert(duplicate);
6347 if (type != duplicate) {
6348 obstack_free(type_obst, duplicate);
6350 ndeclaration->declaration.type = type;
6353 entity_t *const entity = record_entity(ndeclaration, true);
6354 assert(entity->kind == ENTITY_FUNCTION);
6355 assert(ndeclaration->kind == ENTITY_FUNCTION);
6357 function_t *function = &entity->function;
6358 if (ndeclaration != entity) {
6359 function->parameters = ndeclaration->function.parameters;
6361 assert(is_declaration(entity));
6362 type = skip_typeref(entity->declaration.type);
6364 /* push function parameters and switch scope */
6365 size_t const top = environment_top();
6366 scope_t *old_scope = scope_push(&function->parameters);
6368 entity_t *parameter = function->parameters.entities;
6369 for (; parameter != NULL; parameter = parameter->base.next) {
6370 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6371 parameter->base.parent_scope = current_scope;
6373 assert(parameter->base.parent_scope == NULL
6374 || parameter->base.parent_scope == current_scope);
6375 parameter->base.parent_scope = current_scope;
6376 if (parameter->base.symbol == NULL) {
6377 errorf(¶meter->base.source_position, "parameter name omitted");
6380 environment_push(parameter);
6383 if (function->statement != NULL) {
6384 parser_error_multiple_definition(entity, HERE);
6387 /* parse function body */
6388 int label_stack_top = label_top();
6389 function_t *old_current_function = current_function;
6390 current_function = function;
6391 current_parent = NULL;
6394 goto_anchor = &goto_first;
6396 label_anchor = &label_first;
6398 statement_t *const body = parse_compound_statement(false);
6399 function->statement = body;
6402 check_declarations();
6403 if (warning.return_type ||
6404 warning.unreachable_code ||
6405 (warning.missing_noreturn
6406 && !(function->base.modifiers & DM_NORETURN))) {
6407 noreturn_candidate = true;
6408 check_reachable(body);
6409 if (warning.unreachable_code)
6410 walk_statements(body, check_unreachable, NULL);
6411 if (warning.missing_noreturn &&
6412 noreturn_candidate &&
6413 !(function->base.modifiers & DM_NORETURN)) {
6414 warningf(&body->base.source_position,
6415 "function '%#T' is candidate for attribute 'noreturn'",
6416 type, entity->base.symbol);
6420 assert(current_parent == NULL);
6421 assert(current_function == function);
6422 current_function = old_current_function;
6423 label_pop_to(label_stack_top);
6426 assert(current_scope == &function->parameters);
6427 scope_pop(old_scope);
6428 environment_pop_to(top);
6431 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6432 source_position_t *source_position,
6433 const symbol_t *symbol)
6435 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6437 type->bitfield.base_type = base_type;
6438 type->bitfield.size_expression = size;
6441 type_t *skipped_type = skip_typeref(base_type);
6442 if (!is_type_integer(skipped_type)) {
6443 errorf(HERE, "bitfield base type '%T' is not an integer type",
6447 bit_size = skipped_type->base.size * 8;
6450 if (is_constant_expression(size)) {
6451 long v = fold_constant(size);
6454 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6455 } else if (v == 0) {
6456 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6457 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6458 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6460 type->bitfield.bit_size = v;
6467 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6469 entity_t *iter = compound->members.entities;
6470 for (; iter != NULL; iter = iter->base.next) {
6471 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6474 if (iter->base.symbol == symbol) {
6476 } else if (iter->base.symbol == NULL) {
6477 type_t *type = skip_typeref(iter->declaration.type);
6478 if (is_type_compound(type)) {
6480 = find_compound_entry(type->compound.compound, symbol);
6491 static void parse_compound_declarators(compound_t *compound,
6492 const declaration_specifiers_t *specifiers)
6497 if (token.type == ':') {
6498 source_position_t source_position = *HERE;
6501 type_t *base_type = specifiers->type;
6502 expression_t *size = parse_constant_expression();
6504 type_t *type = make_bitfield_type(base_type, size,
6505 &source_position, sym_anonymous);
6507 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6508 entity->base.namespc = NAMESPACE_NORMAL;
6509 entity->base.source_position = source_position;
6510 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6511 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6512 entity->declaration.modifiers = specifiers->modifiers;
6513 entity->declaration.type = type;
6515 entity = parse_declarator(specifiers,
6516 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6517 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6519 if (token.type == ':') {
6520 source_position_t source_position = *HERE;
6522 expression_t *size = parse_constant_expression();
6524 type_t *type = entity->declaration.type;
6525 type_t *bitfield_type = make_bitfield_type(type, size,
6526 &source_position, entity->base.symbol);
6527 entity->declaration.type = bitfield_type;
6531 /* make sure we don't define a symbol multiple times */
6532 symbol_t *symbol = entity->base.symbol;
6533 if (symbol != NULL) {
6534 entity_t *prev = find_compound_entry(compound, symbol);
6537 errorf(&entity->base.source_position,
6538 "multiple declarations of symbol '%Y' (declared %P)",
6539 symbol, &prev->base.source_position);
6543 append_entity(&compound->members, entity);
6545 type_t *orig_type = entity->declaration.type;
6546 type_t *type = skip_typeref(orig_type);
6547 if (is_type_function(type)) {
6548 errorf(&entity->base.source_position,
6549 "compound member '%Y' must not have function type '%T'",
6550 entity->base.symbol, orig_type);
6551 } else if (is_type_incomplete(type)) {
6552 /* §6.7.2.1:16 flexible array member */
6553 if (is_type_array(type) &&
6554 token.type == ';' &&
6555 look_ahead(1)->type == '}') {
6556 compound->has_flexible_member = true;
6558 errorf(&entity->base.source_position,
6559 "compound member '%Y' has incomplete type '%T'",
6560 entity->base.symbol, orig_type);
6564 if (token.type != ',')
6568 expect(';', end_error);
6571 anonymous_entity = NULL;
6574 static void parse_compound_type_entries(compound_t *compound)
6577 add_anchor_token('}');
6579 while (token.type != '}') {
6580 if (token.type == T_EOF) {
6581 errorf(HERE, "EOF while parsing struct");
6584 declaration_specifiers_t specifiers;
6585 memset(&specifiers, 0, sizeof(specifiers));
6586 parse_declaration_specifiers(&specifiers);
6588 parse_compound_declarators(compound, &specifiers);
6590 rem_anchor_token('}');
6594 compound->complete = true;
6597 static type_t *parse_typename(void)
6599 declaration_specifiers_t specifiers;
6600 memset(&specifiers, 0, sizeof(specifiers));
6601 parse_declaration_specifiers(&specifiers);
6602 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6603 specifiers.thread_local) {
6604 /* TODO: improve error message, user does probably not know what a
6605 * storage class is...
6607 errorf(HERE, "typename may not have a storage class");
6610 type_t *result = parse_abstract_declarator(specifiers.type);
6618 typedef expression_t* (*parse_expression_function)(void);
6619 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6621 typedef struct expression_parser_function_t expression_parser_function_t;
6622 struct expression_parser_function_t {
6623 parse_expression_function parser;
6624 unsigned infix_precedence;
6625 parse_expression_infix_function infix_parser;
6628 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6631 * Prints an error message if an expression was expected but not read
6633 static expression_t *expected_expression_error(void)
6635 /* skip the error message if the error token was read */
6636 if (token.type != T_ERROR) {
6637 errorf(HERE, "expected expression, got token %K", &token);
6641 return create_invalid_expression();
6645 * Parse a string constant.
6647 static expression_t *parse_string_const(void)
6650 if (token.type == T_STRING_LITERAL) {
6651 string_t res = token.v.string;
6653 while (token.type == T_STRING_LITERAL) {
6654 res = concat_strings(&res, &token.v.string);
6657 if (token.type != T_WIDE_STRING_LITERAL) {
6658 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6659 /* note: that we use type_char_ptr here, which is already the
6660 * automatic converted type. revert_automatic_type_conversion
6661 * will construct the array type */
6662 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6663 cnst->string.value = res;
6667 wres = concat_string_wide_string(&res, &token.v.wide_string);
6669 wres = token.v.wide_string;
6674 switch (token.type) {
6675 case T_WIDE_STRING_LITERAL:
6676 wres = concat_wide_strings(&wres, &token.v.wide_string);
6679 case T_STRING_LITERAL:
6680 wres = concat_wide_string_string(&wres, &token.v.string);
6684 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6685 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6686 cnst->wide_string.value = wres;
6695 * Parse a boolean constant.
6697 static expression_t *parse_bool_const(bool value)
6699 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6700 cnst->base.type = type_bool;
6701 cnst->conste.v.int_value = value;
6709 * Parse an integer constant.
6711 static expression_t *parse_int_const(void)
6713 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6714 cnst->base.type = token.datatype;
6715 cnst->conste.v.int_value = token.v.intvalue;
6723 * Parse a character constant.
6725 static expression_t *parse_character_constant(void)
6727 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6728 cnst->base.type = token.datatype;
6729 cnst->conste.v.character = token.v.string;
6731 if (cnst->conste.v.character.size != 1) {
6733 errorf(HERE, "more than 1 character in character constant");
6734 } else if (warning.multichar) {
6735 warningf(HERE, "multi-character character constant");
6744 * Parse a wide character constant.
6746 static expression_t *parse_wide_character_constant(void)
6748 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6749 cnst->base.type = token.datatype;
6750 cnst->conste.v.wide_character = token.v.wide_string;
6752 if (cnst->conste.v.wide_character.size != 1) {
6754 errorf(HERE, "more than 1 character in character constant");
6755 } else if (warning.multichar) {
6756 warningf(HERE, "multi-character character constant");
6765 * Parse a float constant.
6767 static expression_t *parse_float_const(void)
6769 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6770 cnst->base.type = token.datatype;
6771 cnst->conste.v.float_value = token.v.floatvalue;
6778 static entity_t *create_implicit_function(symbol_t *symbol,
6779 const source_position_t *source_position)
6781 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6782 ntype->function.return_type = type_int;
6783 ntype->function.unspecified_parameters = true;
6784 ntype->function.linkage = LINKAGE_C;
6786 type_t *type = typehash_insert(ntype);
6787 if (type != ntype) {
6791 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6792 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6793 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6794 entity->declaration.type = type;
6795 entity->declaration.implicit = true;
6796 entity->base.symbol = symbol;
6797 entity->base.source_position = *source_position;
6799 bool strict_prototypes_old = warning.strict_prototypes;
6800 warning.strict_prototypes = false;
6801 record_entity(entity, false);
6802 warning.strict_prototypes = strict_prototypes_old;
6808 * Creates a return_type (func)(argument_type) function type if not
6811 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6812 type_t *argument_type2)
6814 function_parameter_t *parameter2
6815 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6816 memset(parameter2, 0, sizeof(parameter2[0]));
6817 parameter2->type = argument_type2;
6819 function_parameter_t *parameter1
6820 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6821 memset(parameter1, 0, sizeof(parameter1[0]));
6822 parameter1->type = argument_type1;
6823 parameter1->next = parameter2;
6825 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6826 type->function.return_type = return_type;
6827 type->function.parameters = parameter1;
6829 type_t *result = typehash_insert(type);
6830 if (result != type) {
6838 * Creates a return_type (func)(argument_type) function type if not
6841 * @param return_type the return type
6842 * @param argument_type the argument type
6844 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6846 function_parameter_t *parameter
6847 = obstack_alloc(type_obst, sizeof(parameter[0]));
6848 memset(parameter, 0, sizeof(parameter[0]));
6849 parameter->type = argument_type;
6851 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6852 type->function.return_type = return_type;
6853 type->function.parameters = parameter;
6855 type_t *result = typehash_insert(type);
6856 if (result != type) {
6863 static type_t *make_function_0_type(type_t *return_type)
6865 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6866 type->function.return_type = return_type;
6867 type->function.parameters = NULL;
6869 type_t *result = typehash_insert(type);
6870 if (result != type) {
6878 * Creates a function type for some function like builtins.
6880 * @param symbol the symbol describing the builtin
6882 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6884 switch (symbol->ID) {
6885 case T___builtin_alloca:
6886 return make_function_1_type(type_void_ptr, type_size_t);
6887 case T___builtin_huge_val:
6888 return make_function_0_type(type_double);
6889 case T___builtin_inf:
6890 return make_function_0_type(type_double);
6891 case T___builtin_inff:
6892 return make_function_0_type(type_float);
6893 case T___builtin_infl:
6894 return make_function_0_type(type_long_double);
6895 case T___builtin_nan:
6896 return make_function_1_type(type_double, type_char_ptr);
6897 case T___builtin_nanf:
6898 return make_function_1_type(type_float, type_char_ptr);
6899 case T___builtin_nanl:
6900 return make_function_1_type(type_long_double, type_char_ptr);
6901 case T___builtin_va_end:
6902 return make_function_1_type(type_void, type_valist);
6903 case T___builtin_expect:
6904 return make_function_2_type(type_long, type_long, type_long);
6906 internal_errorf(HERE, "not implemented builtin identifier found");
6911 * Performs automatic type cast as described in § 6.3.2.1.
6913 * @param orig_type the original type
6915 static type_t *automatic_type_conversion(type_t *orig_type)
6917 type_t *type = skip_typeref(orig_type);
6918 if (is_type_array(type)) {
6919 array_type_t *array_type = &type->array;
6920 type_t *element_type = array_type->element_type;
6921 unsigned qualifiers = array_type->base.qualifiers;
6923 return make_pointer_type(element_type, qualifiers);
6926 if (is_type_function(type)) {
6927 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6934 * reverts the automatic casts of array to pointer types and function
6935 * to function-pointer types as defined § 6.3.2.1
6937 type_t *revert_automatic_type_conversion(const expression_t *expression)
6939 switch (expression->kind) {
6940 case EXPR_REFERENCE: {
6941 entity_t *entity = expression->reference.entity;
6942 if (is_declaration(entity)) {
6943 return entity->declaration.type;
6944 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6945 return entity->enum_value.enum_type;
6947 panic("no declaration or enum in reference");
6952 entity_t *entity = expression->select.compound_entry;
6953 assert(is_declaration(entity));
6954 type_t *type = entity->declaration.type;
6955 return get_qualified_type(type,
6956 expression->base.type->base.qualifiers);
6959 case EXPR_UNARY_DEREFERENCE: {
6960 const expression_t *const value = expression->unary.value;
6961 type_t *const type = skip_typeref(value->base.type);
6962 assert(is_type_pointer(type));
6963 return type->pointer.points_to;
6966 case EXPR_BUILTIN_SYMBOL:
6967 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6969 case EXPR_ARRAY_ACCESS: {
6970 const expression_t *array_ref = expression->array_access.array_ref;
6971 type_t *type_left = skip_typeref(array_ref->base.type);
6972 if (!is_type_valid(type_left))
6974 assert(is_type_pointer(type_left));
6975 return type_left->pointer.points_to;
6978 case EXPR_STRING_LITERAL: {
6979 size_t size = expression->string.value.size;
6980 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6983 case EXPR_WIDE_STRING_LITERAL: {
6984 size_t size = expression->wide_string.value.size;
6985 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6988 case EXPR_COMPOUND_LITERAL:
6989 return expression->compound_literal.type;
6994 return expression->base.type;
6997 static expression_t *parse_reference(void)
6999 symbol_t *const symbol = token.v.symbol;
7001 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7003 if (entity == NULL) {
7004 if (!strict_mode && look_ahead(1)->type == '(') {
7005 /* an implicitly declared function */
7006 if (warning.error_implicit_function_declaration) {
7007 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7008 } else if (warning.implicit_function_declaration) {
7009 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7012 entity = create_implicit_function(symbol, HERE);
7014 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7015 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7021 if (is_declaration(entity)) {
7022 orig_type = entity->declaration.type;
7023 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7024 orig_type = entity->enum_value.enum_type;
7025 } else if (entity->kind == ENTITY_TYPEDEF) {
7026 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7029 return create_invalid_expression();
7031 panic("expected declaration or enum value in reference");
7034 /* we always do the auto-type conversions; the & and sizeof parser contains
7035 * code to revert this! */
7036 type_t *type = automatic_type_conversion(orig_type);
7038 expression_kind_t kind = EXPR_REFERENCE;
7039 if (entity->kind == ENTITY_ENUM_VALUE)
7040 kind = EXPR_REFERENCE_ENUM_VALUE;
7042 expression_t *expression = allocate_expression_zero(kind);
7043 expression->reference.entity = entity;
7044 expression->base.type = type;
7046 /* this declaration is used */
7047 if (is_declaration(entity)) {
7048 entity->declaration.used = true;
7051 if (entity->base.parent_scope != file_scope
7052 && entity->base.parent_scope->depth < current_function->parameters.depth
7053 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7054 if (entity->kind == ENTITY_VARIABLE) {
7055 /* access of a variable from an outer function */
7056 entity->variable.address_taken = true;
7057 } else if (entity->kind == ENTITY_PARAMETER) {
7058 entity->parameter.address_taken = true;
7060 current_function->need_closure = true;
7063 /* check for deprecated functions */
7064 if (warning.deprecated_declarations
7065 && is_declaration(entity)
7066 && entity->declaration.modifiers & DM_DEPRECATED) {
7067 declaration_t *declaration = &entity->declaration;
7069 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7070 "function" : "variable";
7072 if (declaration->deprecated_string != NULL) {
7073 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7074 prefix, entity->base.symbol, &entity->base.source_position,
7075 declaration->deprecated_string);
7077 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7078 entity->base.symbol, &entity->base.source_position);
7082 if (warning.init_self && entity == current_init_decl && !in_type_prop
7083 && entity->kind == ENTITY_VARIABLE) {
7084 current_init_decl = NULL;
7085 warningf(HERE, "variable '%#T' is initialized by itself",
7086 entity->declaration.type, entity->base.symbol);
7093 static bool semantic_cast(expression_t *cast)
7095 expression_t *expression = cast->unary.value;
7096 type_t *orig_dest_type = cast->base.type;
7097 type_t *orig_type_right = expression->base.type;
7098 type_t const *dst_type = skip_typeref(orig_dest_type);
7099 type_t const *src_type = skip_typeref(orig_type_right);
7100 source_position_t const *pos = &cast->base.source_position;
7102 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7103 if (dst_type == type_void)
7106 /* only integer and pointer can be casted to pointer */
7107 if (is_type_pointer(dst_type) &&
7108 !is_type_pointer(src_type) &&
7109 !is_type_integer(src_type) &&
7110 is_type_valid(src_type)) {
7111 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7115 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7116 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7120 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7121 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7125 if (warning.cast_qual &&
7126 is_type_pointer(src_type) &&
7127 is_type_pointer(dst_type)) {
7128 type_t *src = skip_typeref(src_type->pointer.points_to);
7129 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7130 unsigned missing_qualifiers =
7131 src->base.qualifiers & ~dst->base.qualifiers;
7132 if (missing_qualifiers != 0) {
7134 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7135 missing_qualifiers, orig_type_right);
7141 static expression_t *parse_compound_literal(type_t *type)
7143 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7145 parse_initializer_env_t env;
7148 env.must_be_constant = false;
7149 initializer_t *initializer = parse_initializer(&env);
7152 expression->compound_literal.initializer = initializer;
7153 expression->compound_literal.type = type;
7154 expression->base.type = automatic_type_conversion(type);
7160 * Parse a cast expression.
7162 static expression_t *parse_cast(void)
7164 add_anchor_token(')');
7166 source_position_t source_position = token.source_position;
7168 type_t *type = parse_typename();
7170 rem_anchor_token(')');
7171 expect(')', end_error);
7173 if (token.type == '{') {
7174 return parse_compound_literal(type);
7177 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7178 cast->base.source_position = source_position;
7180 expression_t *value = parse_sub_expression(PREC_CAST);
7181 cast->base.type = type;
7182 cast->unary.value = value;
7184 if (! semantic_cast(cast)) {
7185 /* TODO: record the error in the AST. else it is impossible to detect it */
7190 return create_invalid_expression();
7194 * Parse a statement expression.
7196 static expression_t *parse_statement_expression(void)
7198 add_anchor_token(')');
7200 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7202 statement_t *statement = parse_compound_statement(true);
7203 statement->compound.stmt_expr = true;
7204 expression->statement.statement = statement;
7206 /* find last statement and use its type */
7207 type_t *type = type_void;
7208 const statement_t *stmt = statement->compound.statements;
7210 while (stmt->base.next != NULL)
7211 stmt = stmt->base.next;
7213 if (stmt->kind == STATEMENT_EXPRESSION) {
7214 type = stmt->expression.expression->base.type;
7216 } else if (warning.other) {
7217 warningf(&expression->base.source_position, "empty statement expression ({})");
7219 expression->base.type = type;
7221 rem_anchor_token(')');
7222 expect(')', end_error);
7229 * Parse a parenthesized expression.
7231 static expression_t *parse_parenthesized_expression(void)
7235 switch (token.type) {
7237 /* gcc extension: a statement expression */
7238 return parse_statement_expression();
7242 return parse_cast();
7244 if (is_typedef_symbol(token.v.symbol)) {
7245 return parse_cast();
7249 add_anchor_token(')');
7250 expression_t *result = parse_expression();
7251 result->base.parenthesized = true;
7252 rem_anchor_token(')');
7253 expect(')', end_error);
7259 static expression_t *parse_function_keyword(void)
7263 if (current_function == NULL) {
7264 errorf(HERE, "'__func__' used outside of a function");
7267 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7268 expression->base.type = type_char_ptr;
7269 expression->funcname.kind = FUNCNAME_FUNCTION;
7276 static expression_t *parse_pretty_function_keyword(void)
7278 if (current_function == NULL) {
7279 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7282 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7283 expression->base.type = type_char_ptr;
7284 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7286 eat(T___PRETTY_FUNCTION__);
7291 static expression_t *parse_funcsig_keyword(void)
7293 if (current_function == NULL) {
7294 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7297 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7298 expression->base.type = type_char_ptr;
7299 expression->funcname.kind = FUNCNAME_FUNCSIG;
7306 static expression_t *parse_funcdname_keyword(void)
7308 if (current_function == NULL) {
7309 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7312 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7313 expression->base.type = type_char_ptr;
7314 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7316 eat(T___FUNCDNAME__);
7321 static designator_t *parse_designator(void)
7323 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7324 result->source_position = *HERE;
7326 if (token.type != T_IDENTIFIER) {
7327 parse_error_expected("while parsing member designator",
7328 T_IDENTIFIER, NULL);
7331 result->symbol = token.v.symbol;
7334 designator_t *last_designator = result;
7336 if (token.type == '.') {
7338 if (token.type != T_IDENTIFIER) {
7339 parse_error_expected("while parsing member designator",
7340 T_IDENTIFIER, NULL);
7343 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7344 designator->source_position = *HERE;
7345 designator->symbol = token.v.symbol;
7348 last_designator->next = designator;
7349 last_designator = designator;
7352 if (token.type == '[') {
7354 add_anchor_token(']');
7355 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7356 designator->source_position = *HERE;
7357 designator->array_index = parse_expression();
7358 rem_anchor_token(']');
7359 expect(']', end_error);
7360 if (designator->array_index == NULL) {
7364 last_designator->next = designator;
7365 last_designator = designator;
7377 * Parse the __builtin_offsetof() expression.
7379 static expression_t *parse_offsetof(void)
7381 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7382 expression->base.type = type_size_t;
7384 eat(T___builtin_offsetof);
7386 expect('(', end_error);
7387 add_anchor_token(',');
7388 type_t *type = parse_typename();
7389 rem_anchor_token(',');
7390 expect(',', end_error);
7391 add_anchor_token(')');
7392 designator_t *designator = parse_designator();
7393 rem_anchor_token(')');
7394 expect(')', end_error);
7396 expression->offsetofe.type = type;
7397 expression->offsetofe.designator = designator;
7400 memset(&path, 0, sizeof(path));
7401 path.top_type = type;
7402 path.path = NEW_ARR_F(type_path_entry_t, 0);
7404 descend_into_subtype(&path);
7406 if (!walk_designator(&path, designator, true)) {
7407 return create_invalid_expression();
7410 DEL_ARR_F(path.path);
7414 return create_invalid_expression();
7418 * Parses a _builtin_va_start() expression.
7420 static expression_t *parse_va_start(void)
7422 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7424 eat(T___builtin_va_start);
7426 expect('(', end_error);
7427 add_anchor_token(',');
7428 expression->va_starte.ap = parse_assignment_expression();
7429 rem_anchor_token(',');
7430 expect(',', end_error);
7431 expression_t *const expr = parse_assignment_expression();
7432 if (expr->kind == EXPR_REFERENCE) {
7433 entity_t *const entity = expr->reference.entity;
7434 if (entity->base.parent_scope != ¤t_function->parameters
7435 || entity->base.next != NULL
7436 || entity->kind != ENTITY_PARAMETER) {
7437 errorf(&expr->base.source_position,
7438 "second argument of 'va_start' must be last parameter of the current function");
7440 expression->va_starte.parameter = &entity->variable;
7442 expect(')', end_error);
7445 expect(')', end_error);
7447 return create_invalid_expression();
7451 * Parses a _builtin_va_arg() expression.
7453 static expression_t *parse_va_arg(void)
7455 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7457 eat(T___builtin_va_arg);
7459 expect('(', end_error);
7460 expression->va_arge.ap = parse_assignment_expression();
7461 expect(',', end_error);
7462 expression->base.type = parse_typename();
7463 expect(')', end_error);
7467 return create_invalid_expression();
7470 static expression_t *parse_builtin_symbol(void)
7472 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7474 symbol_t *symbol = token.v.symbol;
7476 expression->builtin_symbol.symbol = symbol;
7479 type_t *type = get_builtin_symbol_type(symbol);
7480 type = automatic_type_conversion(type);
7482 expression->base.type = type;
7487 * Parses a __builtin_constant() expression.
7489 static expression_t *parse_builtin_constant(void)
7491 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7493 eat(T___builtin_constant_p);
7495 expect('(', end_error);
7496 add_anchor_token(')');
7497 expression->builtin_constant.value = parse_assignment_expression();
7498 rem_anchor_token(')');
7499 expect(')', end_error);
7500 expression->base.type = type_int;
7504 return create_invalid_expression();
7508 * Parses a __builtin_prefetch() expression.
7510 static expression_t *parse_builtin_prefetch(void)
7512 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7514 eat(T___builtin_prefetch);
7516 expect('(', end_error);
7517 add_anchor_token(')');
7518 expression->builtin_prefetch.adr = parse_assignment_expression();
7519 if (token.type == ',') {
7521 expression->builtin_prefetch.rw = parse_assignment_expression();
7523 if (token.type == ',') {
7525 expression->builtin_prefetch.locality = parse_assignment_expression();
7527 rem_anchor_token(')');
7528 expect(')', end_error);
7529 expression->base.type = type_void;
7533 return create_invalid_expression();
7537 * Parses a __builtin_is_*() compare expression.
7539 static expression_t *parse_compare_builtin(void)
7541 expression_t *expression;
7543 switch (token.type) {
7544 case T___builtin_isgreater:
7545 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7547 case T___builtin_isgreaterequal:
7548 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7550 case T___builtin_isless:
7551 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7553 case T___builtin_islessequal:
7554 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7556 case T___builtin_islessgreater:
7557 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7559 case T___builtin_isunordered:
7560 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7563 internal_errorf(HERE, "invalid compare builtin found");
7565 expression->base.source_position = *HERE;
7568 expect('(', end_error);
7569 expression->binary.left = parse_assignment_expression();
7570 expect(',', end_error);
7571 expression->binary.right = parse_assignment_expression();
7572 expect(')', end_error);
7574 type_t *const orig_type_left = expression->binary.left->base.type;
7575 type_t *const orig_type_right = expression->binary.right->base.type;
7577 type_t *const type_left = skip_typeref(orig_type_left);
7578 type_t *const type_right = skip_typeref(orig_type_right);
7579 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7580 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7581 type_error_incompatible("invalid operands in comparison",
7582 &expression->base.source_position, orig_type_left, orig_type_right);
7585 semantic_comparison(&expression->binary);
7590 return create_invalid_expression();
7595 * Parses a __builtin_expect(, end_error) expression.
7597 static expression_t *parse_builtin_expect(void, end_error)
7599 expression_t *expression
7600 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7602 eat(T___builtin_expect);
7604 expect('(', end_error);
7605 expression->binary.left = parse_assignment_expression();
7606 expect(',', end_error);
7607 expression->binary.right = parse_constant_expression();
7608 expect(')', end_error);
7610 expression->base.type = expression->binary.left->base.type;
7614 return create_invalid_expression();
7619 * Parses a MS assume() expression.
7621 static expression_t *parse_assume(void)
7623 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7627 expect('(', end_error);
7628 add_anchor_token(')');
7629 expression->unary.value = parse_assignment_expression();
7630 rem_anchor_token(')');
7631 expect(')', end_error);
7633 expression->base.type = type_void;
7636 return create_invalid_expression();
7640 * Return the declaration for a given label symbol or create a new one.
7642 * @param symbol the symbol of the label
7644 static label_t *get_label(symbol_t *symbol)
7647 assert(current_function != NULL);
7649 label = get_entity(symbol, NAMESPACE_LABEL);
7650 /* if we found a local label, we already created the declaration */
7651 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7652 if (label->base.parent_scope != current_scope) {
7653 assert(label->base.parent_scope->depth < current_scope->depth);
7654 current_function->goto_to_outer = true;
7656 return &label->label;
7659 label = get_entity(symbol, NAMESPACE_LABEL);
7660 /* if we found a label in the same function, then we already created the
7663 && label->base.parent_scope == ¤t_function->parameters) {
7664 return &label->label;
7667 /* otherwise we need to create a new one */
7668 label = allocate_entity_zero(ENTITY_LABEL);
7669 label->base.namespc = NAMESPACE_LABEL;
7670 label->base.symbol = symbol;
7674 return &label->label;
7678 * Parses a GNU && label address expression.
7680 static expression_t *parse_label_address(void)
7682 source_position_t source_position = token.source_position;
7684 if (token.type != T_IDENTIFIER) {
7685 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7688 symbol_t *symbol = token.v.symbol;
7691 label_t *label = get_label(symbol);
7693 label->address_taken = true;
7695 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7696 expression->base.source_position = source_position;
7698 /* label address is threaten as a void pointer */
7699 expression->base.type = type_void_ptr;
7700 expression->label_address.label = label;
7703 return create_invalid_expression();
7707 * Parse a microsoft __noop expression.
7709 static expression_t *parse_noop_expression(void)
7711 /* the result is a (int)0 */
7712 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7713 cnst->base.type = type_int;
7714 cnst->conste.v.int_value = 0;
7715 cnst->conste.is_ms_noop = true;
7719 if (token.type == '(') {
7720 /* parse arguments */
7722 add_anchor_token(')');
7723 add_anchor_token(',');
7725 if (token.type != ')') {
7727 (void)parse_assignment_expression();
7728 if (token.type != ',')
7734 rem_anchor_token(',');
7735 rem_anchor_token(')');
7736 expect(')', end_error);
7743 * Parses a primary expression.
7745 static expression_t *parse_primary_expression(void)
7747 switch (token.type) {
7748 case T_false: return parse_bool_const(false);
7749 case T_true: return parse_bool_const(true);
7750 case T_INTEGER: return parse_int_const();
7751 case T_CHARACTER_CONSTANT: return parse_character_constant();
7752 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7753 case T_FLOATINGPOINT: return parse_float_const();
7754 case T_STRING_LITERAL:
7755 case T_WIDE_STRING_LITERAL: return parse_string_const();
7756 case T_IDENTIFIER: return parse_reference();
7757 case T___FUNCTION__:
7758 case T___func__: return parse_function_keyword();
7759 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7760 case T___FUNCSIG__: return parse_funcsig_keyword();
7761 case T___FUNCDNAME__: return parse_funcdname_keyword();
7762 case T___builtin_offsetof: return parse_offsetof();
7763 case T___builtin_va_start: return parse_va_start();
7764 case T___builtin_va_arg: return parse_va_arg();
7765 case T___builtin_expect:
7766 case T___builtin_alloca:
7767 case T___builtin_inf:
7768 case T___builtin_inff:
7769 case T___builtin_infl:
7770 case T___builtin_nan:
7771 case T___builtin_nanf:
7772 case T___builtin_nanl:
7773 case T___builtin_huge_val:
7774 case T___builtin_va_end: return parse_builtin_symbol();
7775 case T___builtin_isgreater:
7776 case T___builtin_isgreaterequal:
7777 case T___builtin_isless:
7778 case T___builtin_islessequal:
7779 case T___builtin_islessgreater:
7780 case T___builtin_isunordered: return parse_compare_builtin();
7781 case T___builtin_constant_p: return parse_builtin_constant();
7782 case T___builtin_prefetch: return parse_builtin_prefetch();
7783 case T__assume: return parse_assume();
7786 return parse_label_address();
7789 case '(': return parse_parenthesized_expression();
7790 case T___noop: return parse_noop_expression();
7793 errorf(HERE, "unexpected token %K, expected an expression", &token);
7794 return create_invalid_expression();
7798 * Check if the expression has the character type and issue a warning then.
7800 static void check_for_char_index_type(const expression_t *expression)
7802 type_t *const type = expression->base.type;
7803 const type_t *const base_type = skip_typeref(type);
7805 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7806 warning.char_subscripts) {
7807 warningf(&expression->base.source_position,
7808 "array subscript has type '%T'", type);
7812 static expression_t *parse_array_expression(expression_t *left)
7814 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7817 add_anchor_token(']');
7819 expression_t *inside = parse_expression();
7821 type_t *const orig_type_left = left->base.type;
7822 type_t *const orig_type_inside = inside->base.type;
7824 type_t *const type_left = skip_typeref(orig_type_left);
7825 type_t *const type_inside = skip_typeref(orig_type_inside);
7827 type_t *return_type;
7828 array_access_expression_t *array_access = &expression->array_access;
7829 if (is_type_pointer(type_left)) {
7830 return_type = type_left->pointer.points_to;
7831 array_access->array_ref = left;
7832 array_access->index = inside;
7833 check_for_char_index_type(inside);
7834 } else if (is_type_pointer(type_inside)) {
7835 return_type = type_inside->pointer.points_to;
7836 array_access->array_ref = inside;
7837 array_access->index = left;
7838 array_access->flipped = true;
7839 check_for_char_index_type(left);
7841 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7843 "array access on object with non-pointer types '%T', '%T'",
7844 orig_type_left, orig_type_inside);
7846 return_type = type_error_type;
7847 array_access->array_ref = left;
7848 array_access->index = inside;
7851 expression->base.type = automatic_type_conversion(return_type);
7853 rem_anchor_token(']');
7854 expect(']', end_error);
7859 static expression_t *parse_typeprop(expression_kind_t const kind)
7861 expression_t *tp_expression = allocate_expression_zero(kind);
7862 tp_expression->base.type = type_size_t;
7864 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7866 /* we only refer to a type property, mark this case */
7867 bool old = in_type_prop;
7868 in_type_prop = true;
7871 expression_t *expression;
7872 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7874 add_anchor_token(')');
7875 orig_type = parse_typename();
7876 rem_anchor_token(')');
7877 expect(')', end_error);
7879 if (token.type == '{') {
7880 /* It was not sizeof(type) after all. It is sizeof of an expression
7881 * starting with a compound literal */
7882 expression = parse_compound_literal(orig_type);
7883 goto typeprop_expression;
7886 expression = parse_sub_expression(PREC_UNARY);
7888 typeprop_expression:
7889 tp_expression->typeprop.tp_expression = expression;
7891 orig_type = revert_automatic_type_conversion(expression);
7892 expression->base.type = orig_type;
7895 tp_expression->typeprop.type = orig_type;
7896 type_t const* const type = skip_typeref(orig_type);
7897 char const* const wrong_type =
7898 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7899 is_type_incomplete(type) ? "incomplete" :
7900 type->kind == TYPE_FUNCTION ? "function designator" :
7901 type->kind == TYPE_BITFIELD ? "bitfield" :
7903 if (wrong_type != NULL) {
7904 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7905 errorf(&tp_expression->base.source_position,
7906 "operand of %s expression must not be of %s type '%T'",
7907 what, wrong_type, orig_type);
7912 return tp_expression;
7915 static expression_t *parse_sizeof(void)
7917 return parse_typeprop(EXPR_SIZEOF);
7920 static expression_t *parse_alignof(void)
7922 return parse_typeprop(EXPR_ALIGNOF);
7925 static expression_t *parse_select_expression(expression_t *compound)
7927 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7928 select->select.compound = compound;
7930 assert(token.type == '.' || token.type == T_MINUSGREATER);
7931 bool is_pointer = (token.type == T_MINUSGREATER);
7934 if (token.type != T_IDENTIFIER) {
7935 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7938 symbol_t *symbol = token.v.symbol;
7941 type_t *const orig_type = compound->base.type;
7942 type_t *const type = skip_typeref(orig_type);
7945 bool saw_error = false;
7946 if (is_type_pointer(type)) {
7949 "request for member '%Y' in something not a struct or union, but '%T'",
7953 type_left = skip_typeref(type->pointer.points_to);
7955 if (is_pointer && is_type_valid(type)) {
7956 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7963 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7964 type_left->kind == TYPE_COMPOUND_UNION) {
7965 compound_t *compound = type_left->compound.compound;
7967 if (!compound->complete) {
7968 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7970 goto create_error_entry;
7973 entry = find_compound_entry(compound, symbol);
7974 if (entry == NULL) {
7975 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7976 goto create_error_entry;
7979 if (is_type_valid(type_left) && !saw_error) {
7981 "request for member '%Y' in something not a struct or union, but '%T'",
7985 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7988 assert(is_declaration(entry));
7989 select->select.compound_entry = entry;
7991 type_t *entry_type = entry->declaration.type;
7993 = get_qualified_type(entry_type, type_left->base.qualifiers);
7995 /* we always do the auto-type conversions; the & and sizeof parser contains
7996 * code to revert this! */
7997 select->base.type = automatic_type_conversion(res_type);
7999 type_t *skipped = skip_typeref(res_type);
8000 if (skipped->kind == TYPE_BITFIELD) {
8001 select->base.type = skipped->bitfield.base_type;
8007 static void check_call_argument(const function_parameter_t *parameter,
8008 call_argument_t *argument, unsigned pos)
8010 type_t *expected_type = parameter->type;
8011 type_t *expected_type_skip = skip_typeref(expected_type);
8012 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8013 expression_t *arg_expr = argument->expression;
8014 type_t *arg_type = skip_typeref(arg_expr->base.type);
8016 /* handle transparent union gnu extension */
8017 if (is_type_union(expected_type_skip)
8018 && (expected_type_skip->base.modifiers
8019 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8020 compound_t *union_decl = expected_type_skip->compound.compound;
8021 type_t *best_type = NULL;
8022 entity_t *entry = union_decl->members.entities;
8023 for ( ; entry != NULL; entry = entry->base.next) {
8024 assert(is_declaration(entry));
8025 type_t *decl_type = entry->declaration.type;
8026 error = semantic_assign(decl_type, arg_expr);
8027 if (error == ASSIGN_ERROR_INCOMPATIBLE
8028 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8031 if (error == ASSIGN_SUCCESS) {
8032 best_type = decl_type;
8033 } else if (best_type == NULL) {
8034 best_type = decl_type;
8038 if (best_type != NULL) {
8039 expected_type = best_type;
8043 error = semantic_assign(expected_type, arg_expr);
8044 argument->expression = create_implicit_cast(argument->expression,
8047 if (error != ASSIGN_SUCCESS) {
8048 /* report exact scope in error messages (like "in argument 3") */
8050 snprintf(buf, sizeof(buf), "call argument %u", pos);
8051 report_assign_error(error, expected_type, arg_expr, buf,
8052 &arg_expr->base.source_position);
8053 } else if (warning.traditional || warning.conversion) {
8054 type_t *const promoted_type = get_default_promoted_type(arg_type);
8055 if (!types_compatible(expected_type_skip, promoted_type) &&
8056 !types_compatible(expected_type_skip, type_void_ptr) &&
8057 !types_compatible(type_void_ptr, promoted_type)) {
8058 /* Deliberately show the skipped types in this warning */
8059 warningf(&arg_expr->base.source_position,
8060 "passing call argument %u as '%T' rather than '%T' due to prototype",
8061 pos, expected_type_skip, promoted_type);
8067 * Parse a call expression, ie. expression '( ... )'.
8069 * @param expression the function address
8071 static expression_t *parse_call_expression(expression_t *expression)
8073 expression_t *result = allocate_expression_zero(EXPR_CALL);
8074 call_expression_t *call = &result->call;
8075 call->function = expression;
8077 type_t *const orig_type = expression->base.type;
8078 type_t *const type = skip_typeref(orig_type);
8080 function_type_t *function_type = NULL;
8081 if (is_type_pointer(type)) {
8082 type_t *const to_type = skip_typeref(type->pointer.points_to);
8084 if (is_type_function(to_type)) {
8085 function_type = &to_type->function;
8086 call->base.type = function_type->return_type;
8090 if (function_type == NULL && is_type_valid(type)) {
8091 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8094 /* parse arguments */
8096 add_anchor_token(')');
8097 add_anchor_token(',');
8099 if (token.type != ')') {
8100 call_argument_t *last_argument = NULL;
8103 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8105 argument->expression = parse_assignment_expression();
8106 if (last_argument == NULL) {
8107 call->arguments = argument;
8109 last_argument->next = argument;
8111 last_argument = argument;
8113 if (token.type != ',')
8118 rem_anchor_token(',');
8119 rem_anchor_token(')');
8120 expect(')', end_error);
8122 if (function_type == NULL)
8125 function_parameter_t *parameter = function_type->parameters;
8126 call_argument_t *argument = call->arguments;
8127 if (!function_type->unspecified_parameters) {
8128 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8129 parameter = parameter->next, argument = argument->next) {
8130 check_call_argument(parameter, argument, ++pos);
8133 if (parameter != NULL) {
8134 errorf(HERE, "too few arguments to function '%E'", expression);
8135 } else if (argument != NULL && !function_type->variadic) {
8136 errorf(HERE, "too many arguments to function '%E'", expression);
8140 /* do default promotion */
8141 for (; argument != NULL; argument = argument->next) {
8142 type_t *type = argument->expression->base.type;
8144 type = get_default_promoted_type(type);
8146 argument->expression
8147 = create_implicit_cast(argument->expression, type);
8150 check_format(&result->call);
8152 if (warning.aggregate_return &&
8153 is_type_compound(skip_typeref(function_type->return_type))) {
8154 warningf(&result->base.source_position,
8155 "function call has aggregate value");
8162 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8164 static bool same_compound_type(const type_t *type1, const type_t *type2)
8167 is_type_compound(type1) &&
8168 type1->kind == type2->kind &&
8169 type1->compound.compound == type2->compound.compound;
8172 static expression_t const *get_reference_address(expression_t const *expr)
8174 bool regular_take_address = true;
8176 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8177 expr = expr->unary.value;
8179 regular_take_address = false;
8182 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8185 expr = expr->unary.value;
8188 if (expr->kind != EXPR_REFERENCE)
8191 /* special case for functions which are automatically converted to a
8192 * pointer to function without an extra TAKE_ADDRESS operation */
8193 if (!regular_take_address &&
8194 expr->reference.entity->kind != ENTITY_FUNCTION) {
8201 static void warn_reference_address_as_bool(expression_t const* expr)
8203 if (!warning.address)
8206 expr = get_reference_address(expr);
8208 warningf(&expr->base.source_position,
8209 "the address of '%Y' will always evaluate as 'true'",
8210 expr->reference.entity->base.symbol);
8214 static void warn_assignment_in_condition(const expression_t *const expr)
8216 if (!warning.parentheses)
8218 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8220 if (expr->base.parenthesized)
8222 warningf(&expr->base.source_position,
8223 "suggest parentheses around assignment used as truth value");
8226 static void semantic_condition(expression_t const *const expr,
8227 char const *const context)
8229 type_t *const type = skip_typeref(expr->base.type);
8230 if (is_type_scalar(type)) {
8231 warn_reference_address_as_bool(expr);
8232 warn_assignment_in_condition(expr);
8233 } else if (is_type_valid(type)) {
8234 errorf(&expr->base.source_position,
8235 "%s must have scalar type", context);
8240 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8242 * @param expression the conditional expression
8244 static expression_t *parse_conditional_expression(expression_t *expression)
8246 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8248 conditional_expression_t *conditional = &result->conditional;
8249 conditional->condition = expression;
8252 add_anchor_token(':');
8254 /* §6.5.15:2 The first operand shall have scalar type. */
8255 semantic_condition(expression, "condition of conditional operator");
8257 expression_t *true_expression = expression;
8258 bool gnu_cond = false;
8259 if (GNU_MODE && token.type == ':') {
8262 true_expression = parse_expression();
8264 rem_anchor_token(':');
8265 expect(':', end_error);
8267 expression_t *false_expression =
8268 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8270 type_t *const orig_true_type = true_expression->base.type;
8271 type_t *const orig_false_type = false_expression->base.type;
8272 type_t *const true_type = skip_typeref(orig_true_type);
8273 type_t *const false_type = skip_typeref(orig_false_type);
8276 type_t *result_type;
8277 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8278 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8279 /* ISO/IEC 14882:1998(E) §5.16:2 */
8280 if (true_expression->kind == EXPR_UNARY_THROW) {
8281 result_type = false_type;
8282 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8283 result_type = true_type;
8285 if (warning.other && (
8286 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8287 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8289 warningf(&conditional->base.source_position,
8290 "ISO C forbids conditional expression with only one void side");
8292 result_type = type_void;
8294 } else if (is_type_arithmetic(true_type)
8295 && is_type_arithmetic(false_type)) {
8296 result_type = semantic_arithmetic(true_type, false_type);
8298 true_expression = create_implicit_cast(true_expression, result_type);
8299 false_expression = create_implicit_cast(false_expression, result_type);
8301 conditional->true_expression = true_expression;
8302 conditional->false_expression = false_expression;
8303 conditional->base.type = result_type;
8304 } else if (same_compound_type(true_type, false_type)) {
8305 /* just take 1 of the 2 types */
8306 result_type = true_type;
8307 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8308 type_t *pointer_type;
8310 expression_t *other_expression;
8311 if (is_type_pointer(true_type) &&
8312 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8313 pointer_type = true_type;
8314 other_type = false_type;
8315 other_expression = false_expression;
8317 pointer_type = false_type;
8318 other_type = true_type;
8319 other_expression = true_expression;
8322 if (is_null_pointer_constant(other_expression)) {
8323 result_type = pointer_type;
8324 } else if (is_type_pointer(other_type)) {
8325 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8326 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8329 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8330 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8332 } else if (types_compatible(get_unqualified_type(to1),
8333 get_unqualified_type(to2))) {
8336 if (warning.other) {
8337 warningf(&conditional->base.source_position,
8338 "pointer types '%T' and '%T' in conditional expression are incompatible",
8339 true_type, false_type);
8344 type_t *const type =
8345 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8346 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8347 } else if (is_type_integer(other_type)) {
8348 if (warning.other) {
8349 warningf(&conditional->base.source_position,
8350 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8352 result_type = pointer_type;
8354 if (is_type_valid(other_type)) {
8355 type_error_incompatible("while parsing conditional",
8356 &expression->base.source_position, true_type, false_type);
8358 result_type = type_error_type;
8361 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8362 type_error_incompatible("while parsing conditional",
8363 &conditional->base.source_position, true_type,
8366 result_type = type_error_type;
8369 conditional->true_expression
8370 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8371 conditional->false_expression
8372 = create_implicit_cast(false_expression, result_type);
8373 conditional->base.type = result_type;
8378 * Parse an extension expression.
8380 static expression_t *parse_extension(void)
8382 eat(T___extension__);
8384 bool old_gcc_extension = in_gcc_extension;
8385 in_gcc_extension = true;
8386 expression_t *expression = parse_sub_expression(PREC_UNARY);
8387 in_gcc_extension = old_gcc_extension;
8392 * Parse a __builtin_classify_type() expression.
8394 static expression_t *parse_builtin_classify_type(void)
8396 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8397 result->base.type = type_int;
8399 eat(T___builtin_classify_type);
8401 expect('(', end_error);
8402 add_anchor_token(')');
8403 expression_t *expression = parse_expression();
8404 rem_anchor_token(')');
8405 expect(')', end_error);
8406 result->classify_type.type_expression = expression;
8410 return create_invalid_expression();
8414 * Parse a delete expression
8415 * ISO/IEC 14882:1998(E) §5.3.5
8417 static expression_t *parse_delete(void)
8419 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8420 result->base.type = type_void;
8424 if (token.type == '[') {
8426 result->kind = EXPR_UNARY_DELETE_ARRAY;
8427 expect(']', end_error);
8431 expression_t *const value = parse_sub_expression(PREC_CAST);
8432 result->unary.value = value;
8434 type_t *const type = skip_typeref(value->base.type);
8435 if (!is_type_pointer(type)) {
8436 if (is_type_valid(type)) {
8437 errorf(&value->base.source_position,
8438 "operand of delete must have pointer type");
8440 } else if (warning.other &&
8441 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8442 warningf(&value->base.source_position,
8443 "deleting 'void*' is undefined");
8450 * Parse a throw expression
8451 * ISO/IEC 14882:1998(E) §15:1
8453 static expression_t *parse_throw(void)
8455 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8456 result->base.type = type_void;
8460 expression_t *value = NULL;
8461 switch (token.type) {
8463 value = parse_assignment_expression();
8464 /* ISO/IEC 14882:1998(E) §15.1:3 */
8465 type_t *const orig_type = value->base.type;
8466 type_t *const type = skip_typeref(orig_type);
8467 if (is_type_incomplete(type)) {
8468 errorf(&value->base.source_position,
8469 "cannot throw object of incomplete type '%T'", orig_type);
8470 } else if (is_type_pointer(type)) {
8471 type_t *const points_to = skip_typeref(type->pointer.points_to);
8472 if (is_type_incomplete(points_to) &&
8473 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8474 errorf(&value->base.source_position,
8475 "cannot throw pointer to incomplete type '%T'", orig_type);
8483 result->unary.value = value;
8488 static bool check_pointer_arithmetic(const source_position_t *source_position,
8489 type_t *pointer_type,
8490 type_t *orig_pointer_type)
8492 type_t *points_to = pointer_type->pointer.points_to;
8493 points_to = skip_typeref(points_to);
8495 if (is_type_incomplete(points_to)) {
8496 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8497 errorf(source_position,
8498 "arithmetic with pointer to incomplete type '%T' not allowed",
8501 } else if (warning.pointer_arith) {
8502 warningf(source_position,
8503 "pointer of type '%T' used in arithmetic",
8506 } else if (is_type_function(points_to)) {
8508 errorf(source_position,
8509 "arithmetic with pointer to function type '%T' not allowed",
8512 } else if (warning.pointer_arith) {
8513 warningf(source_position,
8514 "pointer to a function '%T' used in arithmetic",
8521 static bool is_lvalue(const expression_t *expression)
8523 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8524 switch (expression->kind) {
8525 case EXPR_ARRAY_ACCESS:
8526 case EXPR_COMPOUND_LITERAL:
8527 case EXPR_REFERENCE:
8529 case EXPR_UNARY_DEREFERENCE:
8533 type_t *type = skip_typeref(expression->base.type);
8535 /* ISO/IEC 14882:1998(E) §3.10:3 */
8536 is_type_reference(type) ||
8537 /* Claim it is an lvalue, if the type is invalid. There was a parse
8538 * error before, which maybe prevented properly recognizing it as
8540 !is_type_valid(type);
8545 static void semantic_incdec(unary_expression_t *expression)
8547 type_t *const orig_type = expression->value->base.type;
8548 type_t *const type = skip_typeref(orig_type);
8549 if (is_type_pointer(type)) {
8550 if (!check_pointer_arithmetic(&expression->base.source_position,
8554 } else if (!is_type_real(type) && is_type_valid(type)) {
8555 /* TODO: improve error message */
8556 errorf(&expression->base.source_position,
8557 "operation needs an arithmetic or pointer type");
8560 if (!is_lvalue(expression->value)) {
8561 /* TODO: improve error message */
8562 errorf(&expression->base.source_position, "lvalue required as operand");
8564 expression->base.type = orig_type;
8567 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8569 type_t *const orig_type = expression->value->base.type;
8570 type_t *const type = skip_typeref(orig_type);
8571 if (!is_type_arithmetic(type)) {
8572 if (is_type_valid(type)) {
8573 /* TODO: improve error message */
8574 errorf(&expression->base.source_position,
8575 "operation needs an arithmetic type");
8580 expression->base.type = orig_type;
8583 static void semantic_unexpr_plus(unary_expression_t *expression)
8585 semantic_unexpr_arithmetic(expression);
8586 if (warning.traditional)
8587 warningf(&expression->base.source_position,
8588 "traditional C rejects the unary plus operator");
8591 static void semantic_not(unary_expression_t *expression)
8593 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8594 semantic_condition(expression->value, "operand of !");
8595 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8598 static void semantic_unexpr_integer(unary_expression_t *expression)
8600 type_t *const orig_type = expression->value->base.type;
8601 type_t *const type = skip_typeref(orig_type);
8602 if (!is_type_integer(type)) {
8603 if (is_type_valid(type)) {
8604 errorf(&expression->base.source_position,
8605 "operand of ~ must be of integer type");
8610 expression->base.type = orig_type;
8613 static void semantic_dereference(unary_expression_t *expression)
8615 type_t *const orig_type = expression->value->base.type;
8616 type_t *const type = skip_typeref(orig_type);
8617 if (!is_type_pointer(type)) {
8618 if (is_type_valid(type)) {
8619 errorf(&expression->base.source_position,
8620 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8625 type_t *result_type = type->pointer.points_to;
8626 result_type = automatic_type_conversion(result_type);
8627 expression->base.type = result_type;
8631 * Record that an address is taken (expression represents an lvalue).
8633 * @param expression the expression
8634 * @param may_be_register if true, the expression might be an register
8636 static void set_address_taken(expression_t *expression, bool may_be_register)
8638 if (expression->kind != EXPR_REFERENCE)
8641 entity_t *const entity = expression->reference.entity;
8643 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8646 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8647 && !may_be_register) {
8648 errorf(&expression->base.source_position,
8649 "address of register %s '%Y' requested",
8650 get_entity_kind_name(entity->kind), entity->base.symbol);
8653 if (entity->kind == ENTITY_VARIABLE) {
8654 entity->variable.address_taken = true;
8656 assert(entity->kind == ENTITY_PARAMETER);
8657 entity->parameter.address_taken = true;
8662 * Check the semantic of the address taken expression.
8664 static void semantic_take_addr(unary_expression_t *expression)
8666 expression_t *value = expression->value;
8667 value->base.type = revert_automatic_type_conversion(value);
8669 type_t *orig_type = value->base.type;
8670 type_t *type = skip_typeref(orig_type);
8671 if (!is_type_valid(type))
8675 if (!is_lvalue(value)) {
8676 errorf(&expression->base.source_position, "'&' requires an lvalue");
8678 if (type->kind == TYPE_BITFIELD) {
8679 errorf(&expression->base.source_position,
8680 "'&' not allowed on object with bitfield type '%T'",
8684 set_address_taken(value, false);
8686 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8689 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8690 static expression_t *parse_##unexpression_type(void) \
8692 expression_t *unary_expression \
8693 = allocate_expression_zero(unexpression_type); \
8695 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8697 sfunc(&unary_expression->unary); \
8699 return unary_expression; \
8702 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8703 semantic_unexpr_arithmetic)
8704 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8705 semantic_unexpr_plus)
8706 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8708 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8709 semantic_dereference)
8710 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8712 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8713 semantic_unexpr_integer)
8714 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8716 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8719 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8721 static expression_t *parse_##unexpression_type(expression_t *left) \
8723 expression_t *unary_expression \
8724 = allocate_expression_zero(unexpression_type); \
8726 unary_expression->unary.value = left; \
8728 sfunc(&unary_expression->unary); \
8730 return unary_expression; \
8733 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8734 EXPR_UNARY_POSTFIX_INCREMENT,
8736 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8737 EXPR_UNARY_POSTFIX_DECREMENT,
8740 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8742 /* TODO: handle complex + imaginary types */
8744 type_left = get_unqualified_type(type_left);
8745 type_right = get_unqualified_type(type_right);
8747 /* § 6.3.1.8 Usual arithmetic conversions */
8748 if (type_left == type_long_double || type_right == type_long_double) {
8749 return type_long_double;
8750 } else if (type_left == type_double || type_right == type_double) {
8752 } else if (type_left == type_float || type_right == type_float) {
8756 type_left = promote_integer(type_left);
8757 type_right = promote_integer(type_right);
8759 if (type_left == type_right)
8762 bool const signed_left = is_type_signed(type_left);
8763 bool const signed_right = is_type_signed(type_right);
8764 int const rank_left = get_rank(type_left);
8765 int const rank_right = get_rank(type_right);
8767 if (signed_left == signed_right)
8768 return rank_left >= rank_right ? type_left : type_right;
8777 u_rank = rank_right;
8778 u_type = type_right;
8780 s_rank = rank_right;
8781 s_type = type_right;
8786 if (u_rank >= s_rank)
8789 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8791 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8792 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8796 case ATOMIC_TYPE_INT: return type_unsigned_int;
8797 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8798 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8800 default: panic("invalid atomic type");
8805 * Check the semantic restrictions for a binary expression.
8807 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8809 expression_t *const left = expression->left;
8810 expression_t *const right = expression->right;
8811 type_t *const orig_type_left = left->base.type;
8812 type_t *const orig_type_right = right->base.type;
8813 type_t *const type_left = skip_typeref(orig_type_left);
8814 type_t *const type_right = skip_typeref(orig_type_right);
8816 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8817 /* TODO: improve error message */
8818 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8819 errorf(&expression->base.source_position,
8820 "operation needs arithmetic types");
8825 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8826 expression->left = create_implicit_cast(left, arithmetic_type);
8827 expression->right = create_implicit_cast(right, arithmetic_type);
8828 expression->base.type = arithmetic_type;
8831 static void warn_div_by_zero(binary_expression_t const *const expression)
8833 if (!warning.div_by_zero ||
8834 !is_type_integer(expression->base.type))
8837 expression_t const *const right = expression->right;
8838 /* The type of the right operand can be different for /= */
8839 if (is_type_integer(right->base.type) &&
8840 is_constant_expression(right) &&
8841 fold_constant(right) == 0) {
8842 warningf(&expression->base.source_position, "division by zero");
8847 * Check the semantic restrictions for a div/mod expression.
8849 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8850 semantic_binexpr_arithmetic(expression);
8851 warn_div_by_zero(expression);
8854 static void warn_addsub_in_shift(const expression_t *const expr)
8856 if (expr->base.parenthesized)
8860 switch (expr->kind) {
8861 case EXPR_BINARY_ADD: op = '+'; break;
8862 case EXPR_BINARY_SUB: op = '-'; break;
8866 warningf(&expr->base.source_position,
8867 "suggest parentheses around '%c' inside shift", op);
8870 static void semantic_shift_op(binary_expression_t *expression)
8872 expression_t *const left = expression->left;
8873 expression_t *const right = expression->right;
8874 type_t *const orig_type_left = left->base.type;
8875 type_t *const orig_type_right = right->base.type;
8876 type_t * type_left = skip_typeref(orig_type_left);
8877 type_t * type_right = skip_typeref(orig_type_right);
8879 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8880 /* TODO: improve error message */
8881 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8882 errorf(&expression->base.source_position,
8883 "operands of shift operation must have integer types");
8888 if (warning.parentheses) {
8889 warn_addsub_in_shift(left);
8890 warn_addsub_in_shift(right);
8893 type_left = promote_integer(type_left);
8894 type_right = promote_integer(type_right);
8896 expression->left = create_implicit_cast(left, type_left);
8897 expression->right = create_implicit_cast(right, type_right);
8898 expression->base.type = type_left;
8901 static void semantic_add(binary_expression_t *expression)
8903 expression_t *const left = expression->left;
8904 expression_t *const right = expression->right;
8905 type_t *const orig_type_left = left->base.type;
8906 type_t *const orig_type_right = right->base.type;
8907 type_t *const type_left = skip_typeref(orig_type_left);
8908 type_t *const type_right = skip_typeref(orig_type_right);
8911 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8912 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8913 expression->left = create_implicit_cast(left, arithmetic_type);
8914 expression->right = create_implicit_cast(right, arithmetic_type);
8915 expression->base.type = arithmetic_type;
8916 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8917 check_pointer_arithmetic(&expression->base.source_position,
8918 type_left, orig_type_left);
8919 expression->base.type = type_left;
8920 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8921 check_pointer_arithmetic(&expression->base.source_position,
8922 type_right, orig_type_right);
8923 expression->base.type = type_right;
8924 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8925 errorf(&expression->base.source_position,
8926 "invalid operands to binary + ('%T', '%T')",
8927 orig_type_left, orig_type_right);
8931 static void semantic_sub(binary_expression_t *expression)
8933 expression_t *const left = expression->left;
8934 expression_t *const right = expression->right;
8935 type_t *const orig_type_left = left->base.type;
8936 type_t *const orig_type_right = right->base.type;
8937 type_t *const type_left = skip_typeref(orig_type_left);
8938 type_t *const type_right = skip_typeref(orig_type_right);
8939 source_position_t const *const pos = &expression->base.source_position;
8942 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8943 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8944 expression->left = create_implicit_cast(left, arithmetic_type);
8945 expression->right = create_implicit_cast(right, arithmetic_type);
8946 expression->base.type = arithmetic_type;
8947 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8948 check_pointer_arithmetic(&expression->base.source_position,
8949 type_left, orig_type_left);
8950 expression->base.type = type_left;
8951 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8952 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8953 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8954 if (!types_compatible(unqual_left, unqual_right)) {
8956 "subtracting pointers to incompatible types '%T' and '%T'",
8957 orig_type_left, orig_type_right);
8958 } else if (!is_type_object(unqual_left)) {
8959 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8960 errorf(pos, "subtracting pointers to non-object types '%T'",
8962 } else if (warning.other) {
8963 warningf(pos, "subtracting pointers to void");
8966 expression->base.type = type_ptrdiff_t;
8967 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8968 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8969 orig_type_left, orig_type_right);
8973 static void warn_string_literal_address(expression_t const* expr)
8975 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8976 expr = expr->unary.value;
8977 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8979 expr = expr->unary.value;
8982 if (expr->kind == EXPR_STRING_LITERAL ||
8983 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8984 warningf(&expr->base.source_position,
8985 "comparison with string literal results in unspecified behaviour");
8989 static void warn_comparison_in_comparison(const expression_t *const expr)
8991 if (expr->base.parenthesized)
8993 switch (expr->base.kind) {
8994 case EXPR_BINARY_LESS:
8995 case EXPR_BINARY_GREATER:
8996 case EXPR_BINARY_LESSEQUAL:
8997 case EXPR_BINARY_GREATEREQUAL:
8998 case EXPR_BINARY_NOTEQUAL:
8999 case EXPR_BINARY_EQUAL:
9000 warningf(&expr->base.source_position,
9001 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9009 * Check the semantics of comparison expressions.
9011 * @param expression The expression to check.
9013 static void semantic_comparison(binary_expression_t *expression)
9015 expression_t *left = expression->left;
9016 expression_t *right = expression->right;
9018 if (warning.address) {
9019 warn_string_literal_address(left);
9020 warn_string_literal_address(right);
9022 expression_t const* const func_left = get_reference_address(left);
9023 if (func_left != NULL && is_null_pointer_constant(right)) {
9024 warningf(&expression->base.source_position,
9025 "the address of '%Y' will never be NULL",
9026 func_left->reference.entity->base.symbol);
9029 expression_t const* const func_right = get_reference_address(right);
9030 if (func_right != NULL && is_null_pointer_constant(right)) {
9031 warningf(&expression->base.source_position,
9032 "the address of '%Y' will never be NULL",
9033 func_right->reference.entity->base.symbol);
9037 if (warning.parentheses) {
9038 warn_comparison_in_comparison(left);
9039 warn_comparison_in_comparison(right);
9042 type_t *orig_type_left = left->base.type;
9043 type_t *orig_type_right = right->base.type;
9044 type_t *type_left = skip_typeref(orig_type_left);
9045 type_t *type_right = skip_typeref(orig_type_right);
9047 /* TODO non-arithmetic types */
9048 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9049 /* test for signed vs unsigned compares */
9050 if (warning.sign_compare &&
9051 (expression->base.kind != EXPR_BINARY_EQUAL &&
9052 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
9053 (is_type_signed(type_left) != is_type_signed(type_right))) {
9055 /* check if 1 of the operands is a constant, in this case we just
9056 * check wether we can safely represent the resulting constant in
9057 * the type of the other operand. */
9058 expression_t *const_expr = NULL;
9059 expression_t *other_expr = NULL;
9061 if (is_constant_expression(left)) {
9064 } else if (is_constant_expression(right)) {
9069 if (const_expr != NULL) {
9070 type_t *other_type = skip_typeref(other_expr->base.type);
9071 long val = fold_constant(const_expr);
9072 /* TODO: check if val can be represented by other_type */
9076 warningf(&expression->base.source_position,
9077 "comparison between signed and unsigned");
9079 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9080 expression->left = create_implicit_cast(left, arithmetic_type);
9081 expression->right = create_implicit_cast(right, arithmetic_type);
9082 expression->base.type = arithmetic_type;
9083 if (warning.float_equal &&
9084 (expression->base.kind == EXPR_BINARY_EQUAL ||
9085 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9086 is_type_float(arithmetic_type)) {
9087 warningf(&expression->base.source_position,
9088 "comparing floating point with == or != is unsafe");
9090 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9091 /* TODO check compatibility */
9092 } else if (is_type_pointer(type_left)) {
9093 expression->right = create_implicit_cast(right, type_left);
9094 } else if (is_type_pointer(type_right)) {
9095 expression->left = create_implicit_cast(left, type_right);
9096 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9097 type_error_incompatible("invalid operands in comparison",
9098 &expression->base.source_position,
9099 type_left, type_right);
9101 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9105 * Checks if a compound type has constant fields.
9107 static bool has_const_fields(const compound_type_t *type)
9109 compound_t *compound = type->compound;
9110 entity_t *entry = compound->members.entities;
9112 for (; entry != NULL; entry = entry->base.next) {
9113 if (!is_declaration(entry))
9116 const type_t *decl_type = skip_typeref(entry->declaration.type);
9117 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9124 static bool is_valid_assignment_lhs(expression_t const* const left)
9126 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9127 type_t *const type_left = skip_typeref(orig_type_left);
9129 if (!is_lvalue(left)) {
9130 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9135 if (left->kind == EXPR_REFERENCE
9136 && left->reference.entity->kind == ENTITY_FUNCTION) {
9137 errorf(HERE, "cannot assign to function '%E'", left);
9141 if (is_type_array(type_left)) {
9142 errorf(HERE, "cannot assign to array '%E'", left);
9145 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9146 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9150 if (is_type_incomplete(type_left)) {
9151 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9152 left, orig_type_left);
9155 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9156 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9157 left, orig_type_left);
9164 static void semantic_arithmetic_assign(binary_expression_t *expression)
9166 expression_t *left = expression->left;
9167 expression_t *right = expression->right;
9168 type_t *orig_type_left = left->base.type;
9169 type_t *orig_type_right = right->base.type;
9171 if (!is_valid_assignment_lhs(left))
9174 type_t *type_left = skip_typeref(orig_type_left);
9175 type_t *type_right = skip_typeref(orig_type_right);
9177 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9178 /* TODO: improve error message */
9179 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9180 errorf(&expression->base.source_position,
9181 "operation needs arithmetic types");
9186 /* combined instructions are tricky. We can't create an implicit cast on
9187 * the left side, because we need the uncasted form for the store.
9188 * The ast2firm pass has to know that left_type must be right_type
9189 * for the arithmetic operation and create a cast by itself */
9190 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9191 expression->right = create_implicit_cast(right, arithmetic_type);
9192 expression->base.type = type_left;
9195 static void semantic_divmod_assign(binary_expression_t *expression)
9197 semantic_arithmetic_assign(expression);
9198 warn_div_by_zero(expression);
9201 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9203 expression_t *const left = expression->left;
9204 expression_t *const right = expression->right;
9205 type_t *const orig_type_left = left->base.type;
9206 type_t *const orig_type_right = right->base.type;
9207 type_t *const type_left = skip_typeref(orig_type_left);
9208 type_t *const type_right = skip_typeref(orig_type_right);
9210 if (!is_valid_assignment_lhs(left))
9213 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9214 /* combined instructions are tricky. We can't create an implicit cast on
9215 * the left side, because we need the uncasted form for the store.
9216 * The ast2firm pass has to know that left_type must be right_type
9217 * for the arithmetic operation and create a cast by itself */
9218 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9219 expression->right = create_implicit_cast(right, arithmetic_type);
9220 expression->base.type = type_left;
9221 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9222 check_pointer_arithmetic(&expression->base.source_position,
9223 type_left, orig_type_left);
9224 expression->base.type = type_left;
9225 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9226 errorf(&expression->base.source_position,
9227 "incompatible types '%T' and '%T' in assignment",
9228 orig_type_left, orig_type_right);
9232 static void warn_logical_and_within_or(const expression_t *const expr)
9234 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9236 if (expr->base.parenthesized)
9238 warningf(&expr->base.source_position,
9239 "suggest parentheses around && within ||");
9243 * Check the semantic restrictions of a logical expression.
9245 static void semantic_logical_op(binary_expression_t *expression)
9247 /* §6.5.13:2 Each of the operands shall have scalar type.
9248 * §6.5.14:2 Each of the operands shall have scalar type. */
9249 semantic_condition(expression->left, "left operand of logical operator");
9250 semantic_condition(expression->right, "right operand of logical operator");
9251 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9252 warning.parentheses) {
9253 warn_logical_and_within_or(expression->left);
9254 warn_logical_and_within_or(expression->right);
9256 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9260 * Check the semantic restrictions of a binary assign expression.
9262 static void semantic_binexpr_assign(binary_expression_t *expression)
9264 expression_t *left = expression->left;
9265 type_t *orig_type_left = left->base.type;
9267 if (!is_valid_assignment_lhs(left))
9270 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9271 report_assign_error(error, orig_type_left, expression->right,
9272 "assignment", &left->base.source_position);
9273 expression->right = create_implicit_cast(expression->right, orig_type_left);
9274 expression->base.type = orig_type_left;
9278 * Determine if the outermost operation (or parts thereof) of the given
9279 * expression has no effect in order to generate a warning about this fact.
9280 * Therefore in some cases this only examines some of the operands of the
9281 * expression (see comments in the function and examples below).
9283 * f() + 23; // warning, because + has no effect
9284 * x || f(); // no warning, because x controls execution of f()
9285 * x ? y : f(); // warning, because y has no effect
9286 * (void)x; // no warning to be able to suppress the warning
9287 * This function can NOT be used for an "expression has definitely no effect"-
9289 static bool expression_has_effect(const expression_t *const expr)
9291 switch (expr->kind) {
9292 case EXPR_UNKNOWN: break;
9293 case EXPR_INVALID: return true; /* do NOT warn */
9294 case EXPR_REFERENCE: return false;
9295 case EXPR_REFERENCE_ENUM_VALUE: return false;
9296 /* suppress the warning for microsoft __noop operations */
9297 case EXPR_CONST: return expr->conste.is_ms_noop;
9298 case EXPR_CHARACTER_CONSTANT: return false;
9299 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9300 case EXPR_STRING_LITERAL: return false;
9301 case EXPR_WIDE_STRING_LITERAL: return false;
9302 case EXPR_LABEL_ADDRESS: return false;
9305 const call_expression_t *const call = &expr->call;
9306 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9309 switch (call->function->builtin_symbol.symbol->ID) {
9310 case T___builtin_va_end: return true;
9311 default: return false;
9315 /* Generate the warning if either the left or right hand side of a
9316 * conditional expression has no effect */
9317 case EXPR_CONDITIONAL: {
9318 const conditional_expression_t *const cond = &expr->conditional;
9320 expression_has_effect(cond->true_expression) &&
9321 expression_has_effect(cond->false_expression);
9324 case EXPR_SELECT: return false;
9325 case EXPR_ARRAY_ACCESS: return false;
9326 case EXPR_SIZEOF: return false;
9327 case EXPR_CLASSIFY_TYPE: return false;
9328 case EXPR_ALIGNOF: return false;
9330 case EXPR_FUNCNAME: return false;
9331 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9332 case EXPR_BUILTIN_CONSTANT_P: return false;
9333 case EXPR_BUILTIN_PREFETCH: return true;
9334 case EXPR_OFFSETOF: return false;
9335 case EXPR_VA_START: return true;
9336 case EXPR_VA_ARG: return true;
9337 case EXPR_STATEMENT: return true; // TODO
9338 case EXPR_COMPOUND_LITERAL: return false;
9340 case EXPR_UNARY_NEGATE: return false;
9341 case EXPR_UNARY_PLUS: return false;
9342 case EXPR_UNARY_BITWISE_NEGATE: return false;
9343 case EXPR_UNARY_NOT: return false;
9344 case EXPR_UNARY_DEREFERENCE: return false;
9345 case EXPR_UNARY_TAKE_ADDRESS: return false;
9346 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9347 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9348 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9349 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9351 /* Treat void casts as if they have an effect in order to being able to
9352 * suppress the warning */
9353 case EXPR_UNARY_CAST: {
9354 type_t *const type = skip_typeref(expr->base.type);
9355 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9358 case EXPR_UNARY_CAST_IMPLICIT: return true;
9359 case EXPR_UNARY_ASSUME: return true;
9360 case EXPR_UNARY_DELETE: return true;
9361 case EXPR_UNARY_DELETE_ARRAY: return true;
9362 case EXPR_UNARY_THROW: return true;
9364 case EXPR_BINARY_ADD: return false;
9365 case EXPR_BINARY_SUB: return false;
9366 case EXPR_BINARY_MUL: return false;
9367 case EXPR_BINARY_DIV: return false;
9368 case EXPR_BINARY_MOD: return false;
9369 case EXPR_BINARY_EQUAL: return false;
9370 case EXPR_BINARY_NOTEQUAL: return false;
9371 case EXPR_BINARY_LESS: return false;
9372 case EXPR_BINARY_LESSEQUAL: return false;
9373 case EXPR_BINARY_GREATER: return false;
9374 case EXPR_BINARY_GREATEREQUAL: return false;
9375 case EXPR_BINARY_BITWISE_AND: return false;
9376 case EXPR_BINARY_BITWISE_OR: return false;
9377 case EXPR_BINARY_BITWISE_XOR: return false;
9378 case EXPR_BINARY_SHIFTLEFT: return false;
9379 case EXPR_BINARY_SHIFTRIGHT: return false;
9380 case EXPR_BINARY_ASSIGN: return true;
9381 case EXPR_BINARY_MUL_ASSIGN: return true;
9382 case EXPR_BINARY_DIV_ASSIGN: return true;
9383 case EXPR_BINARY_MOD_ASSIGN: return true;
9384 case EXPR_BINARY_ADD_ASSIGN: return true;
9385 case EXPR_BINARY_SUB_ASSIGN: return true;
9386 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9387 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9388 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9389 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9390 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9392 /* Only examine the right hand side of && and ||, because the left hand
9393 * side already has the effect of controlling the execution of the right
9395 case EXPR_BINARY_LOGICAL_AND:
9396 case EXPR_BINARY_LOGICAL_OR:
9397 /* Only examine the right hand side of a comma expression, because the left
9398 * hand side has a separate warning */
9399 case EXPR_BINARY_COMMA:
9400 return expression_has_effect(expr->binary.right);
9402 case EXPR_BINARY_ISGREATER: return false;
9403 case EXPR_BINARY_ISGREATEREQUAL: return false;
9404 case EXPR_BINARY_ISLESS: return false;
9405 case EXPR_BINARY_ISLESSEQUAL: return false;
9406 case EXPR_BINARY_ISLESSGREATER: return false;
9407 case EXPR_BINARY_ISUNORDERED: return false;
9410 internal_errorf(HERE, "unexpected expression");
9413 static void semantic_comma(binary_expression_t *expression)
9415 if (warning.unused_value) {
9416 const expression_t *const left = expression->left;
9417 if (!expression_has_effect(left)) {
9418 warningf(&left->base.source_position,
9419 "left-hand operand of comma expression has no effect");
9422 expression->base.type = expression->right->base.type;
9426 * @param prec_r precedence of the right operand
9428 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9429 static expression_t *parse_##binexpression_type(expression_t *left) \
9431 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9432 binexpr->binary.left = left; \
9435 expression_t *right = parse_sub_expression(prec_r); \
9437 binexpr->binary.right = right; \
9438 sfunc(&binexpr->binary); \
9443 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9444 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9445 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9446 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9447 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9448 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9449 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9450 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9451 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9452 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9453 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9454 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9455 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9456 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9457 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9458 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9459 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9460 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9461 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9462 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9463 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9464 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9465 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9466 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9467 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9468 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9469 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9470 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9471 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9472 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9475 static expression_t *parse_sub_expression(precedence_t precedence)
9477 if (token.type < 0) {
9478 return expected_expression_error();
9481 expression_parser_function_t *parser
9482 = &expression_parsers[token.type];
9483 source_position_t source_position = token.source_position;
9486 if (parser->parser != NULL) {
9487 left = parser->parser();
9489 left = parse_primary_expression();
9491 assert(left != NULL);
9492 left->base.source_position = source_position;
9495 if (token.type < 0) {
9496 return expected_expression_error();
9499 parser = &expression_parsers[token.type];
9500 if (parser->infix_parser == NULL)
9502 if (parser->infix_precedence < precedence)
9505 left = parser->infix_parser(left);
9507 assert(left != NULL);
9508 assert(left->kind != EXPR_UNKNOWN);
9509 left->base.source_position = source_position;
9516 * Parse an expression.
9518 static expression_t *parse_expression(void)
9520 return parse_sub_expression(PREC_EXPRESSION);
9524 * Register a parser for a prefix-like operator.
9526 * @param parser the parser function
9527 * @param token_type the token type of the prefix token
9529 static void register_expression_parser(parse_expression_function parser,
9532 expression_parser_function_t *entry = &expression_parsers[token_type];
9534 if (entry->parser != NULL) {
9535 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9536 panic("trying to register multiple expression parsers for a token");
9538 entry->parser = parser;
9542 * Register a parser for an infix operator with given precedence.
9544 * @param parser the parser function
9545 * @param token_type the token type of the infix operator
9546 * @param precedence the precedence of the operator
9548 static void register_infix_parser(parse_expression_infix_function parser,
9549 int token_type, unsigned precedence)
9551 expression_parser_function_t *entry = &expression_parsers[token_type];
9553 if (entry->infix_parser != NULL) {
9554 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9555 panic("trying to register multiple infix expression parsers for a "
9558 entry->infix_parser = parser;
9559 entry->infix_precedence = precedence;
9563 * Initialize the expression parsers.
9565 static void init_expression_parsers(void)
9567 memset(&expression_parsers, 0, sizeof(expression_parsers));
9569 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9570 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9571 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9572 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9573 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9574 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9575 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9576 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9577 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9578 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9579 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9580 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9581 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9582 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9583 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9584 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9585 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9586 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9587 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9588 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9589 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9590 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9591 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9592 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9593 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9594 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9595 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9596 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9597 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9598 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9599 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9600 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9601 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9602 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9603 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9604 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9605 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9607 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9608 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9609 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9610 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9611 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9612 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9613 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9614 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9615 register_expression_parser(parse_sizeof, T_sizeof);
9616 register_expression_parser(parse_alignof, T___alignof__);
9617 register_expression_parser(parse_extension, T___extension__);
9618 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9619 register_expression_parser(parse_delete, T_delete);
9620 register_expression_parser(parse_throw, T_throw);
9624 * Parse a asm statement arguments specification.
9626 static asm_argument_t *parse_asm_arguments(bool is_out)
9628 asm_argument_t *result = NULL;
9629 asm_argument_t **anchor = &result;
9631 while (token.type == T_STRING_LITERAL || token.type == '[') {
9632 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9633 memset(argument, 0, sizeof(argument[0]));
9635 if (token.type == '[') {
9637 if (token.type != T_IDENTIFIER) {
9638 parse_error_expected("while parsing asm argument",
9639 T_IDENTIFIER, NULL);
9642 argument->symbol = token.v.symbol;
9644 expect(']', end_error);
9647 argument->constraints = parse_string_literals();
9648 expect('(', end_error);
9649 add_anchor_token(')');
9650 expression_t *expression = parse_expression();
9651 rem_anchor_token(')');
9653 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9654 * change size or type representation (e.g. int -> long is ok, but
9655 * int -> float is not) */
9656 if (expression->kind == EXPR_UNARY_CAST) {
9657 type_t *const type = expression->base.type;
9658 type_kind_t const kind = type->kind;
9659 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9662 if (kind == TYPE_ATOMIC) {
9663 atomic_type_kind_t const akind = type->atomic.akind;
9664 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9665 size = get_atomic_type_size(akind);
9667 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9668 size = get_atomic_type_size(get_intptr_kind());
9672 expression_t *const value = expression->unary.value;
9673 type_t *const value_type = value->base.type;
9674 type_kind_t const value_kind = value_type->kind;
9676 unsigned value_flags;
9677 unsigned value_size;
9678 if (value_kind == TYPE_ATOMIC) {
9679 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9680 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9681 value_size = get_atomic_type_size(value_akind);
9682 } else if (value_kind == TYPE_POINTER) {
9683 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9684 value_size = get_atomic_type_size(get_intptr_kind());
9689 if (value_flags != flags || value_size != size)
9693 } while (expression->kind == EXPR_UNARY_CAST);
9697 if (!is_lvalue(expression)) {
9698 errorf(&expression->base.source_position,
9699 "asm output argument is not an lvalue");
9702 if (argument->constraints.begin[0] == '+')
9703 mark_vars_read(expression, NULL);
9705 mark_vars_read(expression, NULL);
9707 argument->expression = expression;
9708 expect(')', end_error);
9710 set_address_taken(expression, true);
9713 anchor = &argument->next;
9715 if (token.type != ',')
9726 * Parse a asm statement clobber specification.
9728 static asm_clobber_t *parse_asm_clobbers(void)
9730 asm_clobber_t *result = NULL;
9731 asm_clobber_t *last = NULL;
9733 while (token.type == T_STRING_LITERAL) {
9734 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9735 clobber->clobber = parse_string_literals();
9738 last->next = clobber;
9744 if (token.type != ',')
9753 * Parse an asm statement.
9755 static statement_t *parse_asm_statement(void)
9757 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9758 asm_statement_t *asm_statement = &statement->asms;
9762 if (token.type == T_volatile) {
9764 asm_statement->is_volatile = true;
9767 expect('(', end_error);
9768 add_anchor_token(')');
9769 add_anchor_token(':');
9770 asm_statement->asm_text = parse_string_literals();
9772 if (token.type != ':') {
9773 rem_anchor_token(':');
9778 asm_statement->outputs = parse_asm_arguments(true);
9779 if (token.type != ':') {
9780 rem_anchor_token(':');
9785 asm_statement->inputs = parse_asm_arguments(false);
9786 if (token.type != ':') {
9787 rem_anchor_token(':');
9790 rem_anchor_token(':');
9793 asm_statement->clobbers = parse_asm_clobbers();
9796 rem_anchor_token(')');
9797 expect(')', end_error);
9798 expect(';', end_error);
9800 if (asm_statement->outputs == NULL) {
9801 /* GCC: An 'asm' instruction without any output operands will be treated
9802 * identically to a volatile 'asm' instruction. */
9803 asm_statement->is_volatile = true;
9808 return create_invalid_statement();
9812 * Parse a case statement.
9814 static statement_t *parse_case_statement(void)
9816 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9817 source_position_t *const pos = &statement->base.source_position;
9821 expression_t *const expression = parse_expression();
9822 statement->case_label.expression = expression;
9823 if (!is_constant_expression(expression)) {
9824 /* This check does not prevent the error message in all cases of an
9825 * prior error while parsing the expression. At least it catches the
9826 * common case of a mistyped enum entry. */
9827 if (is_type_valid(skip_typeref(expression->base.type))) {
9828 errorf(pos, "case label does not reduce to an integer constant");
9830 statement->case_label.is_bad = true;
9832 long const val = fold_constant(expression);
9833 statement->case_label.first_case = val;
9834 statement->case_label.last_case = val;
9838 if (token.type == T_DOTDOTDOT) {
9840 expression_t *const end_range = parse_expression();
9841 statement->case_label.end_range = end_range;
9842 if (!is_constant_expression(end_range)) {
9843 /* This check does not prevent the error message in all cases of an
9844 * prior error while parsing the expression. At least it catches the
9845 * common case of a mistyped enum entry. */
9846 if (is_type_valid(skip_typeref(end_range->base.type))) {
9847 errorf(pos, "case range does not reduce to an integer constant");
9849 statement->case_label.is_bad = true;
9851 long const val = fold_constant(end_range);
9852 statement->case_label.last_case = val;
9854 if (warning.other && val < statement->case_label.first_case) {
9855 statement->case_label.is_empty_range = true;
9856 warningf(pos, "empty range specified");
9862 PUSH_PARENT(statement);
9864 expect(':', end_error);
9867 if (current_switch != NULL) {
9868 if (! statement->case_label.is_bad) {
9869 /* Check for duplicate case values */
9870 case_label_statement_t *c = &statement->case_label;
9871 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9872 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9875 if (c->last_case < l->first_case || c->first_case > l->last_case)
9878 errorf(pos, "duplicate case value (previously used %P)",
9879 &l->base.source_position);
9883 /* link all cases into the switch statement */
9884 if (current_switch->last_case == NULL) {
9885 current_switch->first_case = &statement->case_label;
9887 current_switch->last_case->next = &statement->case_label;
9889 current_switch->last_case = &statement->case_label;
9891 errorf(pos, "case label not within a switch statement");
9894 statement_t *const inner_stmt = parse_statement();
9895 statement->case_label.statement = inner_stmt;
9896 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9897 errorf(&inner_stmt->base.source_position, "declaration after case label");
9905 * Parse a default statement.
9907 static statement_t *parse_default_statement(void)
9909 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9913 PUSH_PARENT(statement);
9915 expect(':', end_error);
9916 if (current_switch != NULL) {
9917 const case_label_statement_t *def_label = current_switch->default_label;
9918 if (def_label != NULL) {
9919 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9920 &def_label->base.source_position);
9922 current_switch->default_label = &statement->case_label;
9924 /* link all cases into the switch statement */
9925 if (current_switch->last_case == NULL) {
9926 current_switch->first_case = &statement->case_label;
9928 current_switch->last_case->next = &statement->case_label;
9930 current_switch->last_case = &statement->case_label;
9933 errorf(&statement->base.source_position,
9934 "'default' label not within a switch statement");
9937 statement_t *const inner_stmt = parse_statement();
9938 statement->case_label.statement = inner_stmt;
9939 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9940 errorf(&inner_stmt->base.source_position, "declaration after default label");
9947 return create_invalid_statement();
9951 * Parse a label statement.
9953 static statement_t *parse_label_statement(void)
9955 assert(token.type == T_IDENTIFIER);
9956 symbol_t *symbol = token.v.symbol;
9957 label_t *label = get_label(symbol);
9959 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9960 statement->label.label = label;
9964 PUSH_PARENT(statement);
9966 /* if statement is already set then the label is defined twice,
9967 * otherwise it was just mentioned in a goto/local label declaration so far
9969 if (label->statement != NULL) {
9970 errorf(HERE, "duplicate label '%Y' (declared %P)",
9971 symbol, &label->base.source_position);
9973 label->base.source_position = token.source_position;
9974 label->statement = statement;
9979 if (token.type == '}') {
9980 /* TODO only warn? */
9981 if (warning.other && false) {
9982 warningf(HERE, "label at end of compound statement");
9983 statement->label.statement = create_empty_statement();
9985 errorf(HERE, "label at end of compound statement");
9986 statement->label.statement = create_invalid_statement();
9988 } else if (token.type == ';') {
9989 /* Eat an empty statement here, to avoid the warning about an empty
9990 * statement after a label. label:; is commonly used to have a label
9991 * before a closing brace. */
9992 statement->label.statement = create_empty_statement();
9995 statement_t *const inner_stmt = parse_statement();
9996 statement->label.statement = inner_stmt;
9997 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9998 errorf(&inner_stmt->base.source_position, "declaration after label");
10002 /* remember the labels in a list for later checking */
10003 *label_anchor = &statement->label;
10004 label_anchor = &statement->label.next;
10011 * Parse an if statement.
10013 static statement_t *parse_if(void)
10015 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10019 PUSH_PARENT(statement);
10021 add_anchor_token('{');
10023 expect('(', end_error);
10024 add_anchor_token(')');
10025 expression_t *const expr = parse_expression();
10026 statement->ifs.condition = expr;
10027 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10029 semantic_condition(expr, "condition of 'if'-statment");
10030 mark_vars_read(expr, NULL);
10031 rem_anchor_token(')');
10032 expect(')', end_error);
10035 rem_anchor_token('{');
10037 add_anchor_token(T_else);
10038 statement_t *const true_stmt = parse_statement();
10039 statement->ifs.true_statement = true_stmt;
10040 rem_anchor_token(T_else);
10042 if (token.type == T_else) {
10044 statement->ifs.false_statement = parse_statement();
10045 } else if (warning.parentheses &&
10046 true_stmt->kind == STATEMENT_IF &&
10047 true_stmt->ifs.false_statement != NULL) {
10048 warningf(&true_stmt->base.source_position,
10049 "suggest explicit braces to avoid ambiguous 'else'");
10057 * Check that all enums are handled in a switch.
10059 * @param statement the switch statement to check
10061 static void check_enum_cases(const switch_statement_t *statement) {
10062 const type_t *type = skip_typeref(statement->expression->base.type);
10063 if (! is_type_enum(type))
10065 const enum_type_t *enumt = &type->enumt;
10067 /* if we have a default, no warnings */
10068 if (statement->default_label != NULL)
10071 /* FIXME: calculation of value should be done while parsing */
10072 /* TODO: quadratic algorithm here. Change to an n log n one */
10073 long last_value = -1;
10074 const entity_t *entry = enumt->enume->base.next;
10075 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10076 entry = entry->base.next) {
10077 const expression_t *expression = entry->enum_value.value;
10078 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10079 bool found = false;
10080 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10081 if (l->expression == NULL)
10083 if (l->first_case <= value && value <= l->last_case) {
10089 warningf(&statement->base.source_position,
10090 "enumeration value '%Y' not handled in switch",
10091 entry->base.symbol);
10093 last_value = value;
10098 * Parse a switch statement.
10100 static statement_t *parse_switch(void)
10102 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10106 PUSH_PARENT(statement);
10108 expect('(', end_error);
10109 add_anchor_token(')');
10110 expression_t *const expr = parse_expression();
10111 mark_vars_read(expr, NULL);
10112 type_t * type = skip_typeref(expr->base.type);
10113 if (is_type_integer(type)) {
10114 type = promote_integer(type);
10115 if (warning.traditional) {
10116 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10117 warningf(&expr->base.source_position,
10118 "'%T' switch expression not converted to '%T' in ISO C",
10122 } else if (is_type_valid(type)) {
10123 errorf(&expr->base.source_position,
10124 "switch quantity is not an integer, but '%T'", type);
10125 type = type_error_type;
10127 statement->switchs.expression = create_implicit_cast(expr, type);
10128 expect(')', end_error);
10129 rem_anchor_token(')');
10131 switch_statement_t *rem = current_switch;
10132 current_switch = &statement->switchs;
10133 statement->switchs.body = parse_statement();
10134 current_switch = rem;
10136 if (warning.switch_default &&
10137 statement->switchs.default_label == NULL) {
10138 warningf(&statement->base.source_position, "switch has no default case");
10140 if (warning.switch_enum)
10141 check_enum_cases(&statement->switchs);
10147 return create_invalid_statement();
10150 static statement_t *parse_loop_body(statement_t *const loop)
10152 statement_t *const rem = current_loop;
10153 current_loop = loop;
10155 statement_t *const body = parse_statement();
10157 current_loop = rem;
10162 * Parse a while statement.
10164 static statement_t *parse_while(void)
10166 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10170 PUSH_PARENT(statement);
10172 expect('(', end_error);
10173 add_anchor_token(')');
10174 expression_t *const cond = parse_expression();
10175 statement->whiles.condition = cond;
10176 /* §6.8.5:2 The controlling expression of an iteration statement shall
10177 * have scalar type. */
10178 semantic_condition(cond, "condition of 'while'-statement");
10179 mark_vars_read(cond, NULL);
10180 rem_anchor_token(')');
10181 expect(')', end_error);
10183 statement->whiles.body = parse_loop_body(statement);
10189 return create_invalid_statement();
10193 * Parse a do statement.
10195 static statement_t *parse_do(void)
10197 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10201 PUSH_PARENT(statement);
10203 add_anchor_token(T_while);
10204 statement->do_while.body = parse_loop_body(statement);
10205 rem_anchor_token(T_while);
10207 expect(T_while, end_error);
10208 expect('(', end_error);
10209 add_anchor_token(')');
10210 expression_t *const cond = parse_expression();
10211 statement->do_while.condition = cond;
10212 /* §6.8.5:2 The controlling expression of an iteration statement shall
10213 * have scalar type. */
10214 semantic_condition(cond, "condition of 'do-while'-statement");
10215 mark_vars_read(cond, NULL);
10216 rem_anchor_token(')');
10217 expect(')', end_error);
10218 expect(';', end_error);
10224 return create_invalid_statement();
10228 * Parse a for statement.
10230 static statement_t *parse_for(void)
10232 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10236 expect('(', end_error1);
10237 add_anchor_token(')');
10239 PUSH_PARENT(statement);
10241 size_t const top = environment_top();
10242 scope_t *old_scope = scope_push(&statement->fors.scope);
10244 if (token.type == ';') {
10246 } else if (is_declaration_specifier(&token, false)) {
10247 parse_declaration(record_entity, DECL_FLAGS_NONE);
10249 add_anchor_token(';');
10250 expression_t *const init = parse_expression();
10251 statement->fors.initialisation = init;
10252 mark_vars_read(init, ENT_ANY);
10253 if (warning.unused_value && !expression_has_effect(init)) {
10254 warningf(&init->base.source_position,
10255 "initialisation of 'for'-statement has no effect");
10257 rem_anchor_token(';');
10258 expect(';', end_error2);
10261 if (token.type != ';') {
10262 add_anchor_token(';');
10263 expression_t *const cond = parse_expression();
10264 statement->fors.condition = cond;
10265 /* §6.8.5:2 The controlling expression of an iteration statement
10266 * shall have scalar type. */
10267 semantic_condition(cond, "condition of 'for'-statement");
10268 mark_vars_read(cond, NULL);
10269 rem_anchor_token(';');
10271 expect(';', end_error2);
10272 if (token.type != ')') {
10273 expression_t *const step = parse_expression();
10274 statement->fors.step = step;
10275 mark_vars_read(step, ENT_ANY);
10276 if (warning.unused_value && !expression_has_effect(step)) {
10277 warningf(&step->base.source_position,
10278 "step of 'for'-statement has no effect");
10281 expect(')', end_error2);
10282 rem_anchor_token(')');
10283 statement->fors.body = parse_loop_body(statement);
10285 assert(current_scope == &statement->fors.scope);
10286 scope_pop(old_scope);
10287 environment_pop_to(top);
10294 rem_anchor_token(')');
10295 assert(current_scope == &statement->fors.scope);
10296 scope_pop(old_scope);
10297 environment_pop_to(top);
10301 return create_invalid_statement();
10305 * Parse a goto statement.
10307 static statement_t *parse_goto(void)
10309 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10312 if (GNU_MODE && token.type == '*') {
10314 expression_t *expression = parse_expression();
10315 mark_vars_read(expression, NULL);
10317 /* Argh: although documentation says the expression must be of type void*,
10318 * gcc accepts anything that can be casted into void* without error */
10319 type_t *type = expression->base.type;
10321 if (type != type_error_type) {
10322 if (!is_type_pointer(type) && !is_type_integer(type)) {
10323 errorf(&expression->base.source_position,
10324 "cannot convert to a pointer type");
10325 } else if (warning.other && type != type_void_ptr) {
10326 warningf(&expression->base.source_position,
10327 "type of computed goto expression should be 'void*' not '%T'", type);
10329 expression = create_implicit_cast(expression, type_void_ptr);
10332 statement->gotos.expression = expression;
10334 if (token.type != T_IDENTIFIER) {
10336 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10338 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10339 eat_until_anchor();
10342 symbol_t *symbol = token.v.symbol;
10345 statement->gotos.label = get_label(symbol);
10348 /* remember the goto's in a list for later checking */
10349 *goto_anchor = &statement->gotos;
10350 goto_anchor = &statement->gotos.next;
10352 expect(';', end_error);
10356 return create_invalid_statement();
10360 * Parse a continue statement.
10362 static statement_t *parse_continue(void)
10364 if (current_loop == NULL) {
10365 errorf(HERE, "continue statement not within loop");
10368 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10371 expect(';', end_error);
10378 * Parse a break statement.
10380 static statement_t *parse_break(void)
10382 if (current_switch == NULL && current_loop == NULL) {
10383 errorf(HERE, "break statement not within loop or switch");
10386 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10389 expect(';', end_error);
10396 * Parse a __leave statement.
10398 static statement_t *parse_leave_statement(void)
10400 if (current_try == NULL) {
10401 errorf(HERE, "__leave statement not within __try");
10404 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10407 expect(';', end_error);
10414 * Check if a given entity represents a local variable.
10416 static bool is_local_variable(const entity_t *entity)
10418 if (entity->kind != ENTITY_VARIABLE)
10421 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10422 case STORAGE_CLASS_AUTO:
10423 case STORAGE_CLASS_REGISTER: {
10424 const type_t *type = skip_typeref(entity->declaration.type);
10425 if (is_type_function(type)) {
10437 * Check if a given expression represents a local variable.
10439 static bool expression_is_local_variable(const expression_t *expression)
10441 if (expression->base.kind != EXPR_REFERENCE) {
10444 const entity_t *entity = expression->reference.entity;
10445 return is_local_variable(entity);
10449 * Check if a given expression represents a local variable and
10450 * return its declaration then, else return NULL.
10452 entity_t *expression_is_variable(const expression_t *expression)
10454 if (expression->base.kind != EXPR_REFERENCE) {
10457 entity_t *entity = expression->reference.entity;
10458 if (entity->kind != ENTITY_VARIABLE)
10465 * Parse a return statement.
10467 static statement_t *parse_return(void)
10471 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10473 expression_t *return_value = NULL;
10474 if (token.type != ';') {
10475 return_value = parse_expression();
10476 mark_vars_read(return_value, NULL);
10479 const type_t *const func_type = skip_typeref(current_function->base.type);
10480 assert(is_type_function(func_type));
10481 type_t *const return_type = skip_typeref(func_type->function.return_type);
10483 source_position_t const *const pos = &statement->base.source_position;
10484 if (return_value != NULL) {
10485 type_t *return_value_type = skip_typeref(return_value->base.type);
10487 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10488 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10489 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10490 /* Only warn in C mode, because GCC does the same */
10491 if (c_mode & _CXX || strict_mode) {
10493 "'return' with a value, in function returning 'void'");
10494 } else if (warning.other) {
10496 "'return' with a value, in function returning 'void'");
10498 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10499 /* Only warn in C mode, because GCC does the same */
10502 "'return' with expression in function return 'void'");
10503 } else if (warning.other) {
10505 "'return' with expression in function return 'void'");
10509 assign_error_t error = semantic_assign(return_type, return_value);
10510 report_assign_error(error, return_type, return_value, "'return'",
10513 return_value = create_implicit_cast(return_value, return_type);
10514 /* check for returning address of a local var */
10515 if (warning.other && return_value != NULL
10516 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10517 const expression_t *expression = return_value->unary.value;
10518 if (expression_is_local_variable(expression)) {
10519 warningf(pos, "function returns address of local variable");
10522 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10523 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10524 if (c_mode & _CXX || strict_mode) {
10526 "'return' without value, in function returning non-void");
10529 "'return' without value, in function returning non-void");
10532 statement->returns.value = return_value;
10534 expect(';', end_error);
10541 * Parse a declaration statement.
10543 static statement_t *parse_declaration_statement(void)
10545 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10547 entity_t *before = current_scope->last_entity;
10549 parse_external_declaration();
10551 parse_declaration(record_entity, DECL_FLAGS_NONE);
10554 if (before == NULL) {
10555 statement->declaration.declarations_begin = current_scope->entities;
10557 statement->declaration.declarations_begin = before->base.next;
10559 statement->declaration.declarations_end = current_scope->last_entity;
10565 * Parse an expression statement, ie. expr ';'.
10567 static statement_t *parse_expression_statement(void)
10569 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10571 expression_t *const expr = parse_expression();
10572 statement->expression.expression = expr;
10573 mark_vars_read(expr, ENT_ANY);
10575 expect(';', end_error);
10582 * Parse a microsoft __try { } __finally { } or
10583 * __try{ } __except() { }
10585 static statement_t *parse_ms_try_statment(void)
10587 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10590 PUSH_PARENT(statement);
10592 ms_try_statement_t *rem = current_try;
10593 current_try = &statement->ms_try;
10594 statement->ms_try.try_statement = parse_compound_statement(false);
10599 if (token.type == T___except) {
10601 expect('(', end_error);
10602 add_anchor_token(')');
10603 expression_t *const expr = parse_expression();
10604 mark_vars_read(expr, NULL);
10605 type_t * type = skip_typeref(expr->base.type);
10606 if (is_type_integer(type)) {
10607 type = promote_integer(type);
10608 } else if (is_type_valid(type)) {
10609 errorf(&expr->base.source_position,
10610 "__expect expression is not an integer, but '%T'", type);
10611 type = type_error_type;
10613 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10614 rem_anchor_token(')');
10615 expect(')', end_error);
10616 statement->ms_try.final_statement = parse_compound_statement(false);
10617 } else if (token.type == T__finally) {
10619 statement->ms_try.final_statement = parse_compound_statement(false);
10621 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10622 return create_invalid_statement();
10626 return create_invalid_statement();
10629 static statement_t *parse_empty_statement(void)
10631 if (warning.empty_statement) {
10632 warningf(HERE, "statement is empty");
10634 statement_t *const statement = create_empty_statement();
10639 static statement_t *parse_local_label_declaration(void)
10641 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10645 entity_t *begin = NULL, *end = NULL;
10648 if (token.type != T_IDENTIFIER) {
10649 parse_error_expected("while parsing local label declaration",
10650 T_IDENTIFIER, NULL);
10653 symbol_t *symbol = token.v.symbol;
10654 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10655 if (entity != NULL && entity->base.parent_scope == current_scope) {
10656 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10657 symbol, &entity->base.source_position);
10659 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10661 entity->base.parent_scope = current_scope;
10662 entity->base.namespc = NAMESPACE_LABEL;
10663 entity->base.source_position = token.source_position;
10664 entity->base.symbol = symbol;
10667 end->base.next = entity;
10672 environment_push(entity);
10676 if (token.type != ',')
10682 statement->declaration.declarations_begin = begin;
10683 statement->declaration.declarations_end = end;
10687 static void parse_namespace_definition(void)
10691 entity_t *entity = NULL;
10692 symbol_t *symbol = NULL;
10694 if (token.type == T_IDENTIFIER) {
10695 symbol = token.v.symbol;
10698 entity = get_entity(symbol, NAMESPACE_NORMAL);
10699 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10700 && entity->base.parent_scope == current_scope) {
10701 error_redefined_as_different_kind(&token.source_position,
10702 entity, ENTITY_NAMESPACE);
10707 if (entity == NULL) {
10708 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10709 entity->base.symbol = symbol;
10710 entity->base.source_position = token.source_position;
10711 entity->base.namespc = NAMESPACE_NORMAL;
10712 entity->base.parent_scope = current_scope;
10715 if (token.type == '=') {
10716 /* TODO: parse namespace alias */
10717 panic("namespace alias definition not supported yet");
10720 environment_push(entity);
10721 append_entity(current_scope, entity);
10723 size_t const top = environment_top();
10724 scope_t *old_scope = scope_push(&entity->namespacee.members);
10726 expect('{', end_error);
10728 expect('}', end_error);
10731 assert(current_scope == &entity->namespacee.members);
10732 scope_pop(old_scope);
10733 environment_pop_to(top);
10737 * Parse a statement.
10738 * There's also parse_statement() which additionally checks for
10739 * "statement has no effect" warnings
10741 static statement_t *intern_parse_statement(void)
10743 statement_t *statement = NULL;
10745 /* declaration or statement */
10746 add_anchor_token(';');
10747 switch (token.type) {
10748 case T_IDENTIFIER: {
10749 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10750 if (la1_type == ':') {
10751 statement = parse_label_statement();
10752 } else if (is_typedef_symbol(token.v.symbol)) {
10753 statement = parse_declaration_statement();
10755 /* it's an identifier, the grammar says this must be an
10756 * expression statement. However it is common that users mistype
10757 * declaration types, so we guess a bit here to improve robustness
10758 * for incorrect programs */
10759 switch (la1_type) {
10762 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10763 goto expression_statment;
10768 statement = parse_declaration_statement();
10772 expression_statment:
10773 statement = parse_expression_statement();
10780 case T___extension__:
10781 /* This can be a prefix to a declaration or an expression statement.
10782 * We simply eat it now and parse the rest with tail recursion. */
10785 } while (token.type == T___extension__);
10786 bool old_gcc_extension = in_gcc_extension;
10787 in_gcc_extension = true;
10788 statement = intern_parse_statement();
10789 in_gcc_extension = old_gcc_extension;
10793 statement = parse_declaration_statement();
10797 statement = parse_local_label_declaration();
10800 case ';': statement = parse_empty_statement(); break;
10801 case '{': statement = parse_compound_statement(false); break;
10802 case T___leave: statement = parse_leave_statement(); break;
10803 case T___try: statement = parse_ms_try_statment(); break;
10804 case T_asm: statement = parse_asm_statement(); break;
10805 case T_break: statement = parse_break(); break;
10806 case T_case: statement = parse_case_statement(); break;
10807 case T_continue: statement = parse_continue(); break;
10808 case T_default: statement = parse_default_statement(); break;
10809 case T_do: statement = parse_do(); break;
10810 case T_for: statement = parse_for(); break;
10811 case T_goto: statement = parse_goto(); break;
10812 case T_if: statement = parse_if(); break;
10813 case T_return: statement = parse_return(); break;
10814 case T_switch: statement = parse_switch(); break;
10815 case T_while: statement = parse_while(); break;
10818 statement = parse_expression_statement();
10822 errorf(HERE, "unexpected token %K while parsing statement", &token);
10823 statement = create_invalid_statement();
10828 rem_anchor_token(';');
10830 assert(statement != NULL
10831 && statement->base.source_position.input_name != NULL);
10837 * parse a statement and emits "statement has no effect" warning if needed
10838 * (This is really a wrapper around intern_parse_statement with check for 1
10839 * single warning. It is needed, because for statement expressions we have
10840 * to avoid the warning on the last statement)
10842 static statement_t *parse_statement(void)
10844 statement_t *statement = intern_parse_statement();
10846 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10847 expression_t *expression = statement->expression.expression;
10848 if (!expression_has_effect(expression)) {
10849 warningf(&expression->base.source_position,
10850 "statement has no effect");
10858 * Parse a compound statement.
10860 static statement_t *parse_compound_statement(bool inside_expression_statement)
10862 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10864 PUSH_PARENT(statement);
10867 add_anchor_token('}');
10868 /* tokens, which can start a statement */
10869 /* TODO MS, __builtin_FOO */
10870 add_anchor_token('!');
10871 add_anchor_token('&');
10872 add_anchor_token('(');
10873 add_anchor_token('*');
10874 add_anchor_token('+');
10875 add_anchor_token('-');
10876 add_anchor_token('{');
10877 add_anchor_token('~');
10878 add_anchor_token(T_CHARACTER_CONSTANT);
10879 add_anchor_token(T_COLONCOLON);
10880 add_anchor_token(T_FLOATINGPOINT);
10881 add_anchor_token(T_IDENTIFIER);
10882 add_anchor_token(T_INTEGER);
10883 add_anchor_token(T_MINUSMINUS);
10884 add_anchor_token(T_PLUSPLUS);
10885 add_anchor_token(T_STRING_LITERAL);
10886 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10887 add_anchor_token(T_WIDE_STRING_LITERAL);
10888 add_anchor_token(T__Bool);
10889 add_anchor_token(T__Complex);
10890 add_anchor_token(T__Imaginary);
10891 add_anchor_token(T___FUNCTION__);
10892 add_anchor_token(T___PRETTY_FUNCTION__);
10893 add_anchor_token(T___alignof__);
10894 add_anchor_token(T___attribute__);
10895 add_anchor_token(T___builtin_va_start);
10896 add_anchor_token(T___extension__);
10897 add_anchor_token(T___func__);
10898 add_anchor_token(T___imag__);
10899 add_anchor_token(T___label__);
10900 add_anchor_token(T___real__);
10901 add_anchor_token(T___thread);
10902 add_anchor_token(T_asm);
10903 add_anchor_token(T_auto);
10904 add_anchor_token(T_bool);
10905 add_anchor_token(T_break);
10906 add_anchor_token(T_case);
10907 add_anchor_token(T_char);
10908 add_anchor_token(T_class);
10909 add_anchor_token(T_const);
10910 add_anchor_token(T_const_cast);
10911 add_anchor_token(T_continue);
10912 add_anchor_token(T_default);
10913 add_anchor_token(T_delete);
10914 add_anchor_token(T_double);
10915 add_anchor_token(T_do);
10916 add_anchor_token(T_dynamic_cast);
10917 add_anchor_token(T_enum);
10918 add_anchor_token(T_extern);
10919 add_anchor_token(T_false);
10920 add_anchor_token(T_float);
10921 add_anchor_token(T_for);
10922 add_anchor_token(T_goto);
10923 add_anchor_token(T_if);
10924 add_anchor_token(T_inline);
10925 add_anchor_token(T_int);
10926 add_anchor_token(T_long);
10927 add_anchor_token(T_new);
10928 add_anchor_token(T_operator);
10929 add_anchor_token(T_register);
10930 add_anchor_token(T_reinterpret_cast);
10931 add_anchor_token(T_restrict);
10932 add_anchor_token(T_return);
10933 add_anchor_token(T_short);
10934 add_anchor_token(T_signed);
10935 add_anchor_token(T_sizeof);
10936 add_anchor_token(T_static);
10937 add_anchor_token(T_static_cast);
10938 add_anchor_token(T_struct);
10939 add_anchor_token(T_switch);
10940 add_anchor_token(T_template);
10941 add_anchor_token(T_this);
10942 add_anchor_token(T_throw);
10943 add_anchor_token(T_true);
10944 add_anchor_token(T_try);
10945 add_anchor_token(T_typedef);
10946 add_anchor_token(T_typeid);
10947 add_anchor_token(T_typename);
10948 add_anchor_token(T_typeof);
10949 add_anchor_token(T_union);
10950 add_anchor_token(T_unsigned);
10951 add_anchor_token(T_using);
10952 add_anchor_token(T_void);
10953 add_anchor_token(T_volatile);
10954 add_anchor_token(T_wchar_t);
10955 add_anchor_token(T_while);
10957 size_t const top = environment_top();
10958 scope_t *old_scope = scope_push(&statement->compound.scope);
10960 statement_t **anchor = &statement->compound.statements;
10961 bool only_decls_so_far = true;
10962 while (token.type != '}') {
10963 if (token.type == T_EOF) {
10964 errorf(&statement->base.source_position,
10965 "EOF while parsing compound statement");
10968 statement_t *sub_statement = intern_parse_statement();
10969 if (is_invalid_statement(sub_statement)) {
10970 /* an error occurred. if we are at an anchor, return */
10976 if (warning.declaration_after_statement) {
10977 if (sub_statement->kind != STATEMENT_DECLARATION) {
10978 only_decls_so_far = false;
10979 } else if (!only_decls_so_far) {
10980 warningf(&sub_statement->base.source_position,
10981 "ISO C90 forbids mixed declarations and code");
10985 *anchor = sub_statement;
10987 while (sub_statement->base.next != NULL)
10988 sub_statement = sub_statement->base.next;
10990 anchor = &sub_statement->base.next;
10994 /* look over all statements again to produce no effect warnings */
10995 if (warning.unused_value) {
10996 statement_t *sub_statement = statement->compound.statements;
10997 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10998 if (sub_statement->kind != STATEMENT_EXPRESSION)
11000 /* don't emit a warning for the last expression in an expression
11001 * statement as it has always an effect */
11002 if (inside_expression_statement && sub_statement->base.next == NULL)
11005 expression_t *expression = sub_statement->expression.expression;
11006 if (!expression_has_effect(expression)) {
11007 warningf(&expression->base.source_position,
11008 "statement has no effect");
11014 rem_anchor_token(T_while);
11015 rem_anchor_token(T_wchar_t);
11016 rem_anchor_token(T_volatile);
11017 rem_anchor_token(T_void);
11018 rem_anchor_token(T_using);
11019 rem_anchor_token(T_unsigned);
11020 rem_anchor_token(T_union);
11021 rem_anchor_token(T_typeof);
11022 rem_anchor_token(T_typename);
11023 rem_anchor_token(T_typeid);
11024 rem_anchor_token(T_typedef);
11025 rem_anchor_token(T_try);
11026 rem_anchor_token(T_true);
11027 rem_anchor_token(T_throw);
11028 rem_anchor_token(T_this);
11029 rem_anchor_token(T_template);
11030 rem_anchor_token(T_switch);
11031 rem_anchor_token(T_struct);
11032 rem_anchor_token(T_static_cast);
11033 rem_anchor_token(T_static);
11034 rem_anchor_token(T_sizeof);
11035 rem_anchor_token(T_signed);
11036 rem_anchor_token(T_short);
11037 rem_anchor_token(T_return);
11038 rem_anchor_token(T_restrict);
11039 rem_anchor_token(T_reinterpret_cast);
11040 rem_anchor_token(T_register);
11041 rem_anchor_token(T_operator);
11042 rem_anchor_token(T_new);
11043 rem_anchor_token(T_long);
11044 rem_anchor_token(T_int);
11045 rem_anchor_token(T_inline);
11046 rem_anchor_token(T_if);
11047 rem_anchor_token(T_goto);
11048 rem_anchor_token(T_for);
11049 rem_anchor_token(T_float);
11050 rem_anchor_token(T_false);
11051 rem_anchor_token(T_extern);
11052 rem_anchor_token(T_enum);
11053 rem_anchor_token(T_dynamic_cast);
11054 rem_anchor_token(T_do);
11055 rem_anchor_token(T_double);
11056 rem_anchor_token(T_delete);
11057 rem_anchor_token(T_default);
11058 rem_anchor_token(T_continue);
11059 rem_anchor_token(T_const_cast);
11060 rem_anchor_token(T_const);
11061 rem_anchor_token(T_class);
11062 rem_anchor_token(T_char);
11063 rem_anchor_token(T_case);
11064 rem_anchor_token(T_break);
11065 rem_anchor_token(T_bool);
11066 rem_anchor_token(T_auto);
11067 rem_anchor_token(T_asm);
11068 rem_anchor_token(T___thread);
11069 rem_anchor_token(T___real__);
11070 rem_anchor_token(T___label__);
11071 rem_anchor_token(T___imag__);
11072 rem_anchor_token(T___func__);
11073 rem_anchor_token(T___extension__);
11074 rem_anchor_token(T___builtin_va_start);
11075 rem_anchor_token(T___attribute__);
11076 rem_anchor_token(T___alignof__);
11077 rem_anchor_token(T___PRETTY_FUNCTION__);
11078 rem_anchor_token(T___FUNCTION__);
11079 rem_anchor_token(T__Imaginary);
11080 rem_anchor_token(T__Complex);
11081 rem_anchor_token(T__Bool);
11082 rem_anchor_token(T_WIDE_STRING_LITERAL);
11083 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11084 rem_anchor_token(T_STRING_LITERAL);
11085 rem_anchor_token(T_PLUSPLUS);
11086 rem_anchor_token(T_MINUSMINUS);
11087 rem_anchor_token(T_INTEGER);
11088 rem_anchor_token(T_IDENTIFIER);
11089 rem_anchor_token(T_FLOATINGPOINT);
11090 rem_anchor_token(T_COLONCOLON);
11091 rem_anchor_token(T_CHARACTER_CONSTANT);
11092 rem_anchor_token('~');
11093 rem_anchor_token('{');
11094 rem_anchor_token('-');
11095 rem_anchor_token('+');
11096 rem_anchor_token('*');
11097 rem_anchor_token('(');
11098 rem_anchor_token('&');
11099 rem_anchor_token('!');
11100 rem_anchor_token('}');
11101 assert(current_scope == &statement->compound.scope);
11102 scope_pop(old_scope);
11103 environment_pop_to(top);
11110 * Check for unused global static functions and variables
11112 static void check_unused_globals(void)
11114 if (!warning.unused_function && !warning.unused_variable)
11117 for (const entity_t *entity = file_scope->entities; entity != NULL;
11118 entity = entity->base.next) {
11119 if (!is_declaration(entity))
11122 const declaration_t *declaration = &entity->declaration;
11123 if (declaration->used ||
11124 declaration->modifiers & DM_UNUSED ||
11125 declaration->modifiers & DM_USED ||
11126 declaration->storage_class != STORAGE_CLASS_STATIC)
11129 type_t *const type = declaration->type;
11131 if (entity->kind == ENTITY_FUNCTION) {
11132 /* inhibit warning for static inline functions */
11133 if (entity->function.is_inline)
11136 s = entity->function.statement != NULL ? "defined" : "declared";
11141 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11142 type, declaration->base.symbol, s);
11146 static void parse_global_asm(void)
11148 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11151 expect('(', end_error);
11153 statement->asms.asm_text = parse_string_literals();
11154 statement->base.next = unit->global_asm;
11155 unit->global_asm = statement;
11157 expect(')', end_error);
11158 expect(';', end_error);
11163 static void parse_linkage_specification(void)
11166 assert(token.type == T_STRING_LITERAL);
11168 const char *linkage = parse_string_literals().begin;
11170 linkage_kind_t old_linkage = current_linkage;
11171 linkage_kind_t new_linkage;
11172 if (strcmp(linkage, "C") == 0) {
11173 new_linkage = LINKAGE_C;
11174 } else if (strcmp(linkage, "C++") == 0) {
11175 new_linkage = LINKAGE_CXX;
11177 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11178 new_linkage = LINKAGE_INVALID;
11180 current_linkage = new_linkage;
11182 if (token.type == '{') {
11185 expect('}', end_error);
11191 assert(current_linkage == new_linkage);
11192 current_linkage = old_linkage;
11195 static void parse_external(void)
11197 switch (token.type) {
11198 DECLARATION_START_NO_EXTERN
11200 case T___extension__:
11201 /* tokens below are for implicit int */
11202 case '&': /* & x; -> int& x; (and error later, because C++ has no
11204 case '*': /* * x; -> int* x; */
11205 case '(': /* (x); -> int (x); */
11206 parse_external_declaration();
11210 if (look_ahead(1)->type == T_STRING_LITERAL) {
11211 parse_linkage_specification();
11213 parse_external_declaration();
11218 parse_global_asm();
11222 parse_namespace_definition();
11226 if (!strict_mode) {
11228 warningf(HERE, "stray ';' outside of function");
11235 errorf(HERE, "stray %K outside of function", &token);
11236 if (token.type == '(' || token.type == '{' || token.type == '[')
11237 eat_until_matching_token(token.type);
11243 static void parse_externals(void)
11245 add_anchor_token('}');
11246 add_anchor_token(T_EOF);
11249 unsigned char token_anchor_copy[T_LAST_TOKEN];
11250 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11253 while (token.type != T_EOF && token.type != '}') {
11255 bool anchor_leak = false;
11256 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11257 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11259 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11260 anchor_leak = true;
11263 if (in_gcc_extension) {
11264 errorf(HERE, "Leaked __extension__");
11265 anchor_leak = true;
11275 rem_anchor_token(T_EOF);
11276 rem_anchor_token('}');
11280 * Parse a translation unit.
11282 static void parse_translation_unit(void)
11284 add_anchor_token(T_EOF);
11289 if (token.type == T_EOF)
11292 errorf(HERE, "stray %K outside of function", &token);
11293 if (token.type == '(' || token.type == '{' || token.type == '[')
11294 eat_until_matching_token(token.type);
11302 * @return the translation unit or NULL if errors occurred.
11304 void start_parsing(void)
11306 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11307 label_stack = NEW_ARR_F(stack_entry_t, 0);
11308 diagnostic_count = 0;
11312 type_set_output(stderr);
11313 ast_set_output(stderr);
11315 assert(unit == NULL);
11316 unit = allocate_ast_zero(sizeof(unit[0]));
11318 assert(file_scope == NULL);
11319 file_scope = &unit->scope;
11321 assert(current_scope == NULL);
11322 scope_push(&unit->scope);
11325 translation_unit_t *finish_parsing(void)
11327 assert(current_scope == &unit->scope);
11330 assert(file_scope == &unit->scope);
11331 check_unused_globals();
11334 DEL_ARR_F(environment_stack);
11335 DEL_ARR_F(label_stack);
11337 translation_unit_t *result = unit;
11342 /* GCC allows global arrays without size and assigns them a length of one,
11343 * if no different declaration follows */
11344 static void complete_incomplete_arrays(void)
11346 size_t n = ARR_LEN(incomplete_arrays);
11347 for (size_t i = 0; i != n; ++i) {
11348 declaration_t *const decl = incomplete_arrays[i];
11349 type_t *const orig_type = decl->type;
11350 type_t *const type = skip_typeref(orig_type);
11352 if (!is_type_incomplete(type))
11355 if (warning.other) {
11356 warningf(&decl->base.source_position,
11357 "array '%#T' assumed to have one element",
11358 orig_type, decl->base.symbol);
11361 type_t *const new_type = duplicate_type(type);
11362 new_type->array.size_constant = true;
11363 new_type->array.has_implicit_size = true;
11364 new_type->array.size = 1;
11366 type_t *const result = typehash_insert(new_type);
11367 if (type != result)
11370 decl->type = result;
11376 lookahead_bufpos = 0;
11377 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11380 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11381 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11382 parse_translation_unit();
11383 complete_incomplete_arrays();
11384 DEL_ARR_F(incomplete_arrays);
11385 incomplete_arrays = NULL;
11389 * Initialize the parser.
11391 void init_parser(void)
11393 sym_anonymous = symbol_table_insert("<anonymous>");
11395 if (c_mode & _MS) {
11396 /* add predefined symbols for extended-decl-modifier */
11397 sym_align = symbol_table_insert("align");
11398 sym_allocate = symbol_table_insert("allocate");
11399 sym_dllimport = symbol_table_insert("dllimport");
11400 sym_dllexport = symbol_table_insert("dllexport");
11401 sym_naked = symbol_table_insert("naked");
11402 sym_noinline = symbol_table_insert("noinline");
11403 sym_returns_twice = symbol_table_insert("returns_twice");
11404 sym_noreturn = symbol_table_insert("noreturn");
11405 sym_nothrow = symbol_table_insert("nothrow");
11406 sym_novtable = symbol_table_insert("novtable");
11407 sym_property = symbol_table_insert("property");
11408 sym_get = symbol_table_insert("get");
11409 sym_put = symbol_table_insert("put");
11410 sym_selectany = symbol_table_insert("selectany");
11411 sym_thread = symbol_table_insert("thread");
11412 sym_uuid = symbol_table_insert("uuid");
11413 sym_deprecated = symbol_table_insert("deprecated");
11414 sym_restrict = symbol_table_insert("restrict");
11415 sym_noalias = symbol_table_insert("noalias");
11417 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11419 init_expression_parsers();
11420 obstack_init(&temp_obst);
11422 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11423 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11427 * Terminate the parser.
11429 void exit_parser(void)
11431 obstack_free(&temp_obst, NULL);