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 1
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool has_arguments; /**< True, if this attribute has arguments. */
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
102 * Capture a MS __base extension.
104 typedef struct based_spec_t {
105 source_position_t source_position;
106 variable_t *base_variable;
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
111 /** The current token. */
112 static token_t token;
113 /** The lookahead ring-buffer. */
114 static token_t lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static size_t 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 < lengthof(sizes));
355 assert(sizes[kind] != 0);
360 * Allocate an entity of given kind and initialize all
363 static entity_t *allocate_entity_zero(entity_kind_t kind)
365 size_t size = get_entity_struct_size(kind);
366 entity_t *entity = allocate_ast_zero(size);
372 * Returns the size of a statement node.
374 * @param kind the statement kind
376 static size_t get_statement_struct_size(statement_kind_t kind)
378 static const size_t sizes[] = {
379 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
380 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
381 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
382 [STATEMENT_RETURN] = sizeof(return_statement_t),
383 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
384 [STATEMENT_IF] = sizeof(if_statement_t),
385 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
386 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
387 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
388 [STATEMENT_BREAK] = sizeof(statement_base_t),
389 [STATEMENT_GOTO] = sizeof(goto_statement_t),
390 [STATEMENT_LABEL] = sizeof(label_statement_t),
391 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
392 [STATEMENT_WHILE] = sizeof(while_statement_t),
393 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
394 [STATEMENT_FOR] = sizeof(for_statement_t),
395 [STATEMENT_ASM] = sizeof(asm_statement_t),
396 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
397 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
399 assert(kind < lengthof(sizes));
400 assert(sizes[kind] != 0);
405 * Returns the size of an expression node.
407 * @param kind the expression kind
409 static size_t get_expression_struct_size(expression_kind_t kind)
411 static const size_t sizes[] = {
412 [EXPR_INVALID] = sizeof(expression_base_t),
413 [EXPR_REFERENCE] = sizeof(reference_expression_t),
414 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
415 [EXPR_CONST] = sizeof(const_expression_t),
416 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
417 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
418 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
419 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
420 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
421 [EXPR_CALL] = sizeof(call_expression_t),
422 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
423 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
424 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
425 [EXPR_SELECT] = sizeof(select_expression_t),
426 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
427 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
428 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
429 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
430 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
431 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
432 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
433 [EXPR_BUILTIN_ADDRESS] = sizeof(builtin_address_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 < lengthof(sizes));
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(lengthof(sizes) == (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 < lengthof(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 * Returns the index of the top element of the environment stack.
586 static size_t environment_top(void)
588 return ARR_LEN(environment_stack);
592 * Returns the index of the top element of the global label stack.
594 static size_t label_top(void)
596 return ARR_LEN(label_stack);
600 * Return the next token.
602 static inline void next_token(void)
604 token = lookahead_buffer[lookahead_bufpos];
605 lookahead_buffer[lookahead_bufpos] = lexer_token;
608 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
611 print_token(stderr, &token);
612 fprintf(stderr, "\n");
617 * Return the next token with a given lookahead.
619 static inline const token_t *look_ahead(size_t num)
621 assert(0 < num && num <= MAX_LOOKAHEAD);
622 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
623 return &lookahead_buffer[pos];
627 * Adds a token type to the token type anchor set (a multi-set).
629 static void add_anchor_token(int token_type)
631 assert(0 <= token_type && token_type < T_LAST_TOKEN);
632 ++token_anchor_set[token_type];
636 * Set the number of tokens types of the given type
637 * to zero and return the old count.
639 static int save_and_reset_anchor_state(int token_type)
641 assert(0 <= token_type && token_type < T_LAST_TOKEN);
642 int count = token_anchor_set[token_type];
643 token_anchor_set[token_type] = 0;
648 * Restore the number of token types to the given count.
650 static void restore_anchor_state(int token_type, int count)
652 assert(0 <= token_type && token_type < T_LAST_TOKEN);
653 token_anchor_set[token_type] = count;
657 * Remove a token type from the token type anchor set (a multi-set).
659 static void rem_anchor_token(int token_type)
661 assert(0 <= token_type && token_type < T_LAST_TOKEN);
662 assert(token_anchor_set[token_type] != 0);
663 --token_anchor_set[token_type];
667 * Return true if the token type of the current token is
670 static bool at_anchor(void)
674 return token_anchor_set[token.type];
678 * Eat tokens until a matching token type is found.
680 static void eat_until_matching_token(int type)
684 case '(': end_token = ')'; break;
685 case '{': end_token = '}'; break;
686 case '[': end_token = ']'; break;
687 default: end_token = type; break;
690 unsigned parenthesis_count = 0;
691 unsigned brace_count = 0;
692 unsigned bracket_count = 0;
693 while (token.type != end_token ||
694 parenthesis_count != 0 ||
696 bracket_count != 0) {
697 switch (token.type) {
699 case '(': ++parenthesis_count; break;
700 case '{': ++brace_count; break;
701 case '[': ++bracket_count; break;
704 if (parenthesis_count > 0)
714 if (bracket_count > 0)
717 if (token.type == end_token &&
718 parenthesis_count == 0 &&
732 * Eat input tokens until an anchor is found.
734 static void eat_until_anchor(void)
736 while (token_anchor_set[token.type] == 0) {
737 if (token.type == '(' || token.type == '{' || token.type == '[')
738 eat_until_matching_token(token.type);
744 * Eat a whole block from input tokens.
746 static void eat_block(void)
748 eat_until_matching_token('{');
749 if (token.type == '}')
753 #define eat(token_type) (assert(token.type == (token_type)), next_token())
756 * Report a parse error because an expected token was not found.
759 #if defined __GNUC__ && __GNUC__ >= 4
760 __attribute__((sentinel))
762 void parse_error_expected(const char *message, ...)
764 if (message != NULL) {
765 errorf(HERE, "%s", message);
768 va_start(ap, message);
769 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
774 * Report an incompatible type.
776 static void type_error_incompatible(const char *msg,
777 const source_position_t *source_position, type_t *type1, type_t *type2)
779 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
784 * Expect the current token is the expected token.
785 * If not, generate an error, eat the current statement,
786 * and goto the end_error label.
788 #define expect(expected, error_label) \
790 if (UNLIKELY(token.type != (expected))) { \
791 parse_error_expected(NULL, (expected), NULL); \
792 add_anchor_token(expected); \
793 eat_until_anchor(); \
794 if (token.type == expected) \
796 rem_anchor_token(expected); \
803 * Push a given scope on the scope stack and make it the
806 static scope_t *scope_push(scope_t *new_scope)
808 if (current_scope != NULL) {
809 new_scope->depth = current_scope->depth + 1;
812 scope_t *old_scope = current_scope;
813 current_scope = new_scope;
818 * Pop the current scope from the scope stack.
820 static void scope_pop(scope_t *old_scope)
822 current_scope = old_scope;
826 * Search an entity by its symbol in a given namespace.
828 static entity_t *get_entity(const symbol_t *const symbol,
829 namespace_tag_t namespc)
831 entity_t *entity = symbol->entity;
832 for (; entity != NULL; entity = entity->base.symbol_next) {
833 if (entity->base.namespc == namespc)
841 * pushs an entity on the environment stack and links the corresponding symbol
844 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
846 symbol_t *symbol = entity->base.symbol;
847 entity_namespace_t namespc = entity->base.namespc;
848 assert(namespc != NAMESPACE_INVALID);
850 /* replace/add entity into entity list of the symbol */
853 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
858 /* replace an entry? */
859 if (iter->base.namespc == namespc) {
860 entity->base.symbol_next = iter->base.symbol_next;
866 /* remember old declaration */
868 entry.symbol = symbol;
869 entry.old_entity = iter;
870 entry.namespc = namespc;
871 ARR_APP1(stack_entry_t, *stack_ptr, entry);
875 * Push an entity on the environment stack.
877 static void environment_push(entity_t *entity)
879 assert(entity->base.source_position.input_name != NULL);
880 assert(entity->base.parent_scope != NULL);
881 stack_push(&environment_stack, entity);
885 * Push a declaration on the global label stack.
887 * @param declaration the declaration
889 static void label_push(entity_t *label)
891 /* we abuse the parameters scope as parent for the labels */
892 label->base.parent_scope = ¤t_function->parameters;
893 stack_push(&label_stack, label);
897 * pops symbols from the environment stack until @p new_top is the top element
899 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
901 stack_entry_t *stack = *stack_ptr;
902 size_t top = ARR_LEN(stack);
905 assert(new_top <= top);
909 for (i = top; i > new_top; --i) {
910 stack_entry_t *entry = &stack[i - 1];
912 entity_t *old_entity = entry->old_entity;
913 symbol_t *symbol = entry->symbol;
914 entity_namespace_t namespc = entry->namespc;
916 /* replace with old_entity/remove */
919 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
921 assert(iter != NULL);
922 /* replace an entry? */
923 if (iter->base.namespc == namespc)
927 /* restore definition from outer scopes (if there was one) */
928 if (old_entity != NULL) {
929 old_entity->base.symbol_next = iter->base.symbol_next;
930 *anchor = old_entity;
932 /* remove entry from list */
933 *anchor = iter->base.symbol_next;
937 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
941 * Pop all entries from the environment stack until the new_top
944 * @param new_top the new stack top
946 static void environment_pop_to(size_t new_top)
948 stack_pop_to(&environment_stack, new_top);
952 * Pop all entries from the global label stack until the new_top
955 * @param new_top the new stack top
957 static void label_pop_to(size_t new_top)
959 stack_pop_to(&label_stack, new_top);
962 static int get_akind_rank(atomic_type_kind_t akind)
968 * Return the type rank for an atomic type.
970 static int get_rank(const type_t *type)
972 assert(!is_typeref(type));
973 if (type->kind == TYPE_ENUM)
974 return get_akind_rank(type->enumt.akind);
976 assert(type->kind == TYPE_ATOMIC);
977 return get_akind_rank(type->atomic.akind);
981 * Do integer promotion for a given type.
983 * @param type the type to promote
984 * @return the promoted type
986 static type_t *promote_integer(type_t *type)
988 if (type->kind == TYPE_BITFIELD)
989 type = type->bitfield.base_type;
991 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
998 * Create a cast expression.
1000 * @param expression the expression to cast
1001 * @param dest_type the destination type
1003 static expression_t *create_cast_expression(expression_t *expression,
1006 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1008 cast->unary.value = expression;
1009 cast->base.type = dest_type;
1015 * Check if a given expression represents a null pointer constant.
1017 * @param expression the expression to check
1019 static bool is_null_pointer_constant(const expression_t *expression)
1021 /* skip void* cast */
1022 if (expression->kind == EXPR_UNARY_CAST ||
1023 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1024 type_t *const type = skip_typeref(expression->base.type);
1025 if (types_compatible(type, type_void_ptr))
1026 expression = expression->unary.value;
1029 type_t *const type = skip_typeref(expression->base.type);
1031 is_type_integer(type) &&
1032 is_constant_expression(expression) &&
1033 fold_constant(expression) == 0;
1037 * Create an implicit cast expression.
1039 * @param expression the expression to cast
1040 * @param dest_type the destination type
1042 static expression_t *create_implicit_cast(expression_t *expression,
1045 type_t *const source_type = expression->base.type;
1047 if (source_type == dest_type)
1050 return create_cast_expression(expression, dest_type);
1053 typedef enum assign_error_t {
1055 ASSIGN_ERROR_INCOMPATIBLE,
1056 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1057 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1058 ASSIGN_WARNING_POINTER_FROM_INT,
1059 ASSIGN_WARNING_INT_FROM_POINTER
1062 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1063 const expression_t *const right,
1064 const char *context,
1065 const source_position_t *source_position)
1067 type_t *const orig_type_right = right->base.type;
1068 type_t *const type_left = skip_typeref(orig_type_left);
1069 type_t *const type_right = skip_typeref(orig_type_right);
1072 case ASSIGN_SUCCESS:
1074 case ASSIGN_ERROR_INCOMPATIBLE:
1075 errorf(source_position,
1076 "destination type '%T' in %s is incompatible with type '%T'",
1077 orig_type_left, context, orig_type_right);
1080 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1081 if (warning.other) {
1082 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1083 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1085 /* the left type has all qualifiers from the right type */
1086 unsigned missing_qualifiers
1087 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1088 warningf(source_position,
1089 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1090 orig_type_left, context, orig_type_right, missing_qualifiers);
1095 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1096 if (warning.other) {
1097 warningf(source_position,
1098 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1099 orig_type_left, context, right, orig_type_right);
1103 case ASSIGN_WARNING_POINTER_FROM_INT:
1104 if (warning.other) {
1105 warningf(source_position,
1106 "%s makes pointer '%T' from integer '%T' without a cast",
1107 context, orig_type_left, orig_type_right);
1111 case ASSIGN_WARNING_INT_FROM_POINTER:
1112 if (warning.other) {
1113 warningf(source_position,
1114 "%s makes integer '%T' from pointer '%T' without a cast",
1115 context, orig_type_left, orig_type_right);
1120 panic("invalid error value");
1124 /** Implements the rules from § 6.5.16.1 */
1125 static assign_error_t semantic_assign(type_t *orig_type_left,
1126 const expression_t *const right)
1128 type_t *const orig_type_right = right->base.type;
1129 type_t *const type_left = skip_typeref(orig_type_left);
1130 type_t *const type_right = skip_typeref(orig_type_right);
1132 if (is_type_pointer(type_left)) {
1133 if (is_null_pointer_constant(right)) {
1134 return ASSIGN_SUCCESS;
1135 } else if (is_type_pointer(type_right)) {
1136 type_t *points_to_left
1137 = skip_typeref(type_left->pointer.points_to);
1138 type_t *points_to_right
1139 = skip_typeref(type_right->pointer.points_to);
1140 assign_error_t res = ASSIGN_SUCCESS;
1142 /* the left type has all qualifiers from the right type */
1143 unsigned missing_qualifiers
1144 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1145 if (missing_qualifiers != 0) {
1146 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1149 points_to_left = get_unqualified_type(points_to_left);
1150 points_to_right = get_unqualified_type(points_to_right);
1152 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1155 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1156 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1157 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1160 if (!types_compatible(points_to_left, points_to_right)) {
1161 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1165 } else if (is_type_integer(type_right)) {
1166 return ASSIGN_WARNING_POINTER_FROM_INT;
1168 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1169 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1170 && is_type_pointer(type_right))) {
1171 return ASSIGN_SUCCESS;
1172 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1173 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1174 type_t *const unqual_type_left = get_unqualified_type(type_left);
1175 type_t *const unqual_type_right = get_unqualified_type(type_right);
1176 if (types_compatible(unqual_type_left, unqual_type_right)) {
1177 return ASSIGN_SUCCESS;
1179 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1180 return ASSIGN_WARNING_INT_FROM_POINTER;
1183 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1184 return ASSIGN_SUCCESS;
1186 return ASSIGN_ERROR_INCOMPATIBLE;
1189 static expression_t *parse_constant_expression(void)
1191 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1193 if (!is_constant_expression(result)) {
1194 errorf(&result->base.source_position,
1195 "expression '%E' is not constant", result);
1201 static expression_t *parse_assignment_expression(void)
1203 return parse_sub_expression(PREC_ASSIGNMENT);
1206 static string_t parse_string_literals(void)
1208 assert(token.type == T_STRING_LITERAL);
1209 string_t result = token.v.string;
1213 while (token.type == T_STRING_LITERAL) {
1214 result = concat_strings(&result, &token.v.string);
1221 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1222 [GNU_AK_CONST] = "const",
1223 [GNU_AK_VOLATILE] = "volatile",
1224 [GNU_AK_CDECL] = "cdecl",
1225 [GNU_AK_STDCALL] = "stdcall",
1226 [GNU_AK_FASTCALL] = "fastcall",
1227 [GNU_AK_DEPRECATED] = "deprecated",
1228 [GNU_AK_NOINLINE] = "noinline",
1229 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1230 [GNU_AK_NORETURN] = "noreturn",
1231 [GNU_AK_NAKED] = "naked",
1232 [GNU_AK_PURE] = "pure",
1233 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1234 [GNU_AK_MALLOC] = "malloc",
1235 [GNU_AK_WEAK] = "weak",
1236 [GNU_AK_CONSTRUCTOR] = "constructor",
1237 [GNU_AK_DESTRUCTOR] = "destructor",
1238 [GNU_AK_NOTHROW] = "nothrow",
1239 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1240 [GNU_AK_COMMON] = "common",
1241 [GNU_AK_NOCOMMON] = "nocommon",
1242 [GNU_AK_PACKED] = "packed",
1243 [GNU_AK_SHARED] = "shared",
1244 [GNU_AK_NOTSHARED] = "notshared",
1245 [GNU_AK_USED] = "used",
1246 [GNU_AK_UNUSED] = "unused",
1247 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1248 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1249 [GNU_AK_LONGCALL] = "longcall",
1250 [GNU_AK_SHORTCALL] = "shortcall",
1251 [GNU_AK_LONG_CALL] = "long_call",
1252 [GNU_AK_SHORT_CALL] = "short_call",
1253 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1254 [GNU_AK_INTERRUPT] = "interrupt",
1255 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1256 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1257 [GNU_AK_NESTING] = "nesting",
1258 [GNU_AK_NEAR] = "near",
1259 [GNU_AK_FAR] = "far",
1260 [GNU_AK_SIGNAL] = "signal",
1261 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1262 [GNU_AK_TINY_DATA] = "tiny_data",
1263 [GNU_AK_SAVEALL] = "saveall",
1264 [GNU_AK_FLATTEN] = "flatten",
1265 [GNU_AK_SSEREGPARM] = "sseregparm",
1266 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1267 [GNU_AK_RETURN_TWICE] = "return_twice",
1268 [GNU_AK_MAY_ALIAS] = "may_alias",
1269 [GNU_AK_MS_STRUCT] = "ms_struct",
1270 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1271 [GNU_AK_DLLIMPORT] = "dllimport",
1272 [GNU_AK_DLLEXPORT] = "dllexport",
1273 [GNU_AK_ALIGNED] = "aligned",
1274 [GNU_AK_ALIAS] = "alias",
1275 [GNU_AK_SECTION] = "section",
1276 [GNU_AK_FORMAT] = "format",
1277 [GNU_AK_FORMAT_ARG] = "format_arg",
1278 [GNU_AK_WEAKREF] = "weakref",
1279 [GNU_AK_NONNULL] = "nonnull",
1280 [GNU_AK_TLS_MODEL] = "tls_model",
1281 [GNU_AK_VISIBILITY] = "visibility",
1282 [GNU_AK_REGPARM] = "regparm",
1283 [GNU_AK_MODE] = "mode",
1284 [GNU_AK_MODEL] = "model",
1285 [GNU_AK_TRAP_EXIT] = "trap_exit",
1286 [GNU_AK_SP_SWITCH] = "sp_switch",
1287 [GNU_AK_SENTINEL] = "sentinel"
1291 * compare two string, ignoring double underscores on the second.
1293 static int strcmp_underscore(const char *s1, const char *s2)
1295 if (s2[0] == '_' && s2[1] == '_') {
1296 size_t len2 = strlen(s2);
1297 size_t len1 = strlen(s1);
1298 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1299 return strncmp(s1, s2+2, len2-4);
1303 return strcmp(s1, s2);
1307 * Allocate a new gnu temporal attribute of given kind.
1309 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1311 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1312 attribute->kind = kind;
1313 attribute->next = NULL;
1314 attribute->invalid = false;
1315 attribute->has_arguments = false;
1321 * Parse one constant expression argument of the given attribute.
1323 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1325 expression_t *expression;
1326 add_anchor_token(')');
1327 expression = parse_constant_expression();
1328 rem_anchor_token(')');
1329 expect(')', end_error);
1330 attribute->u.argument = fold_constant(expression);
1333 attribute->invalid = true;
1337 * Parse a list of constant expressions arguments of the given attribute.
1339 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1341 argument_list_t **list = &attribute->u.arguments;
1342 argument_list_t *entry;
1343 expression_t *expression;
1344 add_anchor_token(')');
1345 add_anchor_token(',');
1347 expression = parse_constant_expression();
1348 entry = obstack_alloc(&temp_obst, sizeof(entry));
1349 entry->argument = fold_constant(expression);
1352 list = &entry->next;
1353 if (token.type != ',')
1357 rem_anchor_token(',');
1358 rem_anchor_token(')');
1359 expect(')', end_error);
1362 attribute->invalid = true;
1366 * Parse one string literal argument of the given attribute.
1368 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1371 add_anchor_token('(');
1372 if (token.type != T_STRING_LITERAL) {
1373 parse_error_expected("while parsing attribute directive",
1374 T_STRING_LITERAL, NULL);
1377 *string = parse_string_literals();
1378 rem_anchor_token('(');
1379 expect(')', end_error);
1382 attribute->invalid = true;
1386 * Parse one tls model of the given attribute.
1388 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1390 static const char *const tls_models[] = {
1396 string_t string = { NULL, 0 };
1397 parse_gnu_attribute_string_arg(attribute, &string);
1398 if (string.begin != NULL) {
1399 for (size_t i = 0; i < 4; ++i) {
1400 if (strcmp(tls_models[i], string.begin) == 0) {
1401 attribute->u.value = i;
1405 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1407 attribute->invalid = true;
1411 * Parse one tls model of the given attribute.
1413 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1415 static const char *const visibilities[] = {
1421 string_t string = { NULL, 0 };
1422 parse_gnu_attribute_string_arg(attribute, &string);
1423 if (string.begin != NULL) {
1424 for (size_t i = 0; i < 4; ++i) {
1425 if (strcmp(visibilities[i], string.begin) == 0) {
1426 attribute->u.value = i;
1430 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1432 attribute->invalid = true;
1436 * Parse one (code) model of the given attribute.
1438 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1440 static const char *const visibilities[] = {
1445 string_t string = { NULL, 0 };
1446 parse_gnu_attribute_string_arg(attribute, &string);
1447 if (string.begin != NULL) {
1448 for (int i = 0; i < 3; ++i) {
1449 if (strcmp(visibilities[i], string.begin) == 0) {
1450 attribute->u.value = i;
1454 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1456 attribute->invalid = true;
1460 * Parse one mode of the given attribute.
1462 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1464 add_anchor_token(')');
1466 if (token.type != T_IDENTIFIER) {
1467 expect(T_IDENTIFIER, end_error);
1470 attribute->u.symbol = token.v.symbol;
1473 rem_anchor_token(')');
1474 expect(')', end_error);
1477 attribute->invalid = true;
1481 * Parse one interrupt argument of the given attribute.
1483 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1485 static const char *const interrupts[] = {
1492 string_t string = { NULL, 0 };
1493 parse_gnu_attribute_string_arg(attribute, &string);
1494 if (string.begin != NULL) {
1495 for (size_t i = 0; i < 5; ++i) {
1496 if (strcmp(interrupts[i], string.begin) == 0) {
1497 attribute->u.value = i;
1501 errorf(HERE, "'%s' is not an interrupt", string.begin);
1503 attribute->invalid = true;
1507 * Parse ( identifier, const expression, const expression )
1509 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1511 static const char *const format_names[] = {
1519 if (token.type != T_IDENTIFIER) {
1520 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1523 const char *name = token.v.symbol->string;
1524 for (i = 0; i < 4; ++i) {
1525 if (strcmp_underscore(format_names[i], name) == 0)
1529 if (warning.attribute)
1530 warningf(HERE, "'%s' is an unrecognized format function type", name);
1534 expect(',', end_error);
1535 add_anchor_token(')');
1536 add_anchor_token(',');
1537 parse_constant_expression();
1538 rem_anchor_token(',');
1539 rem_anchor_token(')');
1541 expect(',', end_error);
1542 add_anchor_token(')');
1543 parse_constant_expression();
1544 rem_anchor_token(')');
1545 expect(')', end_error);
1548 attribute->u.value = true;
1552 * Check that a given GNU attribute has no arguments.
1554 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1556 if (!attribute->has_arguments)
1559 /* should have no arguments */
1560 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1561 eat_until_matching_token('(');
1562 /* we have already consumed '(', so we stop before ')', eat it */
1564 attribute->invalid = true;
1568 * Parse one GNU attribute.
1570 * Note that attribute names can be specified WITH or WITHOUT
1571 * double underscores, ie const or __const__.
1573 * The following attributes are parsed without arguments
1598 * no_instrument_function
1599 * warn_unused_result
1616 * externally_visible
1624 * The following attributes are parsed with arguments
1625 * aligned( const expression )
1626 * alias( string literal )
1627 * section( string literal )
1628 * format( identifier, const expression, const expression )
1629 * format_arg( const expression )
1630 * tls_model( string literal )
1631 * visibility( string literal )
1632 * regparm( const expression )
1633 * model( string leteral )
1634 * trap_exit( const expression )
1635 * sp_switch( string literal )
1637 * The following attributes might have arguments
1638 * weak_ref( string literal )
1639 * non_null( const expression // ',' )
1640 * interrupt( string literal )
1641 * sentinel( constant expression )
1643 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1645 gnu_attribute_t *head = *attributes;
1646 gnu_attribute_t *last = *attributes;
1647 decl_modifiers_t modifiers = 0;
1648 gnu_attribute_t *attribute;
1650 eat(T___attribute__);
1651 expect('(', end_error);
1652 expect('(', end_error);
1654 if (token.type != ')') {
1655 /* find the end of the list */
1657 while (last->next != NULL)
1661 /* non-empty attribute list */
1664 if (token.type == T_const) {
1666 } else if (token.type == T_volatile) {
1668 } else if (token.type == T_cdecl) {
1669 /* __attribute__((cdecl)), WITH ms mode */
1671 } else if (token.type == T_IDENTIFIER) {
1672 const symbol_t *sym = token.v.symbol;
1675 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1682 for (i = 0; i < GNU_AK_LAST; ++i) {
1683 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1686 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1689 if (kind == GNU_AK_LAST) {
1690 if (warning.attribute)
1691 warningf(HERE, "'%s' attribute directive ignored", name);
1693 /* skip possible arguments */
1694 if (token.type == '(') {
1695 eat_until_matching_token(')');
1698 /* check for arguments */
1699 attribute = allocate_gnu_attribute(kind);
1700 if (token.type == '(') {
1702 if (token.type == ')') {
1703 /* empty args are allowed */
1706 attribute->has_arguments = true;
1710 case GNU_AK_VOLATILE:
1715 case GNU_AK_NOCOMMON:
1717 case GNU_AK_NOTSHARED:
1718 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1719 case GNU_AK_WARN_UNUSED_RESULT:
1720 case GNU_AK_LONGCALL:
1721 case GNU_AK_SHORTCALL:
1722 case GNU_AK_LONG_CALL:
1723 case GNU_AK_SHORT_CALL:
1724 case GNU_AK_FUNCTION_VECTOR:
1725 case GNU_AK_INTERRUPT_HANDLER:
1726 case GNU_AK_NMI_HANDLER:
1727 case GNU_AK_NESTING:
1731 case GNU_AK_EIGTHBIT_DATA:
1732 case GNU_AK_TINY_DATA:
1733 case GNU_AK_SAVEALL:
1734 case GNU_AK_FLATTEN:
1735 case GNU_AK_SSEREGPARM:
1736 case GNU_AK_EXTERNALLY_VISIBLE:
1737 case GNU_AK_RETURN_TWICE:
1738 case GNU_AK_MAY_ALIAS:
1739 case GNU_AK_MS_STRUCT:
1740 case GNU_AK_GCC_STRUCT:
1743 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1744 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1745 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1746 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1747 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1748 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1749 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1750 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1751 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1752 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1753 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1754 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1755 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1756 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1757 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1758 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1759 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1760 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1761 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1763 case GNU_AK_ALIGNED:
1764 /* __align__ may be used without an argument */
1765 if (attribute->has_arguments) {
1766 parse_gnu_attribute_const_arg(attribute);
1770 case GNU_AK_FORMAT_ARG:
1771 case GNU_AK_REGPARM:
1772 case GNU_AK_TRAP_EXIT:
1773 if (!attribute->has_arguments) {
1774 /* should have arguments */
1775 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1776 attribute->invalid = true;
1778 parse_gnu_attribute_const_arg(attribute);
1781 case GNU_AK_SECTION:
1782 case GNU_AK_SP_SWITCH:
1783 if (!attribute->has_arguments) {
1784 /* should have arguments */
1785 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1786 attribute->invalid = true;
1788 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1791 if (!attribute->has_arguments) {
1792 /* should have arguments */
1793 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1794 attribute->invalid = true;
1796 parse_gnu_attribute_format_args(attribute);
1798 case GNU_AK_WEAKREF:
1799 /* may have one string argument */
1800 if (attribute->has_arguments)
1801 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1803 case GNU_AK_NONNULL:
1804 if (attribute->has_arguments)
1805 parse_gnu_attribute_const_arg_list(attribute);
1807 case GNU_AK_TLS_MODEL:
1808 if (!attribute->has_arguments) {
1809 /* should have arguments */
1810 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1812 parse_gnu_attribute_tls_model_arg(attribute);
1814 case GNU_AK_VISIBILITY:
1815 if (!attribute->has_arguments) {
1816 /* should have arguments */
1817 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1819 parse_gnu_attribute_visibility_arg(attribute);
1822 if (!attribute->has_arguments) {
1823 /* should have arguments */
1824 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1826 parse_gnu_attribute_model_arg(attribute);
1830 if (!attribute->has_arguments) {
1831 /* should have arguments */
1832 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1834 parse_gnu_attribute_mode_arg(attribute);
1837 case GNU_AK_INTERRUPT:
1838 /* may have one string argument */
1839 if (attribute->has_arguments)
1840 parse_gnu_attribute_interrupt_arg(attribute);
1842 case GNU_AK_SENTINEL:
1843 /* may have one string argument */
1844 if (attribute->has_arguments)
1845 parse_gnu_attribute_const_arg(attribute);
1848 /* already handled */
1852 check_no_argument(attribute, name);
1855 if (attribute != NULL) {
1857 last->next = attribute;
1860 head = last = attribute;
1864 if (token.type != ',')
1869 expect(')', end_error);
1870 expect(')', end_error);
1878 * Parse GNU attributes.
1880 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1882 decl_modifiers_t modifiers = 0;
1885 switch (token.type) {
1886 case T___attribute__:
1887 modifiers |= parse_gnu_attribute(attributes);
1892 expect('(', end_error);
1893 if (token.type != T_STRING_LITERAL) {
1894 parse_error_expected("while parsing assembler attribute",
1895 T_STRING_LITERAL, NULL);
1896 eat_until_matching_token('(');
1899 parse_string_literals();
1901 expect(')', end_error);
1904 case T_cdecl: modifiers |= DM_CDECL; break;
1905 case T__fastcall: modifiers |= DM_FASTCALL; break;
1906 case T__stdcall: modifiers |= DM_STDCALL; break;
1909 /* TODO record modifier */
1911 warningf(HERE, "Ignoring declaration modifier %K", &token);
1915 default: return modifiers;
1922 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1924 static entity_t *determine_lhs_ent(expression_t *const expr,
1927 switch (expr->kind) {
1928 case EXPR_REFERENCE: {
1929 entity_t *const entity = expr->reference.entity;
1930 /* we should only find variables as lvalues... */
1931 if (entity->base.kind != ENTITY_VARIABLE
1932 && entity->base.kind != ENTITY_PARAMETER)
1938 case EXPR_ARRAY_ACCESS: {
1939 expression_t *const ref = expr->array_access.array_ref;
1940 entity_t * ent = NULL;
1941 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1942 ent = determine_lhs_ent(ref, lhs_ent);
1945 mark_vars_read(expr->select.compound, lhs_ent);
1947 mark_vars_read(expr->array_access.index, lhs_ent);
1952 if (is_type_compound(skip_typeref(expr->base.type))) {
1953 return determine_lhs_ent(expr->select.compound, lhs_ent);
1955 mark_vars_read(expr->select.compound, lhs_ent);
1960 case EXPR_UNARY_DEREFERENCE: {
1961 expression_t *const val = expr->unary.value;
1962 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1964 return determine_lhs_ent(val->unary.value, lhs_ent);
1966 mark_vars_read(val, NULL);
1972 mark_vars_read(expr, NULL);
1977 #define ENT_ANY ((entity_t*)-1)
1980 * Mark declarations, which are read. This is used to detect variables, which
1984 * x is not marked as "read", because it is only read to calculate its own new
1988 * x and y are not detected as "not read", because multiple variables are
1991 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1993 switch (expr->kind) {
1994 case EXPR_REFERENCE: {
1995 entity_t *const entity = expr->reference.entity;
1996 if (entity->kind != ENTITY_VARIABLE
1997 && entity->kind != ENTITY_PARAMETER)
2000 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2001 if (entity->kind == ENTITY_VARIABLE) {
2002 entity->variable.read = true;
2004 entity->parameter.read = true;
2011 // TODO respect pure/const
2012 mark_vars_read(expr->call.function, NULL);
2013 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2014 mark_vars_read(arg->expression, NULL);
2018 case EXPR_CONDITIONAL:
2019 // TODO lhs_decl should depend on whether true/false have an effect
2020 mark_vars_read(expr->conditional.condition, NULL);
2021 if (expr->conditional.true_expression != NULL)
2022 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2023 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2027 if (lhs_ent == ENT_ANY
2028 && !is_type_compound(skip_typeref(expr->base.type)))
2030 mark_vars_read(expr->select.compound, lhs_ent);
2033 case EXPR_ARRAY_ACCESS: {
2034 expression_t *const ref = expr->array_access.array_ref;
2035 mark_vars_read(ref, lhs_ent);
2036 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2037 mark_vars_read(expr->array_access.index, lhs_ent);
2042 mark_vars_read(expr->va_arge.ap, lhs_ent);
2045 case EXPR_UNARY_CAST:
2046 /* Special case: Use void cast to mark a variable as "read" */
2047 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2052 case EXPR_UNARY_THROW:
2053 if (expr->unary.value == NULL)
2056 case EXPR_UNARY_DEREFERENCE:
2057 case EXPR_UNARY_DELETE:
2058 case EXPR_UNARY_DELETE_ARRAY:
2059 if (lhs_ent == ENT_ANY)
2063 case EXPR_UNARY_NEGATE:
2064 case EXPR_UNARY_PLUS:
2065 case EXPR_UNARY_BITWISE_NEGATE:
2066 case EXPR_UNARY_NOT:
2067 case EXPR_UNARY_TAKE_ADDRESS:
2068 case EXPR_UNARY_POSTFIX_INCREMENT:
2069 case EXPR_UNARY_POSTFIX_DECREMENT:
2070 case EXPR_UNARY_PREFIX_INCREMENT:
2071 case EXPR_UNARY_PREFIX_DECREMENT:
2072 case EXPR_UNARY_CAST_IMPLICIT:
2073 case EXPR_UNARY_ASSUME:
2075 mark_vars_read(expr->unary.value, lhs_ent);
2078 case EXPR_BINARY_ADD:
2079 case EXPR_BINARY_SUB:
2080 case EXPR_BINARY_MUL:
2081 case EXPR_BINARY_DIV:
2082 case EXPR_BINARY_MOD:
2083 case EXPR_BINARY_EQUAL:
2084 case EXPR_BINARY_NOTEQUAL:
2085 case EXPR_BINARY_LESS:
2086 case EXPR_BINARY_LESSEQUAL:
2087 case EXPR_BINARY_GREATER:
2088 case EXPR_BINARY_GREATEREQUAL:
2089 case EXPR_BINARY_BITWISE_AND:
2090 case EXPR_BINARY_BITWISE_OR:
2091 case EXPR_BINARY_BITWISE_XOR:
2092 case EXPR_BINARY_LOGICAL_AND:
2093 case EXPR_BINARY_LOGICAL_OR:
2094 case EXPR_BINARY_SHIFTLEFT:
2095 case EXPR_BINARY_SHIFTRIGHT:
2096 case EXPR_BINARY_COMMA:
2097 case EXPR_BINARY_ISGREATER:
2098 case EXPR_BINARY_ISGREATEREQUAL:
2099 case EXPR_BINARY_ISLESS:
2100 case EXPR_BINARY_ISLESSEQUAL:
2101 case EXPR_BINARY_ISLESSGREATER:
2102 case EXPR_BINARY_ISUNORDERED:
2103 mark_vars_read(expr->binary.left, lhs_ent);
2104 mark_vars_read(expr->binary.right, lhs_ent);
2107 case EXPR_BINARY_ASSIGN:
2108 case EXPR_BINARY_MUL_ASSIGN:
2109 case EXPR_BINARY_DIV_ASSIGN:
2110 case EXPR_BINARY_MOD_ASSIGN:
2111 case EXPR_BINARY_ADD_ASSIGN:
2112 case EXPR_BINARY_SUB_ASSIGN:
2113 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2114 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2115 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2116 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2117 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2118 if (lhs_ent == ENT_ANY)
2120 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2121 mark_vars_read(expr->binary.right, lhs_ent);
2126 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2132 case EXPR_CHARACTER_CONSTANT:
2133 case EXPR_WIDE_CHARACTER_CONSTANT:
2134 case EXPR_STRING_LITERAL:
2135 case EXPR_WIDE_STRING_LITERAL:
2136 case EXPR_COMPOUND_LITERAL: // TODO init?
2138 case EXPR_CLASSIFY_TYPE:
2141 case EXPR_BUILTIN_SYMBOL:
2142 case EXPR_BUILTIN_CONSTANT_P:
2143 case EXPR_BUILTIN_ADDRESS:
2144 case EXPR_BUILTIN_PREFETCH:
2146 case EXPR_STATEMENT: // TODO
2147 case EXPR_LABEL_ADDRESS:
2148 case EXPR_REFERENCE_ENUM_VALUE:
2152 panic("unhandled expression");
2155 static designator_t *parse_designation(void)
2157 designator_t *result = NULL;
2158 designator_t *last = NULL;
2161 designator_t *designator;
2162 switch (token.type) {
2164 designator = allocate_ast_zero(sizeof(designator[0]));
2165 designator->source_position = token.source_position;
2167 add_anchor_token(']');
2168 designator->array_index = parse_constant_expression();
2169 rem_anchor_token(']');
2170 expect(']', end_error);
2173 designator = allocate_ast_zero(sizeof(designator[0]));
2174 designator->source_position = token.source_position;
2176 if (token.type != T_IDENTIFIER) {
2177 parse_error_expected("while parsing designator",
2178 T_IDENTIFIER, NULL);
2181 designator->symbol = token.v.symbol;
2185 expect('=', end_error);
2189 assert(designator != NULL);
2191 last->next = designator;
2193 result = designator;
2201 static initializer_t *initializer_from_string(array_type_t *type,
2202 const string_t *const string)
2204 /* TODO: check len vs. size of array type */
2207 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2208 initializer->string.string = *string;
2213 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2214 wide_string_t *const string)
2216 /* TODO: check len vs. size of array type */
2219 initializer_t *const initializer =
2220 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2221 initializer->wide_string.string = *string;
2227 * Build an initializer from a given expression.
2229 static initializer_t *initializer_from_expression(type_t *orig_type,
2230 expression_t *expression)
2232 /* TODO check that expression is a constant expression */
2234 /* § 6.7.8.14/15 char array may be initialized by string literals */
2235 type_t *type = skip_typeref(orig_type);
2236 type_t *expr_type_orig = expression->base.type;
2237 type_t *expr_type = skip_typeref(expr_type_orig);
2238 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2239 array_type_t *const array_type = &type->array;
2240 type_t *const element_type = skip_typeref(array_type->element_type);
2242 if (element_type->kind == TYPE_ATOMIC) {
2243 atomic_type_kind_t akind = element_type->atomic.akind;
2244 switch (expression->kind) {
2245 case EXPR_STRING_LITERAL:
2246 if (akind == ATOMIC_TYPE_CHAR
2247 || akind == ATOMIC_TYPE_SCHAR
2248 || akind == ATOMIC_TYPE_UCHAR) {
2249 return initializer_from_string(array_type,
2250 &expression->string.value);
2254 case EXPR_WIDE_STRING_LITERAL: {
2255 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2256 if (get_unqualified_type(element_type) == bare_wchar_type) {
2257 return initializer_from_wide_string(array_type,
2258 &expression->wide_string.value);
2269 assign_error_t error = semantic_assign(type, expression);
2270 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2272 report_assign_error(error, type, expression, "initializer",
2273 &expression->base.source_position);
2275 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2277 if (type->kind == TYPE_BITFIELD) {
2278 type = type->bitfield.base_type;
2281 result->value.value = create_implicit_cast(expression, type);
2287 * Checks if a given expression can be used as an constant initializer.
2289 static bool is_initializer_constant(const expression_t *expression)
2291 return is_constant_expression(expression)
2292 || is_address_constant(expression);
2296 * Parses an scalar initializer.
2298 * § 6.7.8.11; eat {} without warning
2300 static initializer_t *parse_scalar_initializer(type_t *type,
2301 bool must_be_constant)
2303 /* there might be extra {} hierarchies */
2305 if (token.type == '{') {
2307 warningf(HERE, "extra curly braces around scalar initializer");
2311 } while (token.type == '{');
2314 expression_t *expression = parse_assignment_expression();
2315 mark_vars_read(expression, NULL);
2316 if (must_be_constant && !is_initializer_constant(expression)) {
2317 errorf(&expression->base.source_position,
2318 "Initialisation expression '%E' is not constant",
2322 initializer_t *initializer = initializer_from_expression(type, expression);
2324 if (initializer == NULL) {
2325 errorf(&expression->base.source_position,
2326 "expression '%E' (type '%T') doesn't match expected type '%T'",
2327 expression, expression->base.type, type);
2332 bool additional_warning_displayed = false;
2333 while (braces > 0) {
2334 if (token.type == ',') {
2337 if (token.type != '}') {
2338 if (!additional_warning_displayed && warning.other) {
2339 warningf(HERE, "additional elements in scalar initializer");
2340 additional_warning_displayed = true;
2351 * An entry in the type path.
2353 typedef struct type_path_entry_t type_path_entry_t;
2354 struct type_path_entry_t {
2355 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2357 size_t index; /**< For array types: the current index. */
2358 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2363 * A type path expression a position inside compound or array types.
2365 typedef struct type_path_t type_path_t;
2366 struct type_path_t {
2367 type_path_entry_t *path; /**< An flexible array containing the current path. */
2368 type_t *top_type; /**< type of the element the path points */
2369 size_t max_index; /**< largest index in outermost array */
2373 * Prints a type path for debugging.
2375 static __attribute__((unused)) void debug_print_type_path(
2376 const type_path_t *path)
2378 size_t len = ARR_LEN(path->path);
2380 for (size_t i = 0; i < len; ++i) {
2381 const type_path_entry_t *entry = & path->path[i];
2383 type_t *type = skip_typeref(entry->type);
2384 if (is_type_compound(type)) {
2385 /* in gcc mode structs can have no members */
2386 if (entry->v.compound_entry == NULL) {
2390 fprintf(stderr, ".%s",
2391 entry->v.compound_entry->base.symbol->string);
2392 } else if (is_type_array(type)) {
2393 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2395 fprintf(stderr, "-INVALID-");
2398 if (path->top_type != NULL) {
2399 fprintf(stderr, " (");
2400 print_type(path->top_type);
2401 fprintf(stderr, ")");
2406 * Return the top type path entry, ie. in a path
2407 * (type).a.b returns the b.
2409 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2411 size_t len = ARR_LEN(path->path);
2413 return &path->path[len-1];
2417 * Enlarge the type path by an (empty) element.
2419 static type_path_entry_t *append_to_type_path(type_path_t *path)
2421 size_t len = ARR_LEN(path->path);
2422 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2424 type_path_entry_t *result = & path->path[len];
2425 memset(result, 0, sizeof(result[0]));
2430 * Descending into a sub-type. Enter the scope of the current top_type.
2432 static void descend_into_subtype(type_path_t *path)
2434 type_t *orig_top_type = path->top_type;
2435 type_t *top_type = skip_typeref(orig_top_type);
2437 type_path_entry_t *top = append_to_type_path(path);
2438 top->type = top_type;
2440 if (is_type_compound(top_type)) {
2441 compound_t *compound = top_type->compound.compound;
2442 entity_t *entry = compound->members.entities;
2444 if (entry != NULL) {
2445 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2446 top->v.compound_entry = &entry->declaration;
2447 path->top_type = entry->declaration.type;
2449 path->top_type = NULL;
2451 } else if (is_type_array(top_type)) {
2453 path->top_type = top_type->array.element_type;
2455 assert(!is_type_valid(top_type));
2460 * Pop an entry from the given type path, ie. returning from
2461 * (type).a.b to (type).a
2463 static void ascend_from_subtype(type_path_t *path)
2465 type_path_entry_t *top = get_type_path_top(path);
2467 path->top_type = top->type;
2469 size_t len = ARR_LEN(path->path);
2470 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2474 * Pop entries from the given type path until the given
2475 * path level is reached.
2477 static void ascend_to(type_path_t *path, size_t top_path_level)
2479 size_t len = ARR_LEN(path->path);
2481 while (len > top_path_level) {
2482 ascend_from_subtype(path);
2483 len = ARR_LEN(path->path);
2487 static bool walk_designator(type_path_t *path, const designator_t *designator,
2488 bool used_in_offsetof)
2490 for (; designator != NULL; designator = designator->next) {
2491 type_path_entry_t *top = get_type_path_top(path);
2492 type_t *orig_type = top->type;
2494 type_t *type = skip_typeref(orig_type);
2496 if (designator->symbol != NULL) {
2497 symbol_t *symbol = designator->symbol;
2498 if (!is_type_compound(type)) {
2499 if (is_type_valid(type)) {
2500 errorf(&designator->source_position,
2501 "'.%Y' designator used for non-compound type '%T'",
2505 top->type = type_error_type;
2506 top->v.compound_entry = NULL;
2507 orig_type = type_error_type;
2509 compound_t *compound = type->compound.compound;
2510 entity_t *iter = compound->members.entities;
2511 for (; iter != NULL; iter = iter->base.next) {
2512 if (iter->base.symbol == symbol) {
2517 errorf(&designator->source_position,
2518 "'%T' has no member named '%Y'", orig_type, symbol);
2521 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2522 if (used_in_offsetof) {
2523 type_t *real_type = skip_typeref(iter->declaration.type);
2524 if (real_type->kind == TYPE_BITFIELD) {
2525 errorf(&designator->source_position,
2526 "offsetof designator '%Y' may not specify bitfield",
2532 top->type = orig_type;
2533 top->v.compound_entry = &iter->declaration;
2534 orig_type = iter->declaration.type;
2537 expression_t *array_index = designator->array_index;
2538 assert(designator->array_index != NULL);
2540 if (!is_type_array(type)) {
2541 if (is_type_valid(type)) {
2542 errorf(&designator->source_position,
2543 "[%E] designator used for non-array type '%T'",
2544 array_index, orig_type);
2549 long index = fold_constant(array_index);
2550 if (!used_in_offsetof) {
2552 errorf(&designator->source_position,
2553 "array index [%E] must be positive", array_index);
2554 } else if (type->array.size_constant) {
2555 long array_size = type->array.size;
2556 if (index >= array_size) {
2557 errorf(&designator->source_position,
2558 "designator [%E] (%d) exceeds array size %d",
2559 array_index, index, array_size);
2564 top->type = orig_type;
2565 top->v.index = (size_t) index;
2566 orig_type = type->array.element_type;
2568 path->top_type = orig_type;
2570 if (designator->next != NULL) {
2571 descend_into_subtype(path);
2580 static void advance_current_object(type_path_t *path, size_t top_path_level)
2582 type_path_entry_t *top = get_type_path_top(path);
2584 type_t *type = skip_typeref(top->type);
2585 if (is_type_union(type)) {
2586 /* in unions only the first element is initialized */
2587 top->v.compound_entry = NULL;
2588 } else if (is_type_struct(type)) {
2589 declaration_t *entry = top->v.compound_entry;
2591 entity_t *next_entity = entry->base.next;
2592 if (next_entity != NULL) {
2593 assert(is_declaration(next_entity));
2594 entry = &next_entity->declaration;
2599 top->v.compound_entry = entry;
2600 if (entry != NULL) {
2601 path->top_type = entry->type;
2604 } else if (is_type_array(type)) {
2605 assert(is_type_array(type));
2609 if (!type->array.size_constant || top->v.index < type->array.size) {
2613 assert(!is_type_valid(type));
2617 /* we're past the last member of the current sub-aggregate, try if we
2618 * can ascend in the type hierarchy and continue with another subobject */
2619 size_t len = ARR_LEN(path->path);
2621 if (len > top_path_level) {
2622 ascend_from_subtype(path);
2623 advance_current_object(path, top_path_level);
2625 path->top_type = NULL;
2630 * skip until token is found.
2632 static void skip_until(int type)
2634 while (token.type != type) {
2635 if (token.type == T_EOF)
2642 * skip any {...} blocks until a closing bracket is reached.
2644 static void skip_initializers(void)
2646 if (token.type == '{')
2649 while (token.type != '}') {
2650 if (token.type == T_EOF)
2652 if (token.type == '{') {
2660 static initializer_t *create_empty_initializer(void)
2662 static initializer_t empty_initializer
2663 = { .list = { { INITIALIZER_LIST }, 0 } };
2664 return &empty_initializer;
2668 * Parse a part of an initialiser for a struct or union,
2670 static initializer_t *parse_sub_initializer(type_path_t *path,
2671 type_t *outer_type, size_t top_path_level,
2672 parse_initializer_env_t *env)
2674 if (token.type == '}') {
2675 /* empty initializer */
2676 return create_empty_initializer();
2679 type_t *orig_type = path->top_type;
2680 type_t *type = NULL;
2682 if (orig_type == NULL) {
2683 /* We are initializing an empty compound. */
2685 type = skip_typeref(orig_type);
2688 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2691 designator_t *designator = NULL;
2692 if (token.type == '.' || token.type == '[') {
2693 designator = parse_designation();
2694 goto finish_designator;
2695 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2696 /* GNU-style designator ("identifier: value") */
2697 designator = allocate_ast_zero(sizeof(designator[0]));
2698 designator->source_position = token.source_position;
2699 designator->symbol = token.v.symbol;
2704 /* reset path to toplevel, evaluate designator from there */
2705 ascend_to(path, top_path_level);
2706 if (!walk_designator(path, designator, false)) {
2707 /* can't continue after designation error */
2711 initializer_t *designator_initializer
2712 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2713 designator_initializer->designator.designator = designator;
2714 ARR_APP1(initializer_t*, initializers, designator_initializer);
2716 orig_type = path->top_type;
2717 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2722 if (token.type == '{') {
2723 if (type != NULL && is_type_scalar(type)) {
2724 sub = parse_scalar_initializer(type, env->must_be_constant);
2728 if (env->entity != NULL) {
2730 "extra brace group at end of initializer for '%Y'",
2731 env->entity->base.symbol);
2733 errorf(HERE, "extra brace group at end of initializer");
2736 descend_into_subtype(path);
2738 add_anchor_token('}');
2739 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2741 rem_anchor_token('}');
2744 ascend_from_subtype(path);
2745 expect('}', end_error);
2747 expect('}', end_error);
2748 goto error_parse_next;
2752 /* must be an expression */
2753 expression_t *expression = parse_assignment_expression();
2754 mark_vars_read(expression, NULL);
2756 if (env->must_be_constant && !is_initializer_constant(expression)) {
2757 errorf(&expression->base.source_position,
2758 "Initialisation expression '%E' is not constant",
2763 /* we are already outside, ... */
2764 type_t *const outer_type_skip = skip_typeref(outer_type);
2765 if (is_type_compound(outer_type_skip) &&
2766 !outer_type_skip->compound.compound->complete) {
2767 goto error_parse_next;
2772 /* handle { "string" } special case */
2773 if ((expression->kind == EXPR_STRING_LITERAL
2774 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2775 && outer_type != NULL) {
2776 sub = initializer_from_expression(outer_type, expression);
2778 if (token.type == ',') {
2781 if (token.type != '}' && warning.other) {
2782 warningf(HERE, "excessive elements in initializer for type '%T'",
2785 /* TODO: eat , ... */
2790 /* descend into subtypes until expression matches type */
2792 orig_type = path->top_type;
2793 type = skip_typeref(orig_type);
2795 sub = initializer_from_expression(orig_type, expression);
2799 if (!is_type_valid(type)) {
2802 if (is_type_scalar(type)) {
2803 errorf(&expression->base.source_position,
2804 "expression '%E' doesn't match expected type '%T'",
2805 expression, orig_type);
2809 descend_into_subtype(path);
2813 /* update largest index of top array */
2814 const type_path_entry_t *first = &path->path[0];
2815 type_t *first_type = first->type;
2816 first_type = skip_typeref(first_type);
2817 if (is_type_array(first_type)) {
2818 size_t index = first->v.index;
2819 if (index > path->max_index)
2820 path->max_index = index;
2824 /* append to initializers list */
2825 ARR_APP1(initializer_t*, initializers, sub);
2828 if (warning.other) {
2829 if (env->entity != NULL) {
2830 warningf(HERE, "excess elements in struct initializer for '%Y'",
2831 env->entity->base.symbol);
2833 warningf(HERE, "excess elements in struct initializer");
2839 if (token.type == '}') {
2842 expect(',', end_error);
2843 if (token.type == '}') {
2848 /* advance to the next declaration if we are not at the end */
2849 advance_current_object(path, top_path_level);
2850 orig_type = path->top_type;
2851 if (orig_type != NULL)
2852 type = skip_typeref(orig_type);
2858 size_t len = ARR_LEN(initializers);
2859 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2860 initializer_t *result = allocate_ast_zero(size);
2861 result->kind = INITIALIZER_LIST;
2862 result->list.len = len;
2863 memcpy(&result->list.initializers, initializers,
2864 len * sizeof(initializers[0]));
2866 DEL_ARR_F(initializers);
2867 ascend_to(path, top_path_level+1);
2872 skip_initializers();
2873 DEL_ARR_F(initializers);
2874 ascend_to(path, top_path_level+1);
2879 * Parses an initializer. Parsers either a compound literal
2880 * (env->declaration == NULL) or an initializer of a declaration.
2882 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2884 type_t *type = skip_typeref(env->type);
2885 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2886 initializer_t *result;
2888 if (is_type_scalar(type)) {
2889 result = parse_scalar_initializer(type, env->must_be_constant);
2890 } else if (token.type == '{') {
2894 memset(&path, 0, sizeof(path));
2895 path.top_type = env->type;
2896 path.path = NEW_ARR_F(type_path_entry_t, 0);
2898 descend_into_subtype(&path);
2900 add_anchor_token('}');
2901 result = parse_sub_initializer(&path, env->type, 1, env);
2902 rem_anchor_token('}');
2904 max_index = path.max_index;
2905 DEL_ARR_F(path.path);
2907 expect('}', end_error);
2909 /* parse_scalar_initializer() also works in this case: we simply
2910 * have an expression without {} around it */
2911 result = parse_scalar_initializer(type, env->must_be_constant);
2914 /* § 6.7.8:22 array initializers for arrays with unknown size determine
2915 * the array type size */
2916 if (is_type_array(type) && type->array.size_expression == NULL
2917 && result != NULL) {
2919 switch (result->kind) {
2920 case INITIALIZER_LIST:
2921 assert(max_index != 0xdeadbeaf);
2922 size = max_index + 1;
2925 case INITIALIZER_STRING:
2926 size = result->string.string.size;
2929 case INITIALIZER_WIDE_STRING:
2930 size = result->wide_string.string.size;
2933 case INITIALIZER_DESIGNATOR:
2934 case INITIALIZER_VALUE:
2935 /* can happen for parse errors */
2940 internal_errorf(HERE, "invalid initializer type");
2943 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2944 cnst->base.type = type_size_t;
2945 cnst->conste.v.int_value = size;
2947 type_t *new_type = duplicate_type(type);
2949 new_type->array.size_expression = cnst;
2950 new_type->array.size_constant = true;
2951 new_type->array.has_implicit_size = true;
2952 new_type->array.size = size;
2953 env->type = new_type;
2961 static void append_entity(scope_t *scope, entity_t *entity)
2963 if (scope->last_entity != NULL) {
2964 scope->last_entity->base.next = entity;
2966 scope->entities = entity;
2968 scope->last_entity = entity;
2972 static compound_t *parse_compound_type_specifier(bool is_struct)
2974 gnu_attribute_t *attributes = NULL;
2975 decl_modifiers_t modifiers = 0;
2982 symbol_t *symbol = NULL;
2983 compound_t *compound = NULL;
2985 if (token.type == T___attribute__) {
2986 modifiers |= parse_attributes(&attributes);
2989 if (token.type == T_IDENTIFIER) {
2990 symbol = token.v.symbol;
2993 namespace_tag_t const namespc =
2994 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2995 entity_t *entity = get_entity(symbol, namespc);
2996 if (entity != NULL) {
2997 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2998 compound = &entity->compound;
2999 if (compound->base.parent_scope != current_scope &&
3000 (token.type == '{' || token.type == ';')) {
3001 /* we're in an inner scope and have a definition. Shadow
3002 * existing definition in outer scope */
3004 } else if (compound->complete && token.type == '{') {
3005 assert(symbol != NULL);
3006 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3007 is_struct ? "struct" : "union", symbol,
3008 &compound->base.source_position);
3009 /* clear members in the hope to avoid further errors */
3010 compound->members.entities = NULL;
3013 } else if (token.type != '{') {
3015 parse_error_expected("while parsing struct type specifier",
3016 T_IDENTIFIER, '{', NULL);
3018 parse_error_expected("while parsing union type specifier",
3019 T_IDENTIFIER, '{', NULL);
3025 if (compound == NULL) {
3026 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3027 entity_t *entity = allocate_entity_zero(kind);
3028 compound = &entity->compound;
3030 compound->base.namespc =
3031 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3032 compound->base.source_position = token.source_position;
3033 compound->base.symbol = symbol;
3034 compound->base.parent_scope = current_scope;
3035 if (symbol != NULL) {
3036 environment_push(entity);
3038 append_entity(current_scope, entity);
3041 if (token.type == '{') {
3042 parse_compound_type_entries(compound);
3043 modifiers |= parse_attributes(&attributes);
3045 if (symbol == NULL) {
3046 assert(anonymous_entity == NULL);
3047 anonymous_entity = (entity_t*)compound;
3051 compound->modifiers |= modifiers;
3055 static void parse_enum_entries(type_t *const enum_type)
3059 if (token.type == '}') {
3060 errorf(HERE, "empty enum not allowed");
3065 add_anchor_token('}');
3067 if (token.type != T_IDENTIFIER) {
3068 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3070 rem_anchor_token('}');
3074 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3075 entity->enum_value.enum_type = enum_type;
3076 entity->base.symbol = token.v.symbol;
3077 entity->base.source_position = token.source_position;
3080 if (token.type == '=') {
3082 expression_t *value = parse_constant_expression();
3084 value = create_implicit_cast(value, enum_type);
3085 entity->enum_value.value = value;
3090 record_entity(entity, false);
3092 if (token.type != ',')
3095 } while (token.type != '}');
3096 rem_anchor_token('}');
3098 expect('}', end_error);
3104 static type_t *parse_enum_specifier(void)
3106 gnu_attribute_t *attributes = NULL;
3111 if (token.type == T_IDENTIFIER) {
3112 symbol = token.v.symbol;
3115 entity = get_entity(symbol, NAMESPACE_ENUM);
3116 if (entity != NULL) {
3117 assert(entity->kind == ENTITY_ENUM);
3118 if (entity->base.parent_scope != current_scope &&
3119 (token.type == '{' || token.type == ';')) {
3120 /* we're in an inner scope and have a definition. Shadow
3121 * existing definition in outer scope */
3123 } else if (entity->enume.complete && token.type == '{') {
3124 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3125 symbol, &entity->base.source_position);
3128 } else if (token.type != '{') {
3129 parse_error_expected("while parsing enum type specifier",
3130 T_IDENTIFIER, '{', NULL);
3137 if (entity == NULL) {
3138 entity = allocate_entity_zero(ENTITY_ENUM);
3139 entity->base.namespc = NAMESPACE_ENUM;
3140 entity->base.source_position = token.source_position;
3141 entity->base.symbol = symbol;
3142 entity->base.parent_scope = current_scope;
3145 type_t *const type = allocate_type_zero(TYPE_ENUM);
3146 type->enumt.enume = &entity->enume;
3147 type->enumt.akind = ATOMIC_TYPE_INT;
3149 if (token.type == '{') {
3150 if (symbol != NULL) {
3151 environment_push(entity);
3153 append_entity(current_scope, entity);
3154 entity->enume.complete = true;
3156 parse_enum_entries(type);
3157 parse_attributes(&attributes);
3159 if (symbol == NULL) {
3160 assert(anonymous_entity == NULL);
3161 anonymous_entity = entity;
3163 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3164 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3172 * if a symbol is a typedef to another type, return true
3174 static bool is_typedef_symbol(symbol_t *symbol)
3176 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3177 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3180 static type_t *parse_typeof(void)
3186 expect('(', end_error);
3187 add_anchor_token(')');
3189 expression_t *expression = NULL;
3191 bool old_type_prop = in_type_prop;
3192 bool old_gcc_extension = in_gcc_extension;
3193 in_type_prop = true;
3195 while (token.type == T___extension__) {
3196 /* This can be a prefix to a typename or an expression. */
3198 in_gcc_extension = true;
3200 switch (token.type) {
3202 if (is_typedef_symbol(token.v.symbol)) {
3203 type = parse_typename();
3205 expression = parse_expression();
3206 type = expression->base.type;
3211 type = parse_typename();
3215 expression = parse_expression();
3216 type = expression->base.type;
3219 in_type_prop = old_type_prop;
3220 in_gcc_extension = old_gcc_extension;
3222 rem_anchor_token(')');
3223 expect(')', end_error);
3225 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3226 typeof_type->typeoft.expression = expression;
3227 typeof_type->typeoft.typeof_type = type;
3234 typedef enum specifiers_t {
3235 SPECIFIER_SIGNED = 1 << 0,
3236 SPECIFIER_UNSIGNED = 1 << 1,
3237 SPECIFIER_LONG = 1 << 2,
3238 SPECIFIER_INT = 1 << 3,
3239 SPECIFIER_DOUBLE = 1 << 4,
3240 SPECIFIER_CHAR = 1 << 5,
3241 SPECIFIER_WCHAR_T = 1 << 6,
3242 SPECIFIER_SHORT = 1 << 7,
3243 SPECIFIER_LONG_LONG = 1 << 8,
3244 SPECIFIER_FLOAT = 1 << 9,
3245 SPECIFIER_BOOL = 1 << 10,
3246 SPECIFIER_VOID = 1 << 11,
3247 SPECIFIER_INT8 = 1 << 12,
3248 SPECIFIER_INT16 = 1 << 13,
3249 SPECIFIER_INT32 = 1 << 14,
3250 SPECIFIER_INT64 = 1 << 15,
3251 SPECIFIER_INT128 = 1 << 16,
3252 SPECIFIER_COMPLEX = 1 << 17,
3253 SPECIFIER_IMAGINARY = 1 << 18,
3256 static type_t *create_builtin_type(symbol_t *const symbol,
3257 type_t *const real_type)
3259 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3260 type->builtin.symbol = symbol;
3261 type->builtin.real_type = real_type;
3262 return identify_new_type(type);
3265 static type_t *get_typedef_type(symbol_t *symbol)
3267 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3268 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3271 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3272 type->typedeft.typedefe = &entity->typedefe;
3278 * check for the allowed MS alignment values.
3280 static bool check_alignment_value(long long intvalue)
3282 if (intvalue < 1 || intvalue > 8192) {
3283 errorf(HERE, "illegal alignment value");
3286 unsigned v = (unsigned)intvalue;
3287 for (unsigned i = 1; i <= 8192; i += i) {
3291 errorf(HERE, "alignment must be power of two");
3295 #define DET_MOD(name, tag) do { \
3296 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3297 *modifiers |= tag; \
3300 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3302 decl_modifiers_t *modifiers = &specifiers->modifiers;
3305 if (token.type == T_restrict) {
3307 DET_MOD(restrict, DM_RESTRICT);
3309 } else if (token.type != T_IDENTIFIER)
3311 symbol_t *symbol = token.v.symbol;
3312 if (symbol == sym_align) {
3314 expect('(', end_error);
3315 if (token.type != T_INTEGER)
3317 if (check_alignment_value(token.v.intvalue)) {
3318 if (specifiers->alignment != 0 && warning.other)
3319 warningf(HERE, "align used more than once");
3320 specifiers->alignment = (unsigned char)token.v.intvalue;
3323 expect(')', end_error);
3324 } else if (symbol == sym_allocate) {
3326 expect('(', end_error);
3327 if (token.type != T_IDENTIFIER)
3329 (void)token.v.symbol;
3330 expect(')', end_error);
3331 } else if (symbol == sym_dllimport) {
3333 DET_MOD(dllimport, DM_DLLIMPORT);
3334 } else if (symbol == sym_dllexport) {
3336 DET_MOD(dllexport, DM_DLLEXPORT);
3337 } else if (symbol == sym_thread) {
3339 DET_MOD(thread, DM_THREAD);
3340 } else if (symbol == sym_naked) {
3342 DET_MOD(naked, DM_NAKED);
3343 } else if (symbol == sym_noinline) {
3345 DET_MOD(noinline, DM_NOINLINE);
3346 } else if (symbol == sym_returns_twice) {
3348 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3349 } else if (symbol == sym_noreturn) {
3351 DET_MOD(noreturn, DM_NORETURN);
3352 } else if (symbol == sym_nothrow) {
3354 DET_MOD(nothrow, DM_NOTHROW);
3355 } else if (symbol == sym_novtable) {
3357 DET_MOD(novtable, DM_NOVTABLE);
3358 } else if (symbol == sym_property) {
3360 expect('(', end_error);
3362 bool is_get = false;
3363 if (token.type != T_IDENTIFIER)
3365 if (token.v.symbol == sym_get) {
3367 } else if (token.v.symbol == sym_put) {
3369 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3373 expect('=', end_error);
3374 if (token.type != T_IDENTIFIER)
3377 if (specifiers->get_property_sym != NULL) {
3378 errorf(HERE, "get property name already specified");
3380 specifiers->get_property_sym = token.v.symbol;
3383 if (specifiers->put_property_sym != NULL) {
3384 errorf(HERE, "put property name already specified");
3386 specifiers->put_property_sym = token.v.symbol;
3390 if (token.type == ',') {
3396 expect(')', end_error);
3397 } else if (symbol == sym_selectany) {
3399 DET_MOD(selectany, DM_SELECTANY);
3400 } else if (symbol == sym_uuid) {
3402 expect('(', end_error);
3403 if (token.type != T_STRING_LITERAL)
3406 expect(')', end_error);
3407 } else if (symbol == sym_deprecated) {
3409 if (specifiers->deprecated != 0 && warning.other)
3410 warningf(HERE, "deprecated used more than once");
3411 specifiers->deprecated = true;
3412 if (token.type == '(') {
3414 if (token.type == T_STRING_LITERAL) {
3415 specifiers->deprecated_string = token.v.string.begin;
3418 errorf(HERE, "string literal expected");
3420 expect(')', end_error);
3422 } else if (symbol == sym_noalias) {
3424 DET_MOD(noalias, DM_NOALIAS);
3427 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3429 if (token.type == '(')
3433 if (token.type == ',')
3440 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3442 entity_t *entity = allocate_entity_zero(kind);
3443 entity->base.source_position = *HERE;
3444 entity->base.symbol = symbol;
3445 if (is_declaration(entity)) {
3446 entity->declaration.type = type_error_type;
3447 entity->declaration.implicit = true;
3448 } else if (kind == ENTITY_TYPEDEF) {
3449 entity->typedefe.type = type_error_type;
3450 entity->typedefe.builtin = true;
3452 if (kind != ENTITY_COMPOUND_MEMBER)
3453 record_entity(entity, false);
3457 static void parse_microsoft_based(based_spec_t *based_spec)
3459 if (token.type != T_IDENTIFIER) {
3460 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3463 symbol_t *symbol = token.v.symbol;
3464 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3466 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3467 errorf(HERE, "'%Y' is not a variable name.", symbol);
3468 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3470 variable_t *variable = &entity->variable;
3472 if (based_spec->base_variable != NULL) {
3473 errorf(HERE, "__based type qualifier specified more than once");
3475 based_spec->source_position = token.source_position;
3476 based_spec->base_variable = variable;
3478 type_t *const type = variable->base.type;
3480 if (is_type_valid(type)) {
3481 if (! is_type_pointer(skip_typeref(type))) {
3482 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3484 if (variable->base.base.parent_scope != file_scope) {
3485 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3493 * Finish the construction of a struct type by calculating
3494 * its size, offsets, alignment.
3496 static void finish_struct_type(compound_type_t *type)
3498 assert(type->compound != NULL);
3500 compound_t *compound = type->compound;
3501 if (!compound->complete)
3506 il_alignment_t alignment = 1;
3507 bool need_pad = false;
3509 entity_t *entry = compound->members.entities;
3510 for (; entry != NULL; entry = entry->base.next) {
3511 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3514 type_t *m_type = skip_typeref(entry->declaration.type);
3515 if (! is_type_valid(m_type)) {
3516 /* simply ignore errors here */
3519 il_alignment_t m_alignment = m_type->base.alignment;
3520 if (m_alignment > alignment)
3521 alignment = m_alignment;
3523 offset = (size + m_alignment - 1) & -m_alignment;
3527 entry->compound_member.offset = offset;
3528 size = offset + m_type->base.size;
3530 if (type->base.alignment != 0) {
3531 alignment = type->base.alignment;
3534 offset = (size + alignment - 1) & -alignment;
3539 if (warning.padded) {
3540 warningf(&compound->base.source_position, "'%T' needs padding", type);
3543 if (compound->modifiers & DM_PACKED && warning.packed) {
3544 warningf(&compound->base.source_position,
3545 "superfluous packed attribute on '%T'", type);
3549 type->base.size = offset;
3550 type->base.alignment = alignment;
3554 * Finish the construction of an union type by calculating
3555 * its size and alignment.
3557 static void finish_union_type(compound_type_t *type)
3559 assert(type->compound != NULL);
3561 compound_t *compound = type->compound;
3562 if (! compound->complete)
3566 il_alignment_t alignment = 1;
3568 entity_t *entry = compound->members.entities;
3569 for (; entry != NULL; entry = entry->base.next) {
3570 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3573 type_t *m_type = skip_typeref(entry->declaration.type);
3574 if (! is_type_valid(m_type))
3577 entry->compound_member.offset = 0;
3578 if (m_type->base.size > size)
3579 size = m_type->base.size;
3580 if (m_type->base.alignment > alignment)
3581 alignment = m_type->base.alignment;
3583 if (type->base.alignment != 0) {
3584 alignment = type->base.alignment;
3586 size = (size + alignment - 1) & -alignment;
3587 type->base.size = size;
3588 type->base.alignment = alignment;
3591 static type_t *handle_attribute_mode(const gnu_attribute_t *attribute,
3594 type_t *type = skip_typeref(orig_type);
3596 /* at least: byte, word, pointer, list of machine modes
3597 * __XXX___ is interpreted as XXX */
3599 /* This isn't really correct, the backend should provide a list of machine
3600 * specific modes (according to gcc philosophy that is...) */
3601 const char *symbol_str = attribute->u.symbol->string;
3602 bool sign = is_type_signed(type);
3603 atomic_type_kind_t akind;
3604 if (strcmp_underscore("QI", symbol_str) == 0 ||
3605 strcmp_underscore("byte", symbol_str) == 0) {
3606 akind = sign ? ATOMIC_TYPE_CHAR : ATOMIC_TYPE_UCHAR;
3607 } else if (strcmp_underscore("HI", symbol_str) == 0) {
3608 akind = sign ? ATOMIC_TYPE_SHORT : ATOMIC_TYPE_USHORT;
3609 } else if (strcmp_underscore("SI", symbol_str) == 0
3610 || strcmp_underscore("word", symbol_str) == 0
3611 || strcmp_underscore("pointer", symbol_str) == 0) {
3612 akind = sign ? ATOMIC_TYPE_INT : ATOMIC_TYPE_UINT;
3613 } else if (strcmp_underscore("DI", symbol_str) == 0) {
3614 akind = sign ? ATOMIC_TYPE_LONGLONG : ATOMIC_TYPE_ULONGLONG;
3617 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
3621 if (type->kind == TYPE_ATOMIC) {
3622 type_t *copy = duplicate_type(type);
3623 copy->atomic.akind = akind;
3624 return identify_new_type(copy);
3625 } else if (type->kind == TYPE_ENUM) {
3626 type_t *copy = duplicate_type(type);
3627 copy->enumt.akind = akind;
3628 return identify_new_type(copy);
3629 } else if (is_type_pointer(type)) {
3630 warningf(HERE, "__attribute__((mode)) on pointers not implemented yet (ignored)");
3634 errorf(HERE, "__attribute__((mode)) only allowed on integer, enum or pointer type");
3638 static type_t *handle_type_attributes(const gnu_attribute_t *attributes,
3641 const gnu_attribute_t *attribute = attributes;
3642 for ( ; attribute != NULL; attribute = attribute->next) {
3643 if (attribute->invalid)
3646 if (attribute->kind == GNU_AK_MODE) {
3647 type = handle_attribute_mode(attribute, type);
3648 } else if (attribute->kind == GNU_AK_ALIGNED) {
3649 int alignment = 32; /* TODO: fill in maximum useful alignment for
3651 if (attribute->has_arguments)
3652 alignment = attribute->u.argument;
3654 type_t *copy = duplicate_type(type);
3655 copy->base.alignment = attribute->u.argument;
3656 type = identify_new_type(copy);
3663 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3665 type_t *type = NULL;
3666 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3667 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3668 unsigned type_specifiers = 0;
3669 bool newtype = false;
3670 bool saw_error = false;
3671 bool old_gcc_extension = in_gcc_extension;
3673 specifiers->source_position = token.source_position;
3676 specifiers->modifiers
3677 |= parse_attributes(&specifiers->gnu_attributes);
3679 switch (token.type) {
3681 #define MATCH_STORAGE_CLASS(token, class) \
3683 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3684 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3686 specifiers->storage_class = class; \
3687 if (specifiers->thread_local) \
3688 goto check_thread_storage_class; \
3692 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3693 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3694 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3695 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3696 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3700 expect('(', end_error);
3701 add_anchor_token(')');
3702 parse_microsoft_extended_decl_modifier(specifiers);
3703 rem_anchor_token(')');
3704 expect(')', end_error);
3708 if (specifiers->thread_local) {
3709 errorf(HERE, "duplicate '__thread'");
3711 specifiers->thread_local = true;
3712 check_thread_storage_class:
3713 switch (specifiers->storage_class) {
3714 case STORAGE_CLASS_EXTERN:
3715 case STORAGE_CLASS_NONE:
3716 case STORAGE_CLASS_STATIC:
3720 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3721 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3722 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3723 wrong_thread_stoarge_class:
3724 errorf(HERE, "'__thread' used with '%s'", wrong);
3731 /* type qualifiers */
3732 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3734 qualifiers |= qualifier; \
3738 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3739 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3740 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3741 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3742 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3743 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3744 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3745 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3747 case T___extension__:
3749 in_gcc_extension = true;
3752 /* type specifiers */
3753 #define MATCH_SPECIFIER(token, specifier, name) \
3755 if (type_specifiers & specifier) { \
3756 errorf(HERE, "multiple " name " type specifiers given"); \
3758 type_specifiers |= specifier; \
3763 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3764 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3765 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3766 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3767 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3768 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3769 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3770 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3771 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3772 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3773 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3774 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3775 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3776 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3777 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3778 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3779 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3780 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3782 case T__forceinline:
3783 /* only in microsoft mode */
3784 specifiers->modifiers |= DM_FORCEINLINE;
3789 specifiers->is_inline = true;
3793 if (type_specifiers & SPECIFIER_LONG_LONG) {
3794 errorf(HERE, "multiple type specifiers given");
3795 } else if (type_specifiers & SPECIFIER_LONG) {
3796 type_specifiers |= SPECIFIER_LONG_LONG;
3798 type_specifiers |= SPECIFIER_LONG;
3804 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3806 type->compound.compound = parse_compound_type_specifier(true);
3807 finish_struct_type(&type->compound);
3811 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3812 type->compound.compound = parse_compound_type_specifier(false);
3813 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3814 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3815 finish_union_type(&type->compound);
3819 type = parse_enum_specifier();
3822 type = parse_typeof();
3824 case T___builtin_va_list:
3825 type = duplicate_type(type_valist);
3829 case T_IDENTIFIER: {
3830 /* only parse identifier if we haven't found a type yet */
3831 if (type != NULL || type_specifiers != 0) {
3832 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3833 * declaration, so it doesn't generate errors about expecting '(' or
3835 switch (look_ahead(1)->type) {
3842 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3846 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3851 goto finish_specifiers;
3855 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3856 if (typedef_type == NULL) {
3857 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3858 * declaration, so it doesn't generate 'implicit int' followed by more
3859 * errors later on. */
3860 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3866 errorf(HERE, "%K does not name a type", &token);
3869 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3871 type = allocate_type_zero(TYPE_TYPEDEF);
3872 type->typedeft.typedefe = &entity->typedefe;
3876 if (la1_type == '&' || la1_type == '*')
3877 goto finish_specifiers;
3882 goto finish_specifiers;
3887 type = typedef_type;
3891 /* function specifier */
3893 goto finish_specifiers;
3898 specifiers->modifiers
3899 |= parse_attributes(&specifiers->gnu_attributes);
3901 in_gcc_extension = old_gcc_extension;
3903 if (type == NULL || (saw_error && type_specifiers != 0)) {
3904 atomic_type_kind_t atomic_type;
3906 /* match valid basic types */
3907 switch (type_specifiers) {
3908 case SPECIFIER_VOID:
3909 atomic_type = ATOMIC_TYPE_VOID;
3911 case SPECIFIER_WCHAR_T:
3912 atomic_type = ATOMIC_TYPE_WCHAR_T;
3914 case SPECIFIER_CHAR:
3915 atomic_type = ATOMIC_TYPE_CHAR;
3917 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3918 atomic_type = ATOMIC_TYPE_SCHAR;
3920 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3921 atomic_type = ATOMIC_TYPE_UCHAR;
3923 case SPECIFIER_SHORT:
3924 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3925 case SPECIFIER_SHORT | SPECIFIER_INT:
3926 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3927 atomic_type = ATOMIC_TYPE_SHORT;
3929 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3930 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3931 atomic_type = ATOMIC_TYPE_USHORT;
3934 case SPECIFIER_SIGNED:
3935 case SPECIFIER_SIGNED | SPECIFIER_INT:
3936 atomic_type = ATOMIC_TYPE_INT;
3938 case SPECIFIER_UNSIGNED:
3939 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3940 atomic_type = ATOMIC_TYPE_UINT;
3942 case SPECIFIER_LONG:
3943 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3944 case SPECIFIER_LONG | SPECIFIER_INT:
3945 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3946 atomic_type = ATOMIC_TYPE_LONG;
3948 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3949 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3950 atomic_type = ATOMIC_TYPE_ULONG;
3953 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3954 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3955 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3956 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3958 atomic_type = ATOMIC_TYPE_LONGLONG;
3959 goto warn_about_long_long;
3961 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3962 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3964 atomic_type = ATOMIC_TYPE_ULONGLONG;
3965 warn_about_long_long:
3966 if (warning.long_long) {
3967 warningf(&specifiers->source_position,
3968 "ISO C90 does not support 'long long'");
3972 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3973 atomic_type = unsigned_int8_type_kind;
3976 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3977 atomic_type = unsigned_int16_type_kind;
3980 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3981 atomic_type = unsigned_int32_type_kind;
3984 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3985 atomic_type = unsigned_int64_type_kind;
3988 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3989 atomic_type = unsigned_int128_type_kind;
3992 case SPECIFIER_INT8:
3993 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3994 atomic_type = int8_type_kind;
3997 case SPECIFIER_INT16:
3998 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3999 atomic_type = int16_type_kind;
4002 case SPECIFIER_INT32:
4003 case SPECIFIER_SIGNED | SPECIFIER_INT32:
4004 atomic_type = int32_type_kind;
4007 case SPECIFIER_INT64:
4008 case SPECIFIER_SIGNED | SPECIFIER_INT64:
4009 atomic_type = int64_type_kind;
4012 case SPECIFIER_INT128:
4013 case SPECIFIER_SIGNED | SPECIFIER_INT128:
4014 atomic_type = int128_type_kind;
4017 case SPECIFIER_FLOAT:
4018 atomic_type = ATOMIC_TYPE_FLOAT;
4020 case SPECIFIER_DOUBLE:
4021 atomic_type = ATOMIC_TYPE_DOUBLE;
4023 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
4024 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4026 case SPECIFIER_BOOL:
4027 atomic_type = ATOMIC_TYPE_BOOL;
4029 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
4030 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
4031 atomic_type = ATOMIC_TYPE_FLOAT;
4033 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4034 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4035 atomic_type = ATOMIC_TYPE_DOUBLE;
4037 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4038 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4039 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4042 /* invalid specifier combination, give an error message */
4043 if (type_specifiers == 0) {
4047 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4048 if (!(c_mode & _CXX) && !strict_mode) {
4049 if (warning.implicit_int) {
4050 warningf(HERE, "no type specifiers in declaration, using 'int'");
4052 atomic_type = ATOMIC_TYPE_INT;
4055 errorf(HERE, "no type specifiers given in declaration");
4057 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4058 (type_specifiers & SPECIFIER_UNSIGNED)) {
4059 errorf(HERE, "signed and unsigned specifiers given");
4060 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4061 errorf(HERE, "only integer types can be signed or unsigned");
4063 errorf(HERE, "multiple datatypes in declaration");
4068 if (type_specifiers & SPECIFIER_COMPLEX) {
4069 type = allocate_type_zero(TYPE_COMPLEX);
4070 type->complex.akind = atomic_type;
4071 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4072 type = allocate_type_zero(TYPE_IMAGINARY);
4073 type->imaginary.akind = atomic_type;
4075 type = allocate_type_zero(TYPE_ATOMIC);
4076 type->atomic.akind = atomic_type;
4078 type->base.alignment = get_atomic_type_alignment(atomic_type);
4079 unsigned const size = get_atomic_type_size(atomic_type);
4081 type_specifiers & SPECIFIER_COMPLEX ? size * 2 : size;
4083 } else if (type_specifiers != 0) {
4084 errorf(HERE, "multiple datatypes in declaration");
4087 /* FIXME: check type qualifiers here */
4089 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
4090 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4091 type->base.qualifiers = qualifiers;
4092 type->base.modifiers = modifiers;
4095 type = identify_new_type(type);
4097 type = typehash_insert(type);
4100 type = handle_type_attributes(specifiers->gnu_attributes, type);
4101 specifiers->type = type;
4105 specifiers->type = type_error_type;
4109 static type_qualifiers_t parse_type_qualifiers(void)
4111 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4114 switch (token.type) {
4115 /* type qualifiers */
4116 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4117 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4118 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4119 /* microsoft extended type modifiers */
4120 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4121 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4122 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4123 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4124 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4133 * Parses an K&R identifier list
4135 static void parse_identifier_list(scope_t *scope)
4138 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4139 entity->base.source_position = token.source_position;
4140 entity->base.namespc = NAMESPACE_NORMAL;
4141 entity->base.symbol = token.v.symbol;
4142 /* a K&R parameter has no type, yet */
4146 append_entity(scope, entity);
4148 if (token.type != ',') {
4152 } while (token.type == T_IDENTIFIER);
4155 static entity_t *parse_parameter(void)
4157 declaration_specifiers_t specifiers;
4158 memset(&specifiers, 0, sizeof(specifiers));
4160 parse_declaration_specifiers(&specifiers);
4162 entity_t *entity = parse_declarator(&specifiers,
4163 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4164 anonymous_entity = NULL;
4168 static void semantic_parameter_incomplete(const entity_t *entity)
4170 assert(entity->kind == ENTITY_PARAMETER);
4172 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4173 * list in a function declarator that is part of a
4174 * definition of that function shall not have
4175 * incomplete type. */
4176 type_t *type = skip_typeref(entity->declaration.type);
4177 if (is_type_incomplete(type)) {
4178 errorf(&entity->base.source_position,
4179 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4180 entity->declaration.type);
4185 * Parses function type parameters (and optionally creates variable_t entities
4186 * for them in a scope)
4188 static void parse_parameters(function_type_t *type, scope_t *scope)
4191 add_anchor_token(')');
4192 int saved_comma_state = save_and_reset_anchor_state(',');
4194 if (token.type == T_IDENTIFIER &&
4195 !is_typedef_symbol(token.v.symbol)) {
4196 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4197 if (la1_type == ',' || la1_type == ')') {
4198 type->kr_style_parameters = true;
4199 type->unspecified_parameters = true;
4200 parse_identifier_list(scope);
4201 goto parameters_finished;
4205 if (token.type == ')') {
4206 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4207 if (!(c_mode & _CXX))
4208 type->unspecified_parameters = true;
4209 goto parameters_finished;
4212 function_parameter_t *parameter;
4213 function_parameter_t *last_parameter = NULL;
4216 switch (token.type) {
4219 type->variadic = true;
4220 goto parameters_finished;
4223 case T___extension__:
4226 entity_t *entity = parse_parameter();
4227 if (entity->kind == ENTITY_TYPEDEF) {
4228 errorf(&entity->base.source_position,
4229 "typedef not allowed as function parameter");
4232 assert(is_declaration(entity));
4234 /* func(void) is not a parameter */
4235 if (last_parameter == NULL
4236 && token.type == ')'
4237 && entity->base.symbol == NULL
4238 && skip_typeref(entity->declaration.type) == type_void) {
4239 goto parameters_finished;
4241 semantic_parameter_incomplete(entity);
4243 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4244 memset(parameter, 0, sizeof(parameter[0]));
4245 parameter->type = entity->declaration.type;
4247 if (scope != NULL) {
4248 append_entity(scope, entity);
4251 if (last_parameter != NULL) {
4252 last_parameter->next = parameter;
4254 type->parameters = parameter;
4256 last_parameter = parameter;
4261 goto parameters_finished;
4263 if (token.type != ',') {
4264 goto parameters_finished;
4270 parameters_finished:
4271 rem_anchor_token(')');
4272 expect(')', end_error);
4275 restore_anchor_state(',', saved_comma_state);
4278 typedef enum construct_type_kind_t {
4281 CONSTRUCT_REFERENCE,
4284 } construct_type_kind_t;
4286 typedef struct construct_type_t construct_type_t;
4287 struct construct_type_t {
4288 construct_type_kind_t kind;
4289 construct_type_t *next;
4292 typedef struct parsed_pointer_t parsed_pointer_t;
4293 struct parsed_pointer_t {
4294 construct_type_t construct_type;
4295 type_qualifiers_t type_qualifiers;
4296 variable_t *base_variable; /**< MS __based extension. */
4299 typedef struct parsed_reference_t parsed_reference_t;
4300 struct parsed_reference_t {
4301 construct_type_t construct_type;
4304 typedef struct construct_function_type_t construct_function_type_t;
4305 struct construct_function_type_t {
4306 construct_type_t construct_type;
4307 type_t *function_type;
4310 typedef struct parsed_array_t parsed_array_t;
4311 struct parsed_array_t {
4312 construct_type_t construct_type;
4313 type_qualifiers_t type_qualifiers;
4319 typedef struct construct_base_type_t construct_base_type_t;
4320 struct construct_base_type_t {
4321 construct_type_t construct_type;
4325 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4329 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4330 memset(pointer, 0, sizeof(pointer[0]));
4331 pointer->construct_type.kind = CONSTRUCT_POINTER;
4332 pointer->type_qualifiers = parse_type_qualifiers();
4333 pointer->base_variable = base_variable;
4335 return &pointer->construct_type;
4338 static construct_type_t *parse_reference_declarator(void)
4342 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4343 memset(reference, 0, sizeof(reference[0]));
4344 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4346 return (construct_type_t*)reference;
4349 static construct_type_t *parse_array_declarator(void)
4352 add_anchor_token(']');
4354 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4355 memset(array, 0, sizeof(array[0]));
4356 array->construct_type.kind = CONSTRUCT_ARRAY;
4358 if (token.type == T_static) {
4359 array->is_static = true;
4363 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4364 if (type_qualifiers != 0) {
4365 if (token.type == T_static) {
4366 array->is_static = true;
4370 array->type_qualifiers = type_qualifiers;
4372 if (token.type == '*' && look_ahead(1)->type == ']') {
4373 array->is_variable = true;
4375 } else if (token.type != ']') {
4376 expression_t *const size = parse_assignment_expression();
4378 mark_vars_read(size, NULL);
4381 rem_anchor_token(']');
4382 expect(']', end_error);
4385 return &array->construct_type;
4388 static construct_type_t *parse_function_declarator(scope_t *scope,
4389 decl_modifiers_t modifiers)
4391 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4392 function_type_t *ftype = &type->function;
4394 ftype->linkage = current_linkage;
4396 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4397 case DM_NONE: break;
4398 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4399 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4400 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4401 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4404 errorf(HERE, "multiple calling conventions in declaration");
4408 parse_parameters(ftype, scope);
4410 construct_function_type_t *construct_function_type =
4411 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4412 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4413 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4414 construct_function_type->function_type = type;
4416 return &construct_function_type->construct_type;
4419 typedef struct parse_declarator_env_t {
4420 decl_modifiers_t modifiers;
4422 source_position_t source_position;
4424 } parse_declarator_env_t;
4426 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4427 bool may_be_abstract)
4429 /* construct a single linked list of construct_type_t's which describe
4430 * how to construct the final declarator type */
4431 construct_type_t *first = NULL;
4432 construct_type_t *last = NULL;
4433 gnu_attribute_t *attributes = NULL;
4435 decl_modifiers_t modifiers = parse_attributes(&attributes);
4437 /* MS __based extension */
4438 based_spec_t base_spec;
4439 base_spec.base_variable = NULL;
4442 construct_type_t *type;
4443 switch (token.type) {
4445 if (!(c_mode & _CXX))
4446 errorf(HERE, "references are only available for C++");
4447 if (base_spec.base_variable != NULL && warning.other) {
4448 warningf(&base_spec.source_position,
4449 "__based does not precede a pointer operator, ignored");
4451 type = parse_reference_declarator();
4453 base_spec.base_variable = NULL;
4457 type = parse_pointer_declarator(base_spec.base_variable);
4459 base_spec.base_variable = NULL;
4464 expect('(', end_error);
4465 add_anchor_token(')');
4466 parse_microsoft_based(&base_spec);
4467 rem_anchor_token(')');
4468 expect(')', end_error);
4472 goto ptr_operator_end;
4483 /* TODO: find out if this is correct */
4484 modifiers |= parse_attributes(&attributes);
4487 if (base_spec.base_variable != NULL && warning.other) {
4488 warningf(&base_spec.source_position,
4489 "__based does not precede a pointer operator, ignored");
4493 modifiers |= env->modifiers;
4494 env->modifiers = modifiers;
4497 construct_type_t *inner_types = NULL;
4499 switch (token.type) {
4502 errorf(HERE, "no identifier expected in typename");
4504 env->symbol = token.v.symbol;
4505 env->source_position = token.source_position;
4510 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4511 * interpreted as ``function with no parameter specification'', rather
4512 * than redundant parentheses around the omitted identifier. */
4513 if (look_ahead(1)->type != ')') {
4515 add_anchor_token(')');
4516 inner_types = parse_inner_declarator(env, may_be_abstract);
4517 if (inner_types != NULL) {
4518 /* All later declarators only modify the return type */
4521 rem_anchor_token(')');
4522 expect(')', end_error);
4526 if (may_be_abstract)
4528 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4533 construct_type_t *p = last;
4536 construct_type_t *type;
4537 switch (token.type) {
4539 scope_t *scope = NULL;
4541 scope = &env->parameters;
4543 type = parse_function_declarator(scope, modifiers);
4547 type = parse_array_declarator();
4550 goto declarator_finished;
4553 /* insert in the middle of the list (behind p) */
4555 type->next = p->next;
4566 declarator_finished:
4567 /* append inner_types at the end of the list, we don't to set last anymore
4568 * as it's not needed anymore */
4570 assert(first == NULL);
4571 first = inner_types;
4573 last->next = inner_types;
4581 static void parse_declaration_attributes(entity_t *entity)
4583 gnu_attribute_t *attributes = NULL;
4584 decl_modifiers_t modifiers = parse_attributes(&attributes);
4590 if (entity->kind == ENTITY_TYPEDEF) {
4591 modifiers |= entity->typedefe.modifiers;
4592 type = entity->typedefe.type;
4594 assert(is_declaration(entity));
4595 modifiers |= entity->declaration.modifiers;
4596 type = entity->declaration.type;
4601 gnu_attribute_t *attribute = attributes;
4602 for ( ; attribute != NULL; attribute = attribute->next) {
4603 if (attribute->invalid)
4606 if (attribute->kind == GNU_AK_MODE) {
4607 type = handle_attribute_mode(attribute, type);
4608 } else if (attribute->kind == GNU_AK_ALIGNED) {
4609 int alignment = 32; /* TODO: fill in maximum usefull alignment for target machine */
4610 if (attribute->has_arguments)
4611 alignment = attribute->u.argument;
4613 if (entity->kind == ENTITY_TYPEDEF) {
4614 type_t *copy = duplicate_type(type);
4615 copy->base.alignment = attribute->u.argument;
4616 type = identify_new_type(copy);
4617 } else if(entity->kind == ENTITY_VARIABLE) {
4618 entity->variable.alignment = alignment;
4619 } else if(entity->kind == ENTITY_COMPOUND_MEMBER) {
4620 entity->compound_member.alignment = alignment;
4625 type_modifiers_t type_modifiers = type->base.modifiers;
4626 if (modifiers & DM_TRANSPARENT_UNION)
4627 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4629 if (type->base.modifiers != type_modifiers) {
4630 type_t *copy = duplicate_type(type);
4631 copy->base.modifiers = type_modifiers;
4632 type = identify_new_type(copy);
4635 if (entity->kind == ENTITY_TYPEDEF) {
4636 entity->typedefe.type = type;
4637 entity->typedefe.modifiers = modifiers;
4639 entity->declaration.type = type;
4640 entity->declaration.modifiers = modifiers;
4644 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4646 construct_type_t *iter = construct_list;
4647 for (; iter != NULL; iter = iter->next) {
4648 switch (iter->kind) {
4649 case CONSTRUCT_INVALID:
4650 internal_errorf(HERE, "invalid type construction found");
4651 case CONSTRUCT_FUNCTION: {
4652 construct_function_type_t *construct_function_type
4653 = (construct_function_type_t*) iter;
4655 type_t *function_type = construct_function_type->function_type;
4657 function_type->function.return_type = type;
4659 type_t *skipped_return_type = skip_typeref(type);
4661 if (is_type_function(skipped_return_type)) {
4662 errorf(HERE, "function returning function is not allowed");
4663 } else if (is_type_array(skipped_return_type)) {
4664 errorf(HERE, "function returning array is not allowed");
4666 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4668 "type qualifiers in return type of function type are meaningless");
4672 type = function_type;
4676 case CONSTRUCT_POINTER: {
4677 if (is_type_reference(skip_typeref(type)))
4678 errorf(HERE, "cannot declare a pointer to reference");
4680 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4681 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4685 case CONSTRUCT_REFERENCE:
4686 if (is_type_reference(skip_typeref(type)))
4687 errorf(HERE, "cannot declare a reference to reference");
4689 type = make_reference_type(type);
4692 case CONSTRUCT_ARRAY: {
4693 if (is_type_reference(skip_typeref(type)))
4694 errorf(HERE, "cannot declare an array of references");
4696 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4697 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4699 expression_t *size_expression = parsed_array->size;
4700 if (size_expression != NULL) {
4702 = create_implicit_cast(size_expression, type_size_t);
4705 array_type->base.qualifiers = parsed_array->type_qualifiers;
4706 array_type->array.element_type = type;
4707 array_type->array.is_static = parsed_array->is_static;
4708 array_type->array.is_variable = parsed_array->is_variable;
4709 array_type->array.size_expression = size_expression;
4711 if (size_expression != NULL) {
4712 if (is_constant_expression(size_expression)) {
4713 array_type->array.size_constant = true;
4714 array_type->array.size
4715 = fold_constant(size_expression);
4717 array_type->array.is_vla = true;
4721 type_t *skipped_type = skip_typeref(type);
4723 if (is_type_incomplete(skipped_type)) {
4724 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4725 } else if (is_type_function(skipped_type)) {
4726 errorf(HERE, "array of functions is not allowed");
4733 /* The function type was constructed earlier. Freeing it here will
4734 * destroy other types. */
4735 if (iter->kind == CONSTRUCT_FUNCTION) {
4736 type = typehash_insert(type);
4738 type = identify_new_type(type);
4745 static type_t *automatic_type_conversion(type_t *orig_type);
4747 static type_t *semantic_parameter(const source_position_t *pos,
4749 const declaration_specifiers_t *specifiers,
4752 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4753 * shall be adjusted to ``qualified pointer to type'',
4755 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4756 * type'' shall be adjusted to ``pointer to function
4757 * returning type'', as in 6.3.2.1. */
4758 type = automatic_type_conversion(type);
4760 if (specifiers->is_inline && is_type_valid(type)) {
4761 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4764 /* §6.9.1:6 The declarations in the declaration list shall contain
4765 * no storage-class specifier other than register and no
4766 * initializations. */
4767 if (specifiers->thread_local || (
4768 specifiers->storage_class != STORAGE_CLASS_NONE &&
4769 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4771 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4774 /* delay test for incomplete type, because we might have (void)
4775 * which is legal but incomplete... */
4780 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4781 declarator_flags_t flags)
4783 parse_declarator_env_t env;
4784 memset(&env, 0, sizeof(env));
4785 env.modifiers = specifiers->modifiers;
4787 construct_type_t *construct_type =
4788 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4790 construct_declarator_type(construct_type, specifiers->type);
4791 type_t *type = skip_typeref(orig_type);
4793 if (construct_type != NULL) {
4794 obstack_free(&temp_obst, construct_type);
4798 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4799 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4800 entity->base.symbol = env.symbol;
4801 entity->base.source_position = env.source_position;
4802 entity->typedefe.type = orig_type;
4804 if (anonymous_entity != NULL) {
4805 if (is_type_compound(type)) {
4806 assert(anonymous_entity->compound.alias == NULL);
4807 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4808 anonymous_entity->kind == ENTITY_UNION);
4809 anonymous_entity->compound.alias = entity;
4810 anonymous_entity = NULL;
4811 } else if (is_type_enum(type)) {
4812 assert(anonymous_entity->enume.alias == NULL);
4813 assert(anonymous_entity->kind == ENTITY_ENUM);
4814 anonymous_entity->enume.alias = entity;
4815 anonymous_entity = NULL;
4819 /* create a declaration type entity */
4820 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4821 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4823 if (env.symbol != NULL) {
4824 if (specifiers->is_inline && is_type_valid(type)) {
4825 errorf(&env.source_position,
4826 "compound member '%Y' declared 'inline'", env.symbol);
4829 if (specifiers->thread_local ||
4830 specifiers->storage_class != STORAGE_CLASS_NONE) {
4831 errorf(&env.source_position,
4832 "compound member '%Y' must have no storage class",
4836 } else if (flags & DECL_IS_PARAMETER) {
4837 orig_type = semantic_parameter(&env.source_position, orig_type,
4838 specifiers, env.symbol);
4840 entity = allocate_entity_zero(ENTITY_PARAMETER);
4841 } else if (is_type_function(type)) {
4842 entity = allocate_entity_zero(ENTITY_FUNCTION);
4844 entity->function.is_inline = specifiers->is_inline;
4845 entity->function.parameters = env.parameters;
4847 if (env.symbol != NULL) {
4848 if (specifiers->thread_local || (
4849 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4850 specifiers->storage_class != STORAGE_CLASS_NONE &&
4851 specifiers->storage_class != STORAGE_CLASS_STATIC
4853 errorf(&env.source_position,
4854 "invalid storage class for function '%Y'", env.symbol);
4858 entity = allocate_entity_zero(ENTITY_VARIABLE);
4860 entity->variable.get_property_sym = specifiers->get_property_sym;
4861 entity->variable.put_property_sym = specifiers->put_property_sym;
4863 entity->variable.thread_local = specifiers->thread_local;
4865 if (env.symbol != NULL) {
4866 if (specifiers->is_inline && is_type_valid(type)) {
4867 errorf(&env.source_position,
4868 "variable '%Y' declared 'inline'", env.symbol);
4871 bool invalid_storage_class = false;
4872 if (current_scope == file_scope) {
4873 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4874 specifiers->storage_class != STORAGE_CLASS_NONE &&
4875 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4876 invalid_storage_class = true;
4879 if (specifiers->thread_local &&
4880 specifiers->storage_class == STORAGE_CLASS_NONE) {
4881 invalid_storage_class = true;
4884 if (invalid_storage_class) {
4885 errorf(&env.source_position,
4886 "invalid storage class for variable '%Y'", env.symbol);
4891 if (env.symbol != NULL) {
4892 entity->base.symbol = env.symbol;
4893 entity->base.source_position = env.source_position;
4895 entity->base.source_position = specifiers->source_position;
4897 entity->base.namespc = NAMESPACE_NORMAL;
4898 entity->declaration.type = orig_type;
4899 entity->declaration.modifiers = env.modifiers;
4900 entity->declaration.deprecated_string = specifiers->deprecated_string;
4902 storage_class_t storage_class = specifiers->storage_class;
4903 entity->declaration.declared_storage_class = storage_class;
4905 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4906 storage_class = STORAGE_CLASS_AUTO;
4907 entity->declaration.storage_class = storage_class;
4910 parse_declaration_attributes(entity);
4915 static type_t *parse_abstract_declarator(type_t *base_type)
4917 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4919 type_t *result = construct_declarator_type(construct_type, base_type);
4920 if (construct_type != NULL) {
4921 obstack_free(&temp_obst, construct_type);
4928 * Check if the declaration of main is suspicious. main should be a
4929 * function with external linkage, returning int, taking either zero
4930 * arguments, two, or three arguments of appropriate types, ie.
4932 * int main([ int argc, char **argv [, char **env ] ]).
4934 * @param decl the declaration to check
4935 * @param type the function type of the declaration
4937 static void check_type_of_main(const entity_t *entity)
4939 const source_position_t *pos = &entity->base.source_position;
4940 if (entity->kind != ENTITY_FUNCTION) {
4941 warningf(pos, "'main' is not a function");
4945 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4946 warningf(pos, "'main' is normally a non-static function");
4949 type_t *type = skip_typeref(entity->declaration.type);
4950 assert(is_type_function(type));
4952 function_type_t *func_type = &type->function;
4953 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4954 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4955 func_type->return_type);
4957 const function_parameter_t *parm = func_type->parameters;
4959 type_t *const first_type = parm->type;
4960 if (!types_compatible(skip_typeref(first_type), type_int)) {
4962 "first argument of 'main' should be 'int', but is '%T'",
4967 type_t *const second_type = parm->type;
4968 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4969 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4973 type_t *const third_type = parm->type;
4974 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4975 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4979 goto warn_arg_count;
4983 warningf(pos, "'main' takes only zero, two or three arguments");
4989 * Check if a symbol is the equal to "main".
4991 static bool is_sym_main(const symbol_t *const sym)
4993 return strcmp(sym->string, "main") == 0;
4996 static void error_redefined_as_different_kind(const source_position_t *pos,
4997 const entity_t *old, entity_kind_t new_kind)
4999 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
5000 get_entity_kind_name(old->kind), old->base.symbol,
5001 get_entity_kind_name(new_kind), &old->base.source_position);
5004 static bool is_error_entity(entity_t *const ent)
5006 if (is_declaration(ent)) {
5007 return is_type_valid(skip_typeref(ent->declaration.type));
5008 } else if (ent->kind == ENTITY_TYPEDEF) {
5009 return is_type_valid(skip_typeref(ent->typedefe.type));
5015 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
5016 * for various problems that occur for multiple definitions
5018 static entity_t *record_entity(entity_t *entity, const bool is_definition)
5020 const symbol_t *const symbol = entity->base.symbol;
5021 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
5022 const source_position_t *pos = &entity->base.source_position;
5024 /* can happen in error cases */
5028 entity_t *previous_entity = get_entity(symbol, namespc);
5029 /* pushing the same entity twice will break the stack structure */
5030 assert(previous_entity != entity);
5032 if (entity->kind == ENTITY_FUNCTION) {
5033 type_t *const orig_type = entity->declaration.type;
5034 type_t *const type = skip_typeref(orig_type);
5036 assert(is_type_function(type));
5037 if (type->function.unspecified_parameters &&
5038 warning.strict_prototypes &&
5039 previous_entity == NULL) {
5040 warningf(pos, "function declaration '%#T' is not a prototype",
5044 if (warning.main && current_scope == file_scope
5045 && is_sym_main(symbol)) {
5046 check_type_of_main(entity);
5050 if (is_declaration(entity) &&
5051 warning.nested_externs &&
5052 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5053 current_scope != file_scope) {
5054 warningf(pos, "nested extern declaration of '%#T'",
5055 entity->declaration.type, symbol);
5058 if (previous_entity != NULL &&
5059 previous_entity->base.parent_scope == ¤t_function->parameters &&
5060 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5061 assert(previous_entity->kind == ENTITY_PARAMETER);
5063 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5064 entity->declaration.type, symbol,
5065 previous_entity->declaration.type, symbol,
5066 &previous_entity->base.source_position);
5070 if (previous_entity != NULL &&
5071 previous_entity->base.parent_scope == current_scope) {
5072 if (previous_entity->kind != entity->kind) {
5073 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
5074 error_redefined_as_different_kind(pos, previous_entity,
5079 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5080 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5081 symbol, &previous_entity->base.source_position);
5084 if (previous_entity->kind == ENTITY_TYPEDEF) {
5085 /* TODO: C++ allows this for exactly the same type */
5086 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5087 symbol, &previous_entity->base.source_position);
5091 /* at this point we should have only VARIABLES or FUNCTIONS */
5092 assert(is_declaration(previous_entity) && is_declaration(entity));
5094 declaration_t *const prev_decl = &previous_entity->declaration;
5095 declaration_t *const decl = &entity->declaration;
5097 /* can happen for K&R style declarations */
5098 if (prev_decl->type == NULL &&
5099 previous_entity->kind == ENTITY_PARAMETER &&
5100 entity->kind == ENTITY_PARAMETER) {
5101 prev_decl->type = decl->type;
5102 prev_decl->storage_class = decl->storage_class;
5103 prev_decl->declared_storage_class = decl->declared_storage_class;
5104 prev_decl->modifiers = decl->modifiers;
5105 prev_decl->deprecated_string = decl->deprecated_string;
5106 return previous_entity;
5109 type_t *const orig_type = decl->type;
5110 assert(orig_type != NULL);
5111 type_t *const type = skip_typeref(orig_type);
5112 type_t *const prev_type = skip_typeref(prev_decl->type);
5114 if (!types_compatible(type, prev_type)) {
5116 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5117 orig_type, symbol, prev_decl->type, symbol,
5118 &previous_entity->base.source_position);
5120 unsigned old_storage_class = prev_decl->storage_class;
5121 if (warning.redundant_decls &&
5124 !(prev_decl->modifiers & DM_USED) &&
5125 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5126 warningf(&previous_entity->base.source_position,
5127 "unnecessary static forward declaration for '%#T'",
5128 prev_decl->type, symbol);
5131 storage_class_t new_storage_class = decl->storage_class;
5133 /* pretend no storage class means extern for function
5134 * declarations (except if the previous declaration is neither
5135 * none nor extern) */
5136 if (entity->kind == ENTITY_FUNCTION) {
5137 /* the previous declaration could have unspecified parameters or
5138 * be a typedef, so use the new type */
5139 if (prev_type->function.unspecified_parameters || is_definition)
5140 prev_decl->type = type;
5142 switch (old_storage_class) {
5143 case STORAGE_CLASS_NONE:
5144 old_storage_class = STORAGE_CLASS_EXTERN;
5147 case STORAGE_CLASS_EXTERN:
5148 if (is_definition) {
5149 if (warning.missing_prototypes &&
5150 prev_type->function.unspecified_parameters &&
5151 !is_sym_main(symbol)) {
5152 warningf(pos, "no previous prototype for '%#T'",
5155 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5156 new_storage_class = STORAGE_CLASS_EXTERN;
5163 } else if (is_type_incomplete(prev_type)) {
5164 prev_decl->type = type;
5167 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5168 new_storage_class == STORAGE_CLASS_EXTERN) {
5169 warn_redundant_declaration:
5170 if (!is_definition &&
5171 warning.redundant_decls &&
5172 is_type_valid(prev_type) &&
5173 strcmp(previous_entity->base.source_position.input_name,
5174 "<builtin>") != 0) {
5176 "redundant declaration for '%Y' (declared %P)",
5177 symbol, &previous_entity->base.source_position);
5179 } else if (current_function == NULL) {
5180 if (old_storage_class != STORAGE_CLASS_STATIC &&
5181 new_storage_class == STORAGE_CLASS_STATIC) {
5183 "static declaration of '%Y' follows non-static declaration (declared %P)",
5184 symbol, &previous_entity->base.source_position);
5185 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5186 prev_decl->storage_class = STORAGE_CLASS_NONE;
5187 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5189 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5191 goto error_redeclaration;
5192 goto warn_redundant_declaration;
5194 } else if (is_type_valid(prev_type)) {
5195 if (old_storage_class == new_storage_class) {
5196 error_redeclaration:
5197 errorf(pos, "redeclaration of '%Y' (declared %P)",
5198 symbol, &previous_entity->base.source_position);
5201 "redeclaration of '%Y' with different linkage (declared %P)",
5202 symbol, &previous_entity->base.source_position);
5207 prev_decl->modifiers |= decl->modifiers;
5208 if (entity->kind == ENTITY_FUNCTION) {
5209 previous_entity->function.is_inline |= entity->function.is_inline;
5211 return previous_entity;
5214 if (entity->kind == ENTITY_FUNCTION) {
5215 if (is_definition &&
5216 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5217 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5218 warningf(pos, "no previous prototype for '%#T'",
5219 entity->declaration.type, symbol);
5220 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5221 warningf(pos, "no previous declaration for '%#T'",
5222 entity->declaration.type, symbol);
5225 } else if (warning.missing_declarations &&
5226 entity->kind == ENTITY_VARIABLE &&
5227 current_scope == file_scope) {
5228 declaration_t *declaration = &entity->declaration;
5229 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5230 warningf(pos, "no previous declaration for '%#T'",
5231 declaration->type, symbol);
5236 assert(entity->base.parent_scope == NULL);
5237 assert(current_scope != NULL);
5239 entity->base.parent_scope = current_scope;
5240 entity->base.namespc = NAMESPACE_NORMAL;
5241 environment_push(entity);
5242 append_entity(current_scope, entity);
5247 static void parser_error_multiple_definition(entity_t *entity,
5248 const source_position_t *source_position)
5250 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5251 entity->base.symbol, &entity->base.source_position);
5254 static bool is_declaration_specifier(const token_t *token,
5255 bool only_specifiers_qualifiers)
5257 switch (token->type) {
5262 return is_typedef_symbol(token->v.symbol);
5264 case T___extension__:
5266 return !only_specifiers_qualifiers;
5273 static void parse_init_declarator_rest(entity_t *entity)
5275 assert(is_declaration(entity));
5276 declaration_t *const declaration = &entity->declaration;
5280 type_t *orig_type = declaration->type;
5281 type_t *type = skip_typeref(orig_type);
5283 if (entity->kind == ENTITY_VARIABLE
5284 && entity->variable.initializer != NULL) {
5285 parser_error_multiple_definition(entity, HERE);
5288 bool must_be_constant = false;
5289 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5290 entity->base.parent_scope == file_scope) {
5291 must_be_constant = true;
5294 if (is_type_function(type)) {
5295 errorf(&entity->base.source_position,
5296 "function '%#T' is initialized like a variable",
5297 orig_type, entity->base.symbol);
5298 orig_type = type_error_type;
5301 parse_initializer_env_t env;
5302 env.type = orig_type;
5303 env.must_be_constant = must_be_constant;
5304 env.entity = entity;
5305 current_init_decl = entity;
5307 initializer_t *initializer = parse_initializer(&env);
5308 current_init_decl = NULL;
5310 if (entity->kind == ENTITY_VARIABLE) {
5311 /* § 6.7.5:22 array initializers for arrays with unknown size
5312 * determine the array type size */
5313 declaration->type = env.type;
5314 entity->variable.initializer = initializer;
5318 /* parse rest of a declaration without any declarator */
5319 static void parse_anonymous_declaration_rest(
5320 const declaration_specifiers_t *specifiers)
5323 anonymous_entity = NULL;
5325 if (warning.other) {
5326 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5327 specifiers->thread_local) {
5328 warningf(&specifiers->source_position,
5329 "useless storage class in empty declaration");
5332 type_t *type = specifiers->type;
5333 switch (type->kind) {
5334 case TYPE_COMPOUND_STRUCT:
5335 case TYPE_COMPOUND_UNION: {
5336 if (type->compound.compound->base.symbol == NULL) {
5337 warningf(&specifiers->source_position,
5338 "unnamed struct/union that defines no instances");
5347 warningf(&specifiers->source_position, "empty declaration");
5353 static void check_variable_type_complete(entity_t *ent)
5355 if (ent->kind != ENTITY_VARIABLE)
5358 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5359 * type for the object shall be complete [...] */
5360 declaration_t *decl = &ent->declaration;
5361 if (decl->storage_class != STORAGE_CLASS_NONE)
5364 type_t *const orig_type = decl->type;
5365 type_t *const type = skip_typeref(orig_type);
5366 if (!is_type_incomplete(type))
5369 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
5370 * are given length one. */
5371 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
5372 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5376 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5377 orig_type, ent->base.symbol);
5381 static void parse_declaration_rest(entity_t *ndeclaration,
5382 const declaration_specifiers_t *specifiers,
5383 parsed_declaration_func finished_declaration,
5384 declarator_flags_t flags)
5386 add_anchor_token(';');
5387 add_anchor_token(',');
5389 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5391 if (token.type == '=') {
5392 parse_init_declarator_rest(entity);
5393 } else if (entity->kind == ENTITY_VARIABLE) {
5394 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5395 * [...] where the extern specifier is explicitly used. */
5396 declaration_t *decl = &entity->declaration;
5397 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5398 type_t *type = decl->type;
5399 if (is_type_reference(skip_typeref(type))) {
5400 errorf(&entity->base.source_position,
5401 "reference '%#T' must be initialized",
5402 type, entity->base.symbol);
5407 check_variable_type_complete(entity);
5409 if (token.type != ',')
5413 add_anchor_token('=');
5414 ndeclaration = parse_declarator(specifiers, flags);
5415 rem_anchor_token('=');
5417 expect(';', end_error);
5420 anonymous_entity = NULL;
5421 rem_anchor_token(';');
5422 rem_anchor_token(',');
5425 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5427 symbol_t *symbol = entity->base.symbol;
5428 if (symbol == NULL) {
5429 errorf(HERE, "anonymous declaration not valid as function parameter");
5433 assert(entity->base.namespc == NAMESPACE_NORMAL);
5434 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5435 if (previous_entity == NULL
5436 || previous_entity->base.parent_scope != current_scope) {
5437 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5442 if (is_definition) {
5443 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5446 return record_entity(entity, false);
5449 static void parse_declaration(parsed_declaration_func finished_declaration,
5450 declarator_flags_t flags)
5452 declaration_specifiers_t specifiers;
5453 memset(&specifiers, 0, sizeof(specifiers));
5455 add_anchor_token(';');
5456 parse_declaration_specifiers(&specifiers);
5457 rem_anchor_token(';');
5459 if (token.type == ';') {
5460 parse_anonymous_declaration_rest(&specifiers);
5462 entity_t *entity = parse_declarator(&specifiers, flags);
5463 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5467 static type_t *get_default_promoted_type(type_t *orig_type)
5469 type_t *result = orig_type;
5471 type_t *type = skip_typeref(orig_type);
5472 if (is_type_integer(type)) {
5473 result = promote_integer(type);
5474 } else if (type == type_float) {
5475 result = type_double;
5481 static void parse_kr_declaration_list(entity_t *entity)
5483 if (entity->kind != ENTITY_FUNCTION)
5486 type_t *type = skip_typeref(entity->declaration.type);
5487 assert(is_type_function(type));
5488 if (!type->function.kr_style_parameters)
5492 add_anchor_token('{');
5494 /* push function parameters */
5495 size_t const top = environment_top();
5496 scope_t *old_scope = scope_push(&entity->function.parameters);
5498 entity_t *parameter = entity->function.parameters.entities;
5499 for ( ; parameter != NULL; parameter = parameter->base.next) {
5500 assert(parameter->base.parent_scope == NULL);
5501 parameter->base.parent_scope = current_scope;
5502 environment_push(parameter);
5505 /* parse declaration list */
5507 switch (token.type) {
5509 case T___extension__:
5510 /* This covers symbols, which are no type, too, and results in
5511 * better error messages. The typical cases are misspelled type
5512 * names and missing includes. */
5514 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5522 /* pop function parameters */
5523 assert(current_scope == &entity->function.parameters);
5524 scope_pop(old_scope);
5525 environment_pop_to(top);
5527 /* update function type */
5528 type_t *new_type = duplicate_type(type);
5530 function_parameter_t *parameters = NULL;
5531 function_parameter_t *last_parameter = NULL;
5533 parameter = entity->function.parameters.entities;
5534 for (; parameter != NULL; parameter = parameter->base.next) {
5535 type_t *parameter_type = parameter->declaration.type;
5536 if (parameter_type == NULL) {
5538 errorf(HERE, "no type specified for function parameter '%Y'",
5539 parameter->base.symbol);
5541 if (warning.implicit_int) {
5542 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5543 parameter->base.symbol);
5545 parameter_type = type_int;
5546 parameter->declaration.type = parameter_type;
5550 semantic_parameter_incomplete(parameter);
5551 parameter_type = parameter->declaration.type;
5554 * we need the default promoted types for the function type
5556 parameter_type = get_default_promoted_type(parameter_type);
5558 function_parameter_t *function_parameter
5559 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5560 memset(function_parameter, 0, sizeof(function_parameter[0]));
5562 function_parameter->type = parameter_type;
5563 if (last_parameter != NULL) {
5564 last_parameter->next = function_parameter;
5566 parameters = function_parameter;
5568 last_parameter = function_parameter;
5571 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5573 new_type->function.parameters = parameters;
5574 new_type->function.unspecified_parameters = true;
5576 new_type = identify_new_type(new_type);
5578 entity->declaration.type = new_type;
5580 rem_anchor_token('{');
5583 static bool first_err = true;
5586 * When called with first_err set, prints the name of the current function,
5589 static void print_in_function(void)
5593 diagnosticf("%s: In function '%Y':\n",
5594 current_function->base.base.source_position.input_name,
5595 current_function->base.base.symbol);
5600 * Check if all labels are defined in the current function.
5601 * Check if all labels are used in the current function.
5603 static void check_labels(void)
5605 for (const goto_statement_t *goto_statement = goto_first;
5606 goto_statement != NULL;
5607 goto_statement = goto_statement->next) {
5608 /* skip computed gotos */
5609 if (goto_statement->expression != NULL)
5612 label_t *label = goto_statement->label;
5615 if (label->base.source_position.input_name == NULL) {
5616 print_in_function();
5617 errorf(&goto_statement->base.source_position,
5618 "label '%Y' used but not defined", label->base.symbol);
5622 if (warning.unused_label) {
5623 for (const label_statement_t *label_statement = label_first;
5624 label_statement != NULL;
5625 label_statement = label_statement->next) {
5626 label_t *label = label_statement->label;
5628 if (! label->used) {
5629 print_in_function();
5630 warningf(&label_statement->base.source_position,
5631 "label '%Y' defined but not used", label->base.symbol);
5637 static void warn_unused_entity(entity_t *entity, entity_t *last)
5639 entity_t const *const end = last != NULL ? last->base.next : NULL;
5640 for (; entity != end; entity = entity->base.next) {
5641 if (!is_declaration(entity))
5644 declaration_t *declaration = &entity->declaration;
5645 if (declaration->implicit)
5648 if (!declaration->used) {
5649 print_in_function();
5650 const char *what = get_entity_kind_name(entity->kind);
5651 warningf(&entity->base.source_position, "%s '%Y' is unused",
5652 what, entity->base.symbol);
5653 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5654 print_in_function();
5655 const char *what = get_entity_kind_name(entity->kind);
5656 warningf(&entity->base.source_position, "%s '%Y' is never read",
5657 what, entity->base.symbol);
5662 static void check_unused_variables(statement_t *const stmt, void *const env)
5666 switch (stmt->kind) {
5667 case STATEMENT_DECLARATION: {
5668 declaration_statement_t const *const decls = &stmt->declaration;
5669 warn_unused_entity(decls->declarations_begin,
5670 decls->declarations_end);
5675 warn_unused_entity(stmt->fors.scope.entities, NULL);
5684 * Check declarations of current_function for unused entities.
5686 static void check_declarations(void)
5688 if (warning.unused_parameter) {
5689 const scope_t *scope = ¤t_function->parameters;
5691 /* do not issue unused warnings for main */
5692 if (!is_sym_main(current_function->base.base.symbol)) {
5693 warn_unused_entity(scope->entities, NULL);
5696 if (warning.unused_variable) {
5697 walk_statements(current_function->statement, check_unused_variables,
5702 static int determine_truth(expression_t const* const cond)
5705 !is_constant_expression(cond) ? 0 :
5706 fold_constant(cond) != 0 ? 1 :
5710 static void check_reachable(statement_t *);
5711 static bool reaches_end;
5713 static bool expression_returns(expression_t const *const expr)
5715 switch (expr->kind) {
5717 expression_t const *const func = expr->call.function;
5718 if (func->kind == EXPR_REFERENCE) {
5719 entity_t *entity = func->reference.entity;
5720 if (entity->kind == ENTITY_FUNCTION
5721 && entity->declaration.modifiers & DM_NORETURN)
5725 if (!expression_returns(func))
5728 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5729 if (!expression_returns(arg->expression))
5736 case EXPR_REFERENCE:
5737 case EXPR_REFERENCE_ENUM_VALUE:
5739 case EXPR_CHARACTER_CONSTANT:
5740 case EXPR_WIDE_CHARACTER_CONSTANT:
5741 case EXPR_STRING_LITERAL:
5742 case EXPR_WIDE_STRING_LITERAL:
5743 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5744 case EXPR_LABEL_ADDRESS:
5745 case EXPR_CLASSIFY_TYPE:
5746 case EXPR_SIZEOF: // TODO handle obscure VLA case
5749 case EXPR_BUILTIN_SYMBOL:
5750 case EXPR_BUILTIN_CONSTANT_P:
5751 case EXPR_BUILTIN_ADDRESS:
5752 case EXPR_BUILTIN_PREFETCH:
5757 case EXPR_STATEMENT: {
5758 bool old_reaches_end = reaches_end;
5759 reaches_end = false;
5760 check_reachable(expr->statement.statement);
5761 bool returns = reaches_end;
5762 reaches_end = old_reaches_end;
5766 case EXPR_CONDITIONAL:
5767 // TODO handle constant expression
5769 if (!expression_returns(expr->conditional.condition))
5772 if (expr->conditional.true_expression != NULL
5773 && expression_returns(expr->conditional.true_expression))
5776 return expression_returns(expr->conditional.false_expression);
5779 return expression_returns(expr->select.compound);
5781 case EXPR_ARRAY_ACCESS:
5783 expression_returns(expr->array_access.array_ref) &&
5784 expression_returns(expr->array_access.index);
5787 return expression_returns(expr->va_starte.ap);
5790 return expression_returns(expr->va_arge.ap);
5792 EXPR_UNARY_CASES_MANDATORY
5793 return expression_returns(expr->unary.value);
5795 case EXPR_UNARY_THROW:
5799 // TODO handle constant lhs of && and ||
5801 expression_returns(expr->binary.left) &&
5802 expression_returns(expr->binary.right);
5808 panic("unhandled expression");
5811 static bool initializer_returns(initializer_t const *const init)
5813 switch (init->kind) {
5814 case INITIALIZER_VALUE:
5815 return expression_returns(init->value.value);
5817 case INITIALIZER_LIST: {
5818 initializer_t * const* i = init->list.initializers;
5819 initializer_t * const* const end = i + init->list.len;
5820 bool returns = true;
5821 for (; i != end; ++i) {
5822 if (!initializer_returns(*i))
5828 case INITIALIZER_STRING:
5829 case INITIALIZER_WIDE_STRING:
5830 case INITIALIZER_DESIGNATOR: // designators have no payload
5833 panic("unhandled initializer");
5836 static bool noreturn_candidate;
5838 static void check_reachable(statement_t *const stmt)
5840 if (stmt->base.reachable)
5842 if (stmt->kind != STATEMENT_DO_WHILE)
5843 stmt->base.reachable = true;
5845 statement_t *last = stmt;
5847 switch (stmt->kind) {
5848 case STATEMENT_INVALID:
5849 case STATEMENT_EMPTY:
5851 next = stmt->base.next;
5854 case STATEMENT_DECLARATION: {
5855 declaration_statement_t const *const decl = &stmt->declaration;
5856 entity_t const * ent = decl->declarations_begin;
5857 entity_t const *const last = decl->declarations_end;
5859 for (;; ent = ent->base.next) {
5860 if (ent->kind == ENTITY_VARIABLE &&
5861 ent->variable.initializer != NULL &&
5862 !initializer_returns(ent->variable.initializer)) {
5869 next = stmt->base.next;
5873 case STATEMENT_COMPOUND:
5874 next = stmt->compound.statements;
5876 next = stmt->base.next;
5879 case STATEMENT_RETURN: {
5880 expression_t const *const val = stmt->returns.value;
5881 if (val == NULL || expression_returns(val))
5882 noreturn_candidate = false;
5886 case STATEMENT_IF: {
5887 if_statement_t const *const ifs = &stmt->ifs;
5888 expression_t const *const cond = ifs->condition;
5890 if (!expression_returns(cond))
5893 int const val = determine_truth(cond);
5896 check_reachable(ifs->true_statement);
5901 if (ifs->false_statement != NULL) {
5902 check_reachable(ifs->false_statement);
5906 next = stmt->base.next;
5910 case STATEMENT_SWITCH: {
5911 switch_statement_t const *const switchs = &stmt->switchs;
5912 expression_t const *const expr = switchs->expression;
5914 if (!expression_returns(expr))
5917 if (is_constant_expression(expr)) {
5918 long const val = fold_constant(expr);
5919 case_label_statement_t * defaults = NULL;
5920 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5921 if (i->expression == NULL) {
5926 if (i->first_case <= val && val <= i->last_case) {
5927 check_reachable((statement_t*)i);
5932 if (defaults != NULL) {
5933 check_reachable((statement_t*)defaults);
5937 bool has_default = false;
5938 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5939 if (i->expression == NULL)
5942 check_reachable((statement_t*)i);
5949 next = stmt->base.next;
5953 case STATEMENT_EXPRESSION: {
5954 /* Check for noreturn function call */
5955 expression_t const *const expr = stmt->expression.expression;
5956 if (!expression_returns(expr))
5959 next = stmt->base.next;
5963 case STATEMENT_CONTINUE: {
5964 statement_t *parent = stmt;
5966 parent = parent->base.parent;
5967 if (parent == NULL) /* continue not within loop */
5971 switch (parent->kind) {
5972 case STATEMENT_WHILE: goto continue_while;
5973 case STATEMENT_DO_WHILE: goto continue_do_while;
5974 case STATEMENT_FOR: goto continue_for;
5981 case STATEMENT_BREAK: {
5982 statement_t *parent = stmt;
5984 parent = parent->base.parent;
5985 if (parent == NULL) /* break not within loop/switch */
5988 switch (parent->kind) {
5989 case STATEMENT_SWITCH:
5990 case STATEMENT_WHILE:
5991 case STATEMENT_DO_WHILE:
5994 next = parent->base.next;
5995 goto found_break_parent;
6004 case STATEMENT_GOTO:
6005 if (stmt->gotos.expression) {
6006 if (!expression_returns(stmt->gotos.expression))
6009 statement_t *parent = stmt->base.parent;
6010 if (parent == NULL) /* top level goto */
6014 next = stmt->gotos.label->statement;
6015 if (next == NULL) /* missing label */
6020 case STATEMENT_LABEL:
6021 next = stmt->label.statement;
6024 case STATEMENT_CASE_LABEL:
6025 next = stmt->case_label.statement;
6028 case STATEMENT_WHILE: {
6029 while_statement_t const *const whiles = &stmt->whiles;
6030 expression_t const *const cond = whiles->condition;
6032 if (!expression_returns(cond))
6035 int const val = determine_truth(cond);
6038 check_reachable(whiles->body);
6043 next = stmt->base.next;
6047 case STATEMENT_DO_WHILE:
6048 next = stmt->do_while.body;
6051 case STATEMENT_FOR: {
6052 for_statement_t *const fors = &stmt->fors;
6054 if (fors->condition_reachable)
6056 fors->condition_reachable = true;
6058 expression_t const *const cond = fors->condition;
6063 } else if (expression_returns(cond)) {
6064 val = determine_truth(cond);
6070 check_reachable(fors->body);
6075 next = stmt->base.next;
6079 case STATEMENT_MS_TRY: {
6080 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6081 check_reachable(ms_try->try_statement);
6082 next = ms_try->final_statement;
6086 case STATEMENT_LEAVE: {
6087 statement_t *parent = stmt;
6089 parent = parent->base.parent;
6090 if (parent == NULL) /* __leave not within __try */
6093 if (parent->kind == STATEMENT_MS_TRY) {
6095 next = parent->ms_try.final_statement;
6103 panic("invalid statement kind");
6106 while (next == NULL) {
6107 next = last->base.parent;
6109 noreturn_candidate = false;
6111 type_t *const type = skip_typeref(current_function->base.type);
6112 assert(is_type_function(type));
6113 type_t *const ret = skip_typeref(type->function.return_type);
6114 if (warning.return_type &&
6115 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6116 is_type_valid(ret) &&
6117 !is_sym_main(current_function->base.base.symbol)) {
6118 warningf(&stmt->base.source_position,
6119 "control reaches end of non-void function");
6124 switch (next->kind) {
6125 case STATEMENT_INVALID:
6126 case STATEMENT_EMPTY:
6127 case STATEMENT_DECLARATION:
6128 case STATEMENT_EXPRESSION:
6130 case STATEMENT_RETURN:
6131 case STATEMENT_CONTINUE:
6132 case STATEMENT_BREAK:
6133 case STATEMENT_GOTO:
6134 case STATEMENT_LEAVE:
6135 panic("invalid control flow in function");
6137 case STATEMENT_COMPOUND:
6138 if (next->compound.stmt_expr) {
6144 case STATEMENT_SWITCH:
6145 case STATEMENT_LABEL:
6146 case STATEMENT_CASE_LABEL:
6148 next = next->base.next;
6151 case STATEMENT_WHILE: {
6153 if (next->base.reachable)
6155 next->base.reachable = true;
6157 while_statement_t const *const whiles = &next->whiles;
6158 expression_t const *const cond = whiles->condition;
6160 if (!expression_returns(cond))
6163 int const val = determine_truth(cond);
6166 check_reachable(whiles->body);
6172 next = next->base.next;
6176 case STATEMENT_DO_WHILE: {
6178 if (next->base.reachable)
6180 next->base.reachable = true;
6182 do_while_statement_t const *const dw = &next->do_while;
6183 expression_t const *const cond = dw->condition;
6185 if (!expression_returns(cond))
6188 int const val = determine_truth(cond);
6191 check_reachable(dw->body);
6197 next = next->base.next;
6201 case STATEMENT_FOR: {
6203 for_statement_t *const fors = &next->fors;
6205 fors->step_reachable = true;
6207 if (fors->condition_reachable)
6209 fors->condition_reachable = true;
6211 expression_t const *const cond = fors->condition;
6216 } else if (expression_returns(cond)) {
6217 val = determine_truth(cond);
6223 check_reachable(fors->body);
6229 next = next->base.next;
6233 case STATEMENT_MS_TRY:
6235 next = next->ms_try.final_statement;
6240 check_reachable(next);
6243 static void check_unreachable(statement_t* const stmt, void *const env)
6247 switch (stmt->kind) {
6248 case STATEMENT_DO_WHILE:
6249 if (!stmt->base.reachable) {
6250 expression_t const *const cond = stmt->do_while.condition;
6251 if (determine_truth(cond) >= 0) {
6252 warningf(&cond->base.source_position,
6253 "condition of do-while-loop is unreachable");
6258 case STATEMENT_FOR: {
6259 for_statement_t const* const fors = &stmt->fors;
6261 // if init and step are unreachable, cond is unreachable, too
6262 if (!stmt->base.reachable && !fors->step_reachable) {
6263 warningf(&stmt->base.source_position, "statement is unreachable");
6265 if (!stmt->base.reachable && fors->initialisation != NULL) {
6266 warningf(&fors->initialisation->base.source_position,
6267 "initialisation of for-statement is unreachable");
6270 if (!fors->condition_reachable && fors->condition != NULL) {
6271 warningf(&fors->condition->base.source_position,
6272 "condition of for-statement is unreachable");
6275 if (!fors->step_reachable && fors->step != NULL) {
6276 warningf(&fors->step->base.source_position,
6277 "step of for-statement is unreachable");
6283 case STATEMENT_COMPOUND:
6284 if (stmt->compound.statements != NULL)
6286 goto warn_unreachable;
6288 case STATEMENT_DECLARATION: {
6289 /* Only warn if there is at least one declarator with an initializer.
6290 * This typically occurs in switch statements. */
6291 declaration_statement_t const *const decl = &stmt->declaration;
6292 entity_t const * ent = decl->declarations_begin;
6293 entity_t const *const last = decl->declarations_end;
6295 for (;; ent = ent->base.next) {
6296 if (ent->kind == ENTITY_VARIABLE &&
6297 ent->variable.initializer != NULL) {
6298 goto warn_unreachable;
6308 if (!stmt->base.reachable)
6309 warningf(&stmt->base.source_position, "statement is unreachable");
6314 static void parse_external_declaration(void)
6316 /* function-definitions and declarations both start with declaration
6318 declaration_specifiers_t specifiers;
6319 memset(&specifiers, 0, sizeof(specifiers));
6321 add_anchor_token(';');
6322 parse_declaration_specifiers(&specifiers);
6323 rem_anchor_token(';');
6325 /* must be a declaration */
6326 if (token.type == ';') {
6327 parse_anonymous_declaration_rest(&specifiers);
6331 add_anchor_token(',');
6332 add_anchor_token('=');
6333 add_anchor_token(';');
6334 add_anchor_token('{');
6336 /* declarator is common to both function-definitions and declarations */
6337 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6339 rem_anchor_token('{');
6340 rem_anchor_token(';');
6341 rem_anchor_token('=');
6342 rem_anchor_token(',');
6344 /* must be a declaration */
6345 switch (token.type) {
6349 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6354 /* must be a function definition */
6355 parse_kr_declaration_list(ndeclaration);
6357 if (token.type != '{') {
6358 parse_error_expected("while parsing function definition", '{', NULL);
6359 eat_until_matching_token(';');
6363 assert(is_declaration(ndeclaration));
6364 type_t *const orig_type = ndeclaration->declaration.type;
6365 type_t * type = skip_typeref(orig_type);
6367 if (!is_type_function(type)) {
6368 if (is_type_valid(type)) {
6369 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6370 type, ndeclaration->base.symbol);
6374 } else if (is_typeref(orig_type)) {
6376 errorf(&ndeclaration->base.source_position,
6377 "type of function definition '%#T' is a typedef",
6378 orig_type, ndeclaration->base.symbol);
6381 if (warning.aggregate_return &&
6382 is_type_compound(skip_typeref(type->function.return_type))) {
6383 warningf(HERE, "function '%Y' returns an aggregate",
6384 ndeclaration->base.symbol);
6386 if (warning.traditional && !type->function.unspecified_parameters) {
6387 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6388 ndeclaration->base.symbol);
6390 if (warning.old_style_definition && type->function.unspecified_parameters) {
6391 warningf(HERE, "old-style function definition '%Y'",
6392 ndeclaration->base.symbol);
6395 /* § 6.7.5.3:14 a function definition with () means no
6396 * parameters (and not unspecified parameters) */
6397 if (type->function.unspecified_parameters &&
6398 type->function.parameters == NULL &&
6399 !type->function.kr_style_parameters) {
6400 type_t *copy = duplicate_type(type);
6401 copy->function.unspecified_parameters = false;
6402 type = identify_new_type(copy);
6404 ndeclaration->declaration.type = type;
6407 entity_t *const entity = record_entity(ndeclaration, true);
6408 assert(entity->kind == ENTITY_FUNCTION);
6409 assert(ndeclaration->kind == ENTITY_FUNCTION);
6411 function_t *function = &entity->function;
6412 if (ndeclaration != entity) {
6413 function->parameters = ndeclaration->function.parameters;
6415 assert(is_declaration(entity));
6416 type = skip_typeref(entity->declaration.type);
6418 /* push function parameters and switch scope */
6419 size_t const top = environment_top();
6420 scope_t *old_scope = scope_push(&function->parameters);
6422 entity_t *parameter = function->parameters.entities;
6423 for (; parameter != NULL; parameter = parameter->base.next) {
6424 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6425 parameter->base.parent_scope = current_scope;
6427 assert(parameter->base.parent_scope == NULL
6428 || parameter->base.parent_scope == current_scope);
6429 parameter->base.parent_scope = current_scope;
6430 if (parameter->base.symbol == NULL) {
6431 errorf(¶meter->base.source_position, "parameter name omitted");
6434 environment_push(parameter);
6437 if (function->statement != NULL) {
6438 parser_error_multiple_definition(entity, HERE);
6441 /* parse function body */
6442 int label_stack_top = label_top();
6443 function_t *old_current_function = current_function;
6444 current_function = function;
6445 current_parent = NULL;
6448 goto_anchor = &goto_first;
6450 label_anchor = &label_first;
6452 statement_t *const body = parse_compound_statement(false);
6453 function->statement = body;
6456 check_declarations();
6457 if (warning.return_type ||
6458 warning.unreachable_code ||
6459 (warning.missing_noreturn
6460 && !(function->base.modifiers & DM_NORETURN))) {
6461 noreturn_candidate = true;
6462 check_reachable(body);
6463 if (warning.unreachable_code)
6464 walk_statements(body, check_unreachable, NULL);
6465 if (warning.missing_noreturn &&
6466 noreturn_candidate &&
6467 !(function->base.modifiers & DM_NORETURN)) {
6468 warningf(&body->base.source_position,
6469 "function '%#T' is candidate for attribute 'noreturn'",
6470 type, entity->base.symbol);
6474 assert(current_parent == NULL);
6475 assert(current_function == function);
6476 current_function = old_current_function;
6477 label_pop_to(label_stack_top);
6480 assert(current_scope == &function->parameters);
6481 scope_pop(old_scope);
6482 environment_pop_to(top);
6485 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6486 source_position_t *source_position,
6487 const symbol_t *symbol)
6489 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6491 type->bitfield.base_type = base_type;
6492 type->bitfield.size_expression = size;
6495 type_t *skipped_type = skip_typeref(base_type);
6496 if (!is_type_integer(skipped_type)) {
6497 errorf(HERE, "bitfield base type '%T' is not an integer type",
6501 bit_size = skipped_type->base.size * 8;
6504 if (is_constant_expression(size)) {
6505 long v = fold_constant(size);
6508 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6509 } else if (v == 0) {
6510 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6511 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6512 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6514 type->bitfield.bit_size = v;
6521 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6523 entity_t *iter = compound->members.entities;
6524 for (; iter != NULL; iter = iter->base.next) {
6525 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6528 if (iter->base.symbol == symbol) {
6530 } else if (iter->base.symbol == NULL) {
6531 type_t *type = skip_typeref(iter->declaration.type);
6532 if (is_type_compound(type)) {
6534 = find_compound_entry(type->compound.compound, symbol);
6545 static void parse_compound_declarators(compound_t *compound,
6546 const declaration_specifiers_t *specifiers)
6551 if (token.type == ':') {
6552 source_position_t source_position = *HERE;
6555 type_t *base_type = specifiers->type;
6556 expression_t *size = parse_constant_expression();
6558 type_t *type = make_bitfield_type(base_type, size,
6559 &source_position, sym_anonymous);
6561 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6562 entity->base.namespc = NAMESPACE_NORMAL;
6563 entity->base.source_position = source_position;
6564 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6565 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6566 entity->declaration.modifiers = specifiers->modifiers;
6567 entity->declaration.type = type;
6568 append_entity(&compound->members, entity);
6570 entity = parse_declarator(specifiers,
6571 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6572 if (entity->kind == ENTITY_TYPEDEF) {
6573 errorf(&entity->base.source_position,
6574 "typedef not allowed as compound member");
6576 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6578 /* make sure we don't define a symbol multiple times */
6579 symbol_t *symbol = entity->base.symbol;
6580 if (symbol != NULL) {
6581 entity_t *prev = find_compound_entry(compound, symbol);
6583 errorf(&entity->base.source_position,
6584 "multiple declarations of symbol '%Y' (declared %P)",
6585 symbol, &prev->base.source_position);
6589 if (token.type == ':') {
6590 source_position_t source_position = *HERE;
6592 expression_t *size = parse_constant_expression();
6594 type_t *type = entity->declaration.type;
6595 type_t *bitfield_type = make_bitfield_type(type, size,
6596 &source_position, entity->base.symbol);
6597 entity->declaration.type = bitfield_type;
6599 type_t *orig_type = entity->declaration.type;
6600 type_t *type = skip_typeref(orig_type);
6601 if (is_type_function(type)) {
6602 errorf(&entity->base.source_position,
6603 "compound member '%Y' must not have function type '%T'",
6604 entity->base.symbol, orig_type);
6605 } else if (is_type_incomplete(type)) {
6606 /* §6.7.2.1:16 flexible array member */
6607 if (is_type_array(type) &&
6608 token.type == ';' &&
6609 look_ahead(1)->type == '}') {
6610 compound->has_flexible_member = true;
6612 errorf(&entity->base.source_position,
6613 "compound member '%Y' has incomplete type '%T'",
6614 entity->base.symbol, orig_type);
6619 append_entity(&compound->members, entity);
6623 if (token.type != ',')
6627 expect(';', end_error);
6630 anonymous_entity = NULL;
6633 static void parse_compound_type_entries(compound_t *compound)
6636 add_anchor_token('}');
6638 while (token.type != '}') {
6639 if (token.type == T_EOF) {
6640 errorf(HERE, "EOF while parsing struct");
6643 declaration_specifiers_t specifiers;
6644 memset(&specifiers, 0, sizeof(specifiers));
6645 parse_declaration_specifiers(&specifiers);
6647 parse_compound_declarators(compound, &specifiers);
6649 rem_anchor_token('}');
6653 compound->complete = true;
6656 static type_t *parse_typename(void)
6658 declaration_specifiers_t specifiers;
6659 memset(&specifiers, 0, sizeof(specifiers));
6660 parse_declaration_specifiers(&specifiers);
6661 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6662 specifiers.thread_local) {
6663 /* TODO: improve error message, user does probably not know what a
6664 * storage class is...
6666 errorf(HERE, "typename may not have a storage class");
6669 type_t *result = parse_abstract_declarator(specifiers.type);
6677 typedef expression_t* (*parse_expression_function)(void);
6678 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6680 typedef struct expression_parser_function_t expression_parser_function_t;
6681 struct expression_parser_function_t {
6682 parse_expression_function parser;
6683 precedence_t infix_precedence;
6684 parse_expression_infix_function infix_parser;
6687 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6690 * Prints an error message if an expression was expected but not read
6692 static expression_t *expected_expression_error(void)
6694 /* skip the error message if the error token was read */
6695 if (token.type != T_ERROR) {
6696 errorf(HERE, "expected expression, got token %K", &token);
6700 return create_invalid_expression();
6704 * Parse a string constant.
6706 static expression_t *parse_string_const(void)
6709 if (token.type == T_STRING_LITERAL) {
6710 string_t res = token.v.string;
6712 while (token.type == T_STRING_LITERAL) {
6713 res = concat_strings(&res, &token.v.string);
6716 if (token.type != T_WIDE_STRING_LITERAL) {
6717 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6718 /* note: that we use type_char_ptr here, which is already the
6719 * automatic converted type. revert_automatic_type_conversion
6720 * will construct the array type */
6721 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6722 cnst->string.value = res;
6726 wres = concat_string_wide_string(&res, &token.v.wide_string);
6728 wres = token.v.wide_string;
6733 switch (token.type) {
6734 case T_WIDE_STRING_LITERAL:
6735 wres = concat_wide_strings(&wres, &token.v.wide_string);
6738 case T_STRING_LITERAL:
6739 wres = concat_wide_string_string(&wres, &token.v.string);
6743 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6744 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6745 cnst->wide_string.value = wres;
6754 * Parse a boolean constant.
6756 static expression_t *parse_bool_const(bool value)
6758 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6759 cnst->base.type = type_bool;
6760 cnst->conste.v.int_value = value;
6768 * Parse an integer constant.
6770 static expression_t *parse_int_const(void)
6772 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6773 cnst->base.type = token.datatype;
6774 cnst->conste.v.int_value = token.v.intvalue;
6782 * Parse a character constant.
6784 static expression_t *parse_character_constant(void)
6786 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6787 cnst->base.type = token.datatype;
6788 cnst->conste.v.character = token.v.string;
6790 if (cnst->conste.v.character.size != 1) {
6792 errorf(HERE, "more than 1 character in character constant");
6793 } else if (warning.multichar) {
6794 warningf(HERE, "multi-character character constant");
6803 * Parse a wide character constant.
6805 static expression_t *parse_wide_character_constant(void)
6807 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6808 cnst->base.type = token.datatype;
6809 cnst->conste.v.wide_character = token.v.wide_string;
6811 if (cnst->conste.v.wide_character.size != 1) {
6813 errorf(HERE, "more than 1 character in character constant");
6814 } else if (warning.multichar) {
6815 warningf(HERE, "multi-character character constant");
6824 * Parse a float constant.
6826 static expression_t *parse_float_const(void)
6828 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6829 cnst->base.type = token.datatype;
6830 cnst->conste.v.float_value = token.v.floatvalue;
6837 static entity_t *create_implicit_function(symbol_t *symbol,
6838 const source_position_t *source_position)
6840 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6841 ntype->function.return_type = type_int;
6842 ntype->function.unspecified_parameters = true;
6843 ntype->function.linkage = LINKAGE_C;
6844 type_t *type = identify_new_type(ntype);
6846 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6847 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6848 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6849 entity->declaration.type = type;
6850 entity->declaration.implicit = true;
6851 entity->base.symbol = symbol;
6852 entity->base.source_position = *source_position;
6854 bool strict_prototypes_old = warning.strict_prototypes;
6855 warning.strict_prototypes = false;
6856 record_entity(entity, false);
6857 warning.strict_prototypes = strict_prototypes_old;
6863 * Creates a return_type (func)(argument_type) function type if not
6866 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6867 type_t *argument_type2)
6869 function_parameter_t *parameter2
6870 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6871 memset(parameter2, 0, sizeof(parameter2[0]));
6872 parameter2->type = argument_type2;
6874 function_parameter_t *parameter1
6875 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6876 memset(parameter1, 0, sizeof(parameter1[0]));
6877 parameter1->type = argument_type1;
6878 parameter1->next = parameter2;
6880 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6881 type->function.return_type = return_type;
6882 type->function.parameters = parameter1;
6884 return identify_new_type(type);
6888 * Creates a return_type (func)(argument_type) function type if not
6891 * @param return_type the return type
6892 * @param argument_type the argument type
6894 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6896 function_parameter_t *parameter
6897 = obstack_alloc(type_obst, sizeof(parameter[0]));
6898 memset(parameter, 0, sizeof(parameter[0]));
6899 parameter->type = argument_type;
6901 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6902 type->function.return_type = return_type;
6903 type->function.parameters = parameter;
6905 return identify_new_type(type);
6908 static type_t *make_function_0_type(type_t *return_type)
6910 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6911 type->function.return_type = return_type;
6912 type->function.parameters = NULL;
6914 return identify_new_type(type);
6918 * Creates a function type for some function like builtins.
6920 * @param symbol the symbol describing the builtin
6922 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6924 switch (symbol->ID) {
6925 case T___builtin_alloca:
6926 return make_function_1_type(type_void_ptr, type_size_t);
6927 case T___builtin_huge_val:
6928 return make_function_0_type(type_double);
6929 case T___builtin_inf:
6930 return make_function_0_type(type_double);
6931 case T___builtin_inff:
6932 return make_function_0_type(type_float);
6933 case T___builtin_infl:
6934 return make_function_0_type(type_long_double);
6935 case T___builtin_nan:
6936 return make_function_1_type(type_double, type_char_ptr);
6937 case T___builtin_nanf:
6938 return make_function_1_type(type_float, type_char_ptr);
6939 case T___builtin_nanl:
6940 return make_function_1_type(type_long_double, type_char_ptr);
6941 case T___builtin_va_end:
6942 return make_function_1_type(type_void, type_valist);
6943 case T___builtin_expect:
6944 return make_function_2_type(type_long, type_long, type_long);
6945 case T___builtin_return_address:
6946 case T___builtin_frame_address:
6947 return make_function_1_type(type_void_ptr, type_unsigned_int);
6949 internal_errorf(HERE, "not implemented builtin identifier found");
6954 * Performs automatic type cast as described in § 6.3.2.1.
6956 * @param orig_type the original type
6958 static type_t *automatic_type_conversion(type_t *orig_type)
6960 type_t *type = skip_typeref(orig_type);
6961 if (is_type_array(type)) {
6962 array_type_t *array_type = &type->array;
6963 type_t *element_type = array_type->element_type;
6964 unsigned qualifiers = array_type->base.qualifiers;
6966 return make_pointer_type(element_type, qualifiers);
6969 if (is_type_function(type)) {
6970 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6977 * reverts the automatic casts of array to pointer types and function
6978 * to function-pointer types as defined § 6.3.2.1
6980 type_t *revert_automatic_type_conversion(const expression_t *expression)
6982 switch (expression->kind) {
6983 case EXPR_REFERENCE: {
6984 entity_t *entity = expression->reference.entity;
6985 if (is_declaration(entity)) {
6986 return entity->declaration.type;
6987 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6988 return entity->enum_value.enum_type;
6990 panic("no declaration or enum in reference");
6995 entity_t *entity = expression->select.compound_entry;
6996 assert(is_declaration(entity));
6997 type_t *type = entity->declaration.type;
6998 return get_qualified_type(type,
6999 expression->base.type->base.qualifiers);
7002 case EXPR_UNARY_DEREFERENCE: {
7003 const expression_t *const value = expression->unary.value;
7004 type_t *const type = skip_typeref(value->base.type);
7005 if (!is_type_pointer(type))
7006 return type_error_type;
7007 return type->pointer.points_to;
7010 case EXPR_BUILTIN_SYMBOL:
7011 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
7013 case EXPR_ARRAY_ACCESS: {
7014 const expression_t *array_ref = expression->array_access.array_ref;
7015 type_t *type_left = skip_typeref(array_ref->base.type);
7016 if (!is_type_pointer(type_left))
7017 return type_error_type;
7018 return type_left->pointer.points_to;
7021 case EXPR_STRING_LITERAL: {
7022 size_t size = expression->string.value.size;
7023 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7026 case EXPR_WIDE_STRING_LITERAL: {
7027 size_t size = expression->wide_string.value.size;
7028 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7031 case EXPR_COMPOUND_LITERAL:
7032 return expression->compound_literal.type;
7035 return expression->base.type;
7039 static expression_t *parse_reference(void)
7041 symbol_t *const symbol = token.v.symbol;
7043 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7045 if (entity == NULL) {
7046 if (!strict_mode && look_ahead(1)->type == '(') {
7047 /* an implicitly declared function */
7048 if (warning.error_implicit_function_declaration) {
7049 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7050 } else if (warning.implicit_function_declaration) {
7051 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7054 entity = create_implicit_function(symbol, HERE);
7056 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7057 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7063 if (is_declaration(entity)) {
7064 orig_type = entity->declaration.type;
7065 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7066 orig_type = entity->enum_value.enum_type;
7067 } else if (entity->kind == ENTITY_TYPEDEF) {
7068 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7071 return create_invalid_expression();
7073 panic("expected declaration or enum value in reference");
7076 /* we always do the auto-type conversions; the & and sizeof parser contains
7077 * code to revert this! */
7078 type_t *type = automatic_type_conversion(orig_type);
7080 expression_kind_t kind = EXPR_REFERENCE;
7081 if (entity->kind == ENTITY_ENUM_VALUE)
7082 kind = EXPR_REFERENCE_ENUM_VALUE;
7084 expression_t *expression = allocate_expression_zero(kind);
7085 expression->reference.entity = entity;
7086 expression->base.type = type;
7088 /* this declaration is used */
7089 if (is_declaration(entity)) {
7090 entity->declaration.used = true;
7093 if (entity->base.parent_scope != file_scope
7094 && entity->base.parent_scope->depth < current_function->parameters.depth
7095 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7096 if (entity->kind == ENTITY_VARIABLE) {
7097 /* access of a variable from an outer function */
7098 entity->variable.address_taken = true;
7099 } else if (entity->kind == ENTITY_PARAMETER) {
7100 entity->parameter.address_taken = true;
7102 current_function->need_closure = true;
7105 /* check for deprecated functions */
7106 if (warning.deprecated_declarations
7107 && is_declaration(entity)
7108 && entity->declaration.modifiers & DM_DEPRECATED) {
7109 declaration_t *declaration = &entity->declaration;
7111 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7112 "function" : "variable";
7114 if (declaration->deprecated_string != NULL) {
7115 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7116 prefix, entity->base.symbol, &entity->base.source_position,
7117 declaration->deprecated_string);
7119 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7120 entity->base.symbol, &entity->base.source_position);
7124 if (warning.init_self && entity == current_init_decl && !in_type_prop
7125 && entity->kind == ENTITY_VARIABLE) {
7126 current_init_decl = NULL;
7127 warningf(HERE, "variable '%#T' is initialized by itself",
7128 entity->declaration.type, entity->base.symbol);
7135 static bool semantic_cast(expression_t *cast)
7137 expression_t *expression = cast->unary.value;
7138 type_t *orig_dest_type = cast->base.type;
7139 type_t *orig_type_right = expression->base.type;
7140 type_t const *dst_type = skip_typeref(orig_dest_type);
7141 type_t const *src_type = skip_typeref(orig_type_right);
7142 source_position_t const *pos = &cast->base.source_position;
7144 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7145 if (dst_type == type_void)
7148 /* only integer and pointer can be casted to pointer */
7149 if (is_type_pointer(dst_type) &&
7150 !is_type_pointer(src_type) &&
7151 !is_type_integer(src_type) &&
7152 is_type_valid(src_type)) {
7153 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7157 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7158 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7162 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7163 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7167 if (warning.cast_qual &&
7168 is_type_pointer(src_type) &&
7169 is_type_pointer(dst_type)) {
7170 type_t *src = skip_typeref(src_type->pointer.points_to);
7171 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7172 unsigned missing_qualifiers =
7173 src->base.qualifiers & ~dst->base.qualifiers;
7174 if (missing_qualifiers != 0) {
7176 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7177 missing_qualifiers, orig_type_right);
7183 static expression_t *parse_compound_literal(type_t *type)
7185 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7187 parse_initializer_env_t env;
7190 env.must_be_constant = false;
7191 initializer_t *initializer = parse_initializer(&env);
7194 expression->compound_literal.initializer = initializer;
7195 expression->compound_literal.type = type;
7196 expression->base.type = automatic_type_conversion(type);
7202 * Parse a cast expression.
7204 static expression_t *parse_cast(void)
7206 add_anchor_token(')');
7208 source_position_t source_position = token.source_position;
7210 type_t *type = parse_typename();
7212 rem_anchor_token(')');
7213 expect(')', end_error);
7215 if (token.type == '{') {
7216 return parse_compound_literal(type);
7219 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7220 cast->base.source_position = source_position;
7222 expression_t *value = parse_sub_expression(PREC_CAST);
7223 cast->base.type = type;
7224 cast->unary.value = value;
7226 if (! semantic_cast(cast)) {
7227 /* TODO: record the error in the AST. else it is impossible to detect it */
7232 return create_invalid_expression();
7236 * Parse a statement expression.
7238 static expression_t *parse_statement_expression(void)
7240 add_anchor_token(')');
7242 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7244 statement_t *statement = parse_compound_statement(true);
7245 statement->compound.stmt_expr = true;
7246 expression->statement.statement = statement;
7248 /* find last statement and use its type */
7249 type_t *type = type_void;
7250 const statement_t *stmt = statement->compound.statements;
7252 while (stmt->base.next != NULL)
7253 stmt = stmt->base.next;
7255 if (stmt->kind == STATEMENT_EXPRESSION) {
7256 type = stmt->expression.expression->base.type;
7258 } else if (warning.other) {
7259 warningf(&expression->base.source_position, "empty statement expression ({})");
7261 expression->base.type = type;
7263 rem_anchor_token(')');
7264 expect(')', end_error);
7271 * Parse a parenthesized expression.
7273 static expression_t *parse_parenthesized_expression(void)
7277 switch (token.type) {
7279 /* gcc extension: a statement expression */
7280 return parse_statement_expression();
7284 return parse_cast();
7286 if (is_typedef_symbol(token.v.symbol)) {
7287 return parse_cast();
7291 add_anchor_token(')');
7292 expression_t *result = parse_expression();
7293 result->base.parenthesized = true;
7294 rem_anchor_token(')');
7295 expect(')', end_error);
7301 static expression_t *parse_function_keyword(void)
7305 if (current_function == NULL) {
7306 errorf(HERE, "'__func__' used outside of a function");
7309 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7310 expression->base.type = type_char_ptr;
7311 expression->funcname.kind = FUNCNAME_FUNCTION;
7318 static expression_t *parse_pretty_function_keyword(void)
7320 if (current_function == NULL) {
7321 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7324 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7325 expression->base.type = type_char_ptr;
7326 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7328 eat(T___PRETTY_FUNCTION__);
7333 static expression_t *parse_funcsig_keyword(void)
7335 if (current_function == NULL) {
7336 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7339 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7340 expression->base.type = type_char_ptr;
7341 expression->funcname.kind = FUNCNAME_FUNCSIG;
7348 static expression_t *parse_funcdname_keyword(void)
7350 if (current_function == NULL) {
7351 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7354 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7355 expression->base.type = type_char_ptr;
7356 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7358 eat(T___FUNCDNAME__);
7363 static designator_t *parse_designator(void)
7365 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7366 result->source_position = *HERE;
7368 if (token.type != T_IDENTIFIER) {
7369 parse_error_expected("while parsing member designator",
7370 T_IDENTIFIER, NULL);
7373 result->symbol = token.v.symbol;
7376 designator_t *last_designator = result;
7378 if (token.type == '.') {
7380 if (token.type != T_IDENTIFIER) {
7381 parse_error_expected("while parsing member designator",
7382 T_IDENTIFIER, NULL);
7385 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7386 designator->source_position = *HERE;
7387 designator->symbol = token.v.symbol;
7390 last_designator->next = designator;
7391 last_designator = designator;
7394 if (token.type == '[') {
7396 add_anchor_token(']');
7397 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7398 designator->source_position = *HERE;
7399 designator->array_index = parse_expression();
7400 rem_anchor_token(']');
7401 expect(']', end_error);
7402 if (designator->array_index == NULL) {
7406 last_designator->next = designator;
7407 last_designator = designator;
7419 * Parse the __builtin_offsetof() expression.
7421 static expression_t *parse_offsetof(void)
7423 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7424 expression->base.type = type_size_t;
7426 eat(T___builtin_offsetof);
7428 expect('(', end_error);
7429 add_anchor_token(',');
7430 type_t *type = parse_typename();
7431 rem_anchor_token(',');
7432 expect(',', end_error);
7433 add_anchor_token(')');
7434 designator_t *designator = parse_designator();
7435 rem_anchor_token(')');
7436 expect(')', end_error);
7438 expression->offsetofe.type = type;
7439 expression->offsetofe.designator = designator;
7442 memset(&path, 0, sizeof(path));
7443 path.top_type = type;
7444 path.path = NEW_ARR_F(type_path_entry_t, 0);
7446 descend_into_subtype(&path);
7448 if (!walk_designator(&path, designator, true)) {
7449 return create_invalid_expression();
7452 DEL_ARR_F(path.path);
7456 return create_invalid_expression();
7460 * Parses a _builtin_va_start() expression.
7462 static expression_t *parse_va_start(void)
7464 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7466 eat(T___builtin_va_start);
7468 expect('(', end_error);
7469 add_anchor_token(',');
7470 expression->va_starte.ap = parse_assignment_expression();
7471 rem_anchor_token(',');
7472 expect(',', end_error);
7473 expression_t *const expr = parse_assignment_expression();
7474 if (expr->kind == EXPR_REFERENCE) {
7475 entity_t *const entity = expr->reference.entity;
7476 if (entity->base.parent_scope != ¤t_function->parameters
7477 || entity->base.next != NULL
7478 || entity->kind != ENTITY_PARAMETER) {
7479 errorf(&expr->base.source_position,
7480 "second argument of 'va_start' must be last parameter of the current function");
7482 expression->va_starte.parameter = &entity->variable;
7484 expect(')', end_error);
7487 expect(')', end_error);
7489 return create_invalid_expression();
7493 * Parses a _builtin_va_arg() expression.
7495 static expression_t *parse_va_arg(void)
7497 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7499 eat(T___builtin_va_arg);
7501 expect('(', end_error);
7502 expression->va_arge.ap = parse_assignment_expression();
7503 expect(',', end_error);
7504 expression->base.type = parse_typename();
7505 expect(')', end_error);
7509 return create_invalid_expression();
7512 static expression_t *parse_builtin_symbol(void)
7514 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7516 symbol_t *symbol = token.v.symbol;
7518 expression->builtin_symbol.symbol = symbol;
7521 type_t *type = get_builtin_symbol_type(symbol);
7522 type = automatic_type_conversion(type);
7524 expression->base.type = type;
7529 * Parses a __builtin_constant() expression.
7531 static expression_t *parse_builtin_constant(void)
7533 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7535 eat(T___builtin_constant_p);
7537 expect('(', end_error);
7538 add_anchor_token(')');
7539 expression->builtin_constant.value = parse_assignment_expression();
7540 rem_anchor_token(')');
7541 expect(')', end_error);
7542 expression->base.type = type_int;
7546 return create_invalid_expression();
7550 * Parses a __builtin_prefetch() expression.
7552 static expression_t *parse_builtin_prefetch(void)
7554 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7556 eat(T___builtin_prefetch);
7558 expect('(', end_error);
7559 add_anchor_token(')');
7560 expression->builtin_prefetch.adr = parse_assignment_expression();
7561 if (token.type == ',') {
7563 expression->builtin_prefetch.rw = parse_assignment_expression();
7565 if (token.type == ',') {
7567 expression->builtin_prefetch.locality = parse_assignment_expression();
7569 rem_anchor_token(')');
7570 expect(')', end_error);
7571 expression->base.type = type_void;
7575 return create_invalid_expression();
7579 * Parses a __buildin_return_address of a __builtin_frame_address() expression.
7581 * @param tok_type either T___buildin_return_address or T___builtin_frame_address
7583 static expression_t *parse_builtin_address(int tok_type)
7585 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_ADDRESS);
7587 expression->builtin_address.kind = tok_type == T___builtin_return_address ?
7588 builtin_return_address : builtin_frame_address;
7592 expect('(', end_error);
7593 add_anchor_token(')');
7594 expression->builtin_address.value = parse_constant_expression();
7595 rem_anchor_token(')');
7596 expect(')', end_error);
7597 expression->base.type = type_void_ptr;
7601 return create_invalid_expression();
7605 * Parses a __builtin_is_*() compare expression.
7607 static expression_t *parse_compare_builtin(void)
7609 expression_t *expression;
7611 switch (token.type) {
7612 case T___builtin_isgreater:
7613 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7615 case T___builtin_isgreaterequal:
7616 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7618 case T___builtin_isless:
7619 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7621 case T___builtin_islessequal:
7622 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7624 case T___builtin_islessgreater:
7625 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7627 case T___builtin_isunordered:
7628 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7631 internal_errorf(HERE, "invalid compare builtin found");
7633 expression->base.source_position = *HERE;
7636 expect('(', end_error);
7637 expression->binary.left = parse_assignment_expression();
7638 expect(',', end_error);
7639 expression->binary.right = parse_assignment_expression();
7640 expect(')', end_error);
7642 type_t *const orig_type_left = expression->binary.left->base.type;
7643 type_t *const orig_type_right = expression->binary.right->base.type;
7645 type_t *const type_left = skip_typeref(orig_type_left);
7646 type_t *const type_right = skip_typeref(orig_type_right);
7647 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7648 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7649 type_error_incompatible("invalid operands in comparison",
7650 &expression->base.source_position, orig_type_left, orig_type_right);
7653 semantic_comparison(&expression->binary);
7658 return create_invalid_expression();
7663 * Parses a __builtin_expect(, end_error) expression.
7665 static expression_t *parse_builtin_expect(void, end_error)
7667 expression_t *expression
7668 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7670 eat(T___builtin_expect);
7672 expect('(', end_error);
7673 expression->binary.left = parse_assignment_expression();
7674 expect(',', end_error);
7675 expression->binary.right = parse_constant_expression();
7676 expect(')', end_error);
7678 expression->base.type = expression->binary.left->base.type;
7682 return create_invalid_expression();
7687 * Parses a MS assume() expression.
7689 static expression_t *parse_assume(void)
7691 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7695 expect('(', end_error);
7696 add_anchor_token(')');
7697 expression->unary.value = parse_assignment_expression();
7698 rem_anchor_token(')');
7699 expect(')', end_error);
7701 expression->base.type = type_void;
7704 return create_invalid_expression();
7708 * Return the declaration for a given label symbol or create a new one.
7710 * @param symbol the symbol of the label
7712 static label_t *get_label(symbol_t *symbol)
7715 assert(current_function != NULL);
7717 label = get_entity(symbol, NAMESPACE_LABEL);
7718 /* if we found a local label, we already created the declaration */
7719 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7720 if (label->base.parent_scope != current_scope) {
7721 assert(label->base.parent_scope->depth < current_scope->depth);
7722 current_function->goto_to_outer = true;
7724 return &label->label;
7727 label = get_entity(symbol, NAMESPACE_LABEL);
7728 /* if we found a label in the same function, then we already created the
7731 && label->base.parent_scope == ¤t_function->parameters) {
7732 return &label->label;
7735 /* otherwise we need to create a new one */
7736 label = allocate_entity_zero(ENTITY_LABEL);
7737 label->base.namespc = NAMESPACE_LABEL;
7738 label->base.symbol = symbol;
7742 return &label->label;
7746 * Parses a GNU && label address expression.
7748 static expression_t *parse_label_address(void)
7750 source_position_t source_position = token.source_position;
7752 if (token.type != T_IDENTIFIER) {
7753 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7756 symbol_t *symbol = token.v.symbol;
7759 label_t *label = get_label(symbol);
7761 label->address_taken = true;
7763 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7764 expression->base.source_position = source_position;
7766 /* label address is threaten as a void pointer */
7767 expression->base.type = type_void_ptr;
7768 expression->label_address.label = label;
7771 return create_invalid_expression();
7775 * Parse a microsoft __noop expression.
7777 static expression_t *parse_noop_expression(void)
7779 /* the result is a (int)0 */
7780 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7781 cnst->base.type = type_int;
7782 cnst->conste.v.int_value = 0;
7783 cnst->conste.is_ms_noop = true;
7787 if (token.type == '(') {
7788 /* parse arguments */
7790 add_anchor_token(')');
7791 add_anchor_token(',');
7793 if (token.type != ')') {
7795 (void)parse_assignment_expression();
7796 if (token.type != ',')
7802 rem_anchor_token(',');
7803 rem_anchor_token(')');
7804 expect(')', end_error);
7811 * Parses a primary expression.
7813 static expression_t *parse_primary_expression(void)
7815 switch (token.type) {
7816 case T_false: return parse_bool_const(false);
7817 case T_true: return parse_bool_const(true);
7818 case T_INTEGER: return parse_int_const();
7819 case T_CHARACTER_CONSTANT: return parse_character_constant();
7820 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7821 case T_FLOATINGPOINT: return parse_float_const();
7822 case T_STRING_LITERAL:
7823 case T_WIDE_STRING_LITERAL: return parse_string_const();
7824 case T_IDENTIFIER: return parse_reference();
7825 case T___FUNCTION__:
7826 case T___func__: return parse_function_keyword();
7827 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7828 case T___FUNCSIG__: return parse_funcsig_keyword();
7829 case T___FUNCDNAME__: return parse_funcdname_keyword();
7830 case T___builtin_offsetof: return parse_offsetof();
7831 case T___builtin_va_start: return parse_va_start();
7832 case T___builtin_va_arg: return parse_va_arg();
7833 case T___builtin_expect:
7834 case T___builtin_alloca:
7835 case T___builtin_inf:
7836 case T___builtin_inff:
7837 case T___builtin_infl:
7838 case T___builtin_nan:
7839 case T___builtin_nanf:
7840 case T___builtin_nanl:
7841 case T___builtin_huge_val:
7842 case T___builtin_va_end: return parse_builtin_symbol();
7843 case T___builtin_isgreater:
7844 case T___builtin_isgreaterequal:
7845 case T___builtin_isless:
7846 case T___builtin_islessequal:
7847 case T___builtin_islessgreater:
7848 case T___builtin_isunordered: return parse_compare_builtin();
7849 case T___builtin_constant_p: return parse_builtin_constant();
7850 case T___builtin_prefetch: return parse_builtin_prefetch();
7851 case T___builtin_return_address: return parse_builtin_address(T___builtin_return_address);
7852 case T___builtin_frame_address: return parse_builtin_address(T___builtin_frame_address);
7853 case T__assume: return parse_assume();
7856 return parse_label_address();
7859 case '(': return parse_parenthesized_expression();
7860 case T___noop: return parse_noop_expression();
7863 errorf(HERE, "unexpected token %K, expected an expression", &token);
7864 return create_invalid_expression();
7868 * Check if the expression has the character type and issue a warning then.
7870 static void check_for_char_index_type(const expression_t *expression)
7872 type_t *const type = expression->base.type;
7873 const type_t *const base_type = skip_typeref(type);
7875 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7876 warning.char_subscripts) {
7877 warningf(&expression->base.source_position,
7878 "array subscript has type '%T'", type);
7882 static expression_t *parse_array_expression(expression_t *left)
7884 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7887 add_anchor_token(']');
7889 expression_t *inside = parse_expression();
7891 type_t *const orig_type_left = left->base.type;
7892 type_t *const orig_type_inside = inside->base.type;
7894 type_t *const type_left = skip_typeref(orig_type_left);
7895 type_t *const type_inside = skip_typeref(orig_type_inside);
7897 type_t *return_type;
7898 array_access_expression_t *array_access = &expression->array_access;
7899 if (is_type_pointer(type_left)) {
7900 return_type = type_left->pointer.points_to;
7901 array_access->array_ref = left;
7902 array_access->index = inside;
7903 check_for_char_index_type(inside);
7904 } else if (is_type_pointer(type_inside)) {
7905 return_type = type_inside->pointer.points_to;
7906 array_access->array_ref = inside;
7907 array_access->index = left;
7908 array_access->flipped = true;
7909 check_for_char_index_type(left);
7911 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7913 "array access on object with non-pointer types '%T', '%T'",
7914 orig_type_left, orig_type_inside);
7916 return_type = type_error_type;
7917 array_access->array_ref = left;
7918 array_access->index = inside;
7921 expression->base.type = automatic_type_conversion(return_type);
7923 rem_anchor_token(']');
7924 expect(']', end_error);
7929 static expression_t *parse_typeprop(expression_kind_t const kind)
7931 expression_t *tp_expression = allocate_expression_zero(kind);
7932 tp_expression->base.type = type_size_t;
7934 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7936 /* we only refer to a type property, mark this case */
7937 bool old = in_type_prop;
7938 in_type_prop = true;
7941 expression_t *expression;
7942 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7944 add_anchor_token(')');
7945 orig_type = parse_typename();
7946 rem_anchor_token(')');
7947 expect(')', end_error);
7949 if (token.type == '{') {
7950 /* It was not sizeof(type) after all. It is sizeof of an expression
7951 * starting with a compound literal */
7952 expression = parse_compound_literal(orig_type);
7953 goto typeprop_expression;
7956 expression = parse_sub_expression(PREC_UNARY);
7958 typeprop_expression:
7959 tp_expression->typeprop.tp_expression = expression;
7961 orig_type = revert_automatic_type_conversion(expression);
7962 expression->base.type = orig_type;
7965 tp_expression->typeprop.type = orig_type;
7966 type_t const* const type = skip_typeref(orig_type);
7967 char const* const wrong_type =
7968 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7969 is_type_incomplete(type) ? "incomplete" :
7970 type->kind == TYPE_FUNCTION ? "function designator" :
7971 type->kind == TYPE_BITFIELD ? "bitfield" :
7973 if (wrong_type != NULL) {
7974 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7975 errorf(&tp_expression->base.source_position,
7976 "operand of %s expression must not be of %s type '%T'",
7977 what, wrong_type, orig_type);
7982 return tp_expression;
7985 static expression_t *parse_sizeof(void)
7987 return parse_typeprop(EXPR_SIZEOF);
7990 static expression_t *parse_alignof(void)
7992 return parse_typeprop(EXPR_ALIGNOF);
7995 static expression_t *parse_select_expression(expression_t *compound)
7997 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7998 select->select.compound = compound;
8000 assert(token.type == '.' || token.type == T_MINUSGREATER);
8001 bool is_pointer = (token.type == T_MINUSGREATER);
8004 if (token.type != T_IDENTIFIER) {
8005 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
8008 symbol_t *symbol = token.v.symbol;
8011 type_t *const orig_type = compound->base.type;
8012 type_t *const type = skip_typeref(orig_type);
8015 bool saw_error = false;
8016 if (is_type_pointer(type)) {
8019 "request for member '%Y' in something not a struct or union, but '%T'",
8023 type_left = skip_typeref(type->pointer.points_to);
8025 if (is_pointer && is_type_valid(type)) {
8026 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
8033 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
8034 type_left->kind == TYPE_COMPOUND_UNION) {
8035 compound_t *compound = type_left->compound.compound;
8037 if (!compound->complete) {
8038 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
8040 goto create_error_entry;
8043 entry = find_compound_entry(compound, symbol);
8044 if (entry == NULL) {
8045 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
8046 goto create_error_entry;
8049 if (is_type_valid(type_left) && !saw_error) {
8051 "request for member '%Y' in something not a struct or union, but '%T'",
8055 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8058 assert(is_declaration(entry));
8059 select->select.compound_entry = entry;
8061 type_t *entry_type = entry->declaration.type;
8063 = get_qualified_type(entry_type, type_left->base.qualifiers);
8065 /* we always do the auto-type conversions; the & and sizeof parser contains
8066 * code to revert this! */
8067 select->base.type = automatic_type_conversion(res_type);
8069 type_t *skipped = skip_typeref(res_type);
8070 if (skipped->kind == TYPE_BITFIELD) {
8071 select->base.type = skipped->bitfield.base_type;
8077 static void check_call_argument(const function_parameter_t *parameter,
8078 call_argument_t *argument, unsigned pos)
8080 type_t *expected_type = parameter->type;
8081 type_t *expected_type_skip = skip_typeref(expected_type);
8082 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8083 expression_t *arg_expr = argument->expression;
8084 type_t *arg_type = skip_typeref(arg_expr->base.type);
8086 /* handle transparent union gnu extension */
8087 if (is_type_union(expected_type_skip)
8088 && (expected_type_skip->base.modifiers
8089 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8090 compound_t *union_decl = expected_type_skip->compound.compound;
8091 type_t *best_type = NULL;
8092 entity_t *entry = union_decl->members.entities;
8093 for ( ; entry != NULL; entry = entry->base.next) {
8094 assert(is_declaration(entry));
8095 type_t *decl_type = entry->declaration.type;
8096 error = semantic_assign(decl_type, arg_expr);
8097 if (error == ASSIGN_ERROR_INCOMPATIBLE
8098 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8101 if (error == ASSIGN_SUCCESS) {
8102 best_type = decl_type;
8103 } else if (best_type == NULL) {
8104 best_type = decl_type;
8108 if (best_type != NULL) {
8109 expected_type = best_type;
8113 error = semantic_assign(expected_type, arg_expr);
8114 argument->expression = create_implicit_cast(argument->expression,
8117 if (error != ASSIGN_SUCCESS) {
8118 /* report exact scope in error messages (like "in argument 3") */
8120 snprintf(buf, sizeof(buf), "call argument %u", pos);
8121 report_assign_error(error, expected_type, arg_expr, buf,
8122 &arg_expr->base.source_position);
8123 } else if (warning.traditional || warning.conversion) {
8124 type_t *const promoted_type = get_default_promoted_type(arg_type);
8125 if (!types_compatible(expected_type_skip, promoted_type) &&
8126 !types_compatible(expected_type_skip, type_void_ptr) &&
8127 !types_compatible(type_void_ptr, promoted_type)) {
8128 /* Deliberately show the skipped types in this warning */
8129 warningf(&arg_expr->base.source_position,
8130 "passing call argument %u as '%T' rather than '%T' due to prototype",
8131 pos, expected_type_skip, promoted_type);
8137 * Parse a call expression, ie. expression '( ... )'.
8139 * @param expression the function address
8141 static expression_t *parse_call_expression(expression_t *expression)
8143 expression_t *result = allocate_expression_zero(EXPR_CALL);
8144 call_expression_t *call = &result->call;
8145 call->function = expression;
8147 type_t *const orig_type = expression->base.type;
8148 type_t *const type = skip_typeref(orig_type);
8150 function_type_t *function_type = NULL;
8151 if (is_type_pointer(type)) {
8152 type_t *const to_type = skip_typeref(type->pointer.points_to);
8154 if (is_type_function(to_type)) {
8155 function_type = &to_type->function;
8156 call->base.type = function_type->return_type;
8160 if (function_type == NULL && is_type_valid(type)) {
8161 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8164 /* parse arguments */
8166 add_anchor_token(')');
8167 add_anchor_token(',');
8169 if (token.type != ')') {
8170 call_argument_t *last_argument = NULL;
8173 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8175 argument->expression = parse_assignment_expression();
8176 if (last_argument == NULL) {
8177 call->arguments = argument;
8179 last_argument->next = argument;
8181 last_argument = argument;
8183 if (token.type != ',')
8188 rem_anchor_token(',');
8189 rem_anchor_token(')');
8190 expect(')', end_error);
8192 if (function_type == NULL)
8195 function_parameter_t *parameter = function_type->parameters;
8196 call_argument_t *argument = call->arguments;
8197 if (!function_type->unspecified_parameters) {
8198 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8199 parameter = parameter->next, argument = argument->next) {
8200 check_call_argument(parameter, argument, ++pos);
8203 if (parameter != NULL) {
8204 errorf(HERE, "too few arguments to function '%E'", expression);
8205 } else if (argument != NULL && !function_type->variadic) {
8206 errorf(HERE, "too many arguments to function '%E'", expression);
8210 /* do default promotion */
8211 for (; argument != NULL; argument = argument->next) {
8212 type_t *type = argument->expression->base.type;
8214 type = get_default_promoted_type(type);
8216 argument->expression
8217 = create_implicit_cast(argument->expression, type);
8220 check_format(&result->call);
8222 if (warning.aggregate_return &&
8223 is_type_compound(skip_typeref(function_type->return_type))) {
8224 warningf(&result->base.source_position,
8225 "function call has aggregate value");
8232 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8234 static bool same_compound_type(const type_t *type1, const type_t *type2)
8237 is_type_compound(type1) &&
8238 type1->kind == type2->kind &&
8239 type1->compound.compound == type2->compound.compound;
8242 static expression_t const *get_reference_address(expression_t const *expr)
8244 bool regular_take_address = true;
8246 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8247 expr = expr->unary.value;
8249 regular_take_address = false;
8252 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8255 expr = expr->unary.value;
8258 if (expr->kind != EXPR_REFERENCE)
8261 /* special case for functions which are automatically converted to a
8262 * pointer to function without an extra TAKE_ADDRESS operation */
8263 if (!regular_take_address &&
8264 expr->reference.entity->kind != ENTITY_FUNCTION) {
8271 static void warn_reference_address_as_bool(expression_t const* expr)
8273 if (!warning.address)
8276 expr = get_reference_address(expr);
8278 warningf(&expr->base.source_position,
8279 "the address of '%Y' will always evaluate as 'true'",
8280 expr->reference.entity->base.symbol);
8284 static void warn_assignment_in_condition(const expression_t *const expr)
8286 if (!warning.parentheses)
8288 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8290 if (expr->base.parenthesized)
8292 warningf(&expr->base.source_position,
8293 "suggest parentheses around assignment used as truth value");
8296 static void semantic_condition(expression_t const *const expr,
8297 char const *const context)
8299 type_t *const type = skip_typeref(expr->base.type);
8300 if (is_type_scalar(type)) {
8301 warn_reference_address_as_bool(expr);
8302 warn_assignment_in_condition(expr);
8303 } else if (is_type_valid(type)) {
8304 errorf(&expr->base.source_position,
8305 "%s must have scalar type", context);
8310 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8312 * @param expression the conditional expression
8314 static expression_t *parse_conditional_expression(expression_t *expression)
8316 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8318 conditional_expression_t *conditional = &result->conditional;
8319 conditional->condition = expression;
8322 add_anchor_token(':');
8324 /* §6.5.15:2 The first operand shall have scalar type. */
8325 semantic_condition(expression, "condition of conditional operator");
8327 expression_t *true_expression = expression;
8328 bool gnu_cond = false;
8329 if (GNU_MODE && token.type == ':') {
8332 true_expression = parse_expression();
8334 rem_anchor_token(':');
8335 expect(':', end_error);
8337 expression_t *false_expression =
8338 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8340 type_t *const orig_true_type = true_expression->base.type;
8341 type_t *const orig_false_type = false_expression->base.type;
8342 type_t *const true_type = skip_typeref(orig_true_type);
8343 type_t *const false_type = skip_typeref(orig_false_type);
8346 type_t *result_type;
8347 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8348 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8349 /* ISO/IEC 14882:1998(E) §5.16:2 */
8350 if (true_expression->kind == EXPR_UNARY_THROW) {
8351 result_type = false_type;
8352 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8353 result_type = true_type;
8355 if (warning.other && (
8356 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8357 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8359 warningf(&conditional->base.source_position,
8360 "ISO C forbids conditional expression with only one void side");
8362 result_type = type_void;
8364 } else if (is_type_arithmetic(true_type)
8365 && is_type_arithmetic(false_type)) {
8366 result_type = semantic_arithmetic(true_type, false_type);
8368 true_expression = create_implicit_cast(true_expression, result_type);
8369 false_expression = create_implicit_cast(false_expression, result_type);
8371 conditional->true_expression = true_expression;
8372 conditional->false_expression = false_expression;
8373 conditional->base.type = result_type;
8374 } else if (same_compound_type(true_type, false_type)) {
8375 /* just take 1 of the 2 types */
8376 result_type = true_type;
8377 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8378 type_t *pointer_type;
8380 expression_t *other_expression;
8381 if (is_type_pointer(true_type) &&
8382 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8383 pointer_type = true_type;
8384 other_type = false_type;
8385 other_expression = false_expression;
8387 pointer_type = false_type;
8388 other_type = true_type;
8389 other_expression = true_expression;
8392 if (is_null_pointer_constant(other_expression)) {
8393 result_type = pointer_type;
8394 } else if (is_type_pointer(other_type)) {
8395 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8396 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8399 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8400 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8402 } else if (types_compatible(get_unqualified_type(to1),
8403 get_unqualified_type(to2))) {
8406 if (warning.other) {
8407 warningf(&conditional->base.source_position,
8408 "pointer types '%T' and '%T' in conditional expression are incompatible",
8409 true_type, false_type);
8414 type_t *const type =
8415 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8416 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8417 } else if (is_type_integer(other_type)) {
8418 if (warning.other) {
8419 warningf(&conditional->base.source_position,
8420 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8422 result_type = pointer_type;
8424 if (is_type_valid(other_type)) {
8425 type_error_incompatible("while parsing conditional",
8426 &expression->base.source_position, true_type, false_type);
8428 result_type = type_error_type;
8431 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8432 type_error_incompatible("while parsing conditional",
8433 &conditional->base.source_position, true_type,
8436 result_type = type_error_type;
8439 conditional->true_expression
8440 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8441 conditional->false_expression
8442 = create_implicit_cast(false_expression, result_type);
8443 conditional->base.type = result_type;
8448 * Parse an extension expression.
8450 static expression_t *parse_extension(void)
8452 eat(T___extension__);
8454 bool old_gcc_extension = in_gcc_extension;
8455 in_gcc_extension = true;
8456 expression_t *expression = parse_sub_expression(PREC_UNARY);
8457 in_gcc_extension = old_gcc_extension;
8462 * Parse a __builtin_classify_type() expression.
8464 static expression_t *parse_builtin_classify_type(void)
8466 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8467 result->base.type = type_int;
8469 eat(T___builtin_classify_type);
8471 expect('(', end_error);
8472 add_anchor_token(')');
8473 expression_t *expression = parse_expression();
8474 rem_anchor_token(')');
8475 expect(')', end_error);
8476 result->classify_type.type_expression = expression;
8480 return create_invalid_expression();
8484 * Parse a delete expression
8485 * ISO/IEC 14882:1998(E) §5.3.5
8487 static expression_t *parse_delete(void)
8489 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8490 result->base.type = type_void;
8494 if (token.type == '[') {
8496 result->kind = EXPR_UNARY_DELETE_ARRAY;
8497 expect(']', end_error);
8501 expression_t *const value = parse_sub_expression(PREC_CAST);
8502 result->unary.value = value;
8504 type_t *const type = skip_typeref(value->base.type);
8505 if (!is_type_pointer(type)) {
8506 if (is_type_valid(type)) {
8507 errorf(&value->base.source_position,
8508 "operand of delete must have pointer type");
8510 } else if (warning.other &&
8511 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8512 warningf(&value->base.source_position,
8513 "deleting 'void*' is undefined");
8520 * Parse a throw expression
8521 * ISO/IEC 14882:1998(E) §15:1
8523 static expression_t *parse_throw(void)
8525 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8526 result->base.type = type_void;
8530 expression_t *value = NULL;
8531 switch (token.type) {
8533 value = parse_assignment_expression();
8534 /* ISO/IEC 14882:1998(E) §15.1:3 */
8535 type_t *const orig_type = value->base.type;
8536 type_t *const type = skip_typeref(orig_type);
8537 if (is_type_incomplete(type)) {
8538 errorf(&value->base.source_position,
8539 "cannot throw object of incomplete type '%T'", orig_type);
8540 } else if (is_type_pointer(type)) {
8541 type_t *const points_to = skip_typeref(type->pointer.points_to);
8542 if (is_type_incomplete(points_to) &&
8543 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8544 errorf(&value->base.source_position,
8545 "cannot throw pointer to incomplete type '%T'", orig_type);
8553 result->unary.value = value;
8558 static bool check_pointer_arithmetic(const source_position_t *source_position,
8559 type_t *pointer_type,
8560 type_t *orig_pointer_type)
8562 type_t *points_to = pointer_type->pointer.points_to;
8563 points_to = skip_typeref(points_to);
8565 if (is_type_incomplete(points_to)) {
8566 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8567 errorf(source_position,
8568 "arithmetic with pointer to incomplete type '%T' not allowed",
8571 } else if (warning.pointer_arith) {
8572 warningf(source_position,
8573 "pointer of type '%T' used in arithmetic",
8576 } else if (is_type_function(points_to)) {
8578 errorf(source_position,
8579 "arithmetic with pointer to function type '%T' not allowed",
8582 } else if (warning.pointer_arith) {
8583 warningf(source_position,
8584 "pointer to a function '%T' used in arithmetic",
8591 static bool is_lvalue(const expression_t *expression)
8593 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8594 switch (expression->kind) {
8595 case EXPR_ARRAY_ACCESS:
8596 case EXPR_COMPOUND_LITERAL:
8597 case EXPR_REFERENCE:
8599 case EXPR_UNARY_DEREFERENCE:
8603 type_t *type = skip_typeref(expression->base.type);
8605 /* ISO/IEC 14882:1998(E) §3.10:3 */
8606 is_type_reference(type) ||
8607 /* Claim it is an lvalue, if the type is invalid. There was a parse
8608 * error before, which maybe prevented properly recognizing it as
8610 !is_type_valid(type);
8615 static void semantic_incdec(unary_expression_t *expression)
8617 type_t *const orig_type = expression->value->base.type;
8618 type_t *const type = skip_typeref(orig_type);
8619 if (is_type_pointer(type)) {
8620 if (!check_pointer_arithmetic(&expression->base.source_position,
8624 } else if (!is_type_real(type) && is_type_valid(type)) {
8625 /* TODO: improve error message */
8626 errorf(&expression->base.source_position,
8627 "operation needs an arithmetic or pointer type");
8630 if (!is_lvalue(expression->value)) {
8631 /* TODO: improve error message */
8632 errorf(&expression->base.source_position, "lvalue required as operand");
8634 expression->base.type = orig_type;
8637 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8639 type_t *const orig_type = expression->value->base.type;
8640 type_t *const type = skip_typeref(orig_type);
8641 if (!is_type_arithmetic(type)) {
8642 if (is_type_valid(type)) {
8643 /* TODO: improve error message */
8644 errorf(&expression->base.source_position,
8645 "operation needs an arithmetic type");
8650 expression->base.type = orig_type;
8653 static void semantic_unexpr_plus(unary_expression_t *expression)
8655 semantic_unexpr_arithmetic(expression);
8656 if (warning.traditional)
8657 warningf(&expression->base.source_position,
8658 "traditional C rejects the unary plus operator");
8661 static void semantic_not(unary_expression_t *expression)
8663 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8664 semantic_condition(expression->value, "operand of !");
8665 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8668 static void semantic_unexpr_integer(unary_expression_t *expression)
8670 type_t *const orig_type = expression->value->base.type;
8671 type_t *const type = skip_typeref(orig_type);
8672 if (!is_type_integer(type)) {
8673 if (is_type_valid(type)) {
8674 errorf(&expression->base.source_position,
8675 "operand of ~ must be of integer type");
8680 expression->base.type = orig_type;
8683 static void semantic_dereference(unary_expression_t *expression)
8685 type_t *const orig_type = expression->value->base.type;
8686 type_t *const type = skip_typeref(orig_type);
8687 if (!is_type_pointer(type)) {
8688 if (is_type_valid(type)) {
8689 errorf(&expression->base.source_position,
8690 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8695 type_t *result_type = type->pointer.points_to;
8696 result_type = automatic_type_conversion(result_type);
8697 expression->base.type = result_type;
8701 * Record that an address is taken (expression represents an lvalue).
8703 * @param expression the expression
8704 * @param may_be_register if true, the expression might be an register
8706 static void set_address_taken(expression_t *expression, bool may_be_register)
8708 if (expression->kind != EXPR_REFERENCE)
8711 entity_t *const entity = expression->reference.entity;
8713 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8716 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8717 && !may_be_register) {
8718 errorf(&expression->base.source_position,
8719 "address of register %s '%Y' requested",
8720 get_entity_kind_name(entity->kind), entity->base.symbol);
8723 if (entity->kind == ENTITY_VARIABLE) {
8724 entity->variable.address_taken = true;
8726 assert(entity->kind == ENTITY_PARAMETER);
8727 entity->parameter.address_taken = true;
8732 * Check the semantic of the address taken expression.
8734 static void semantic_take_addr(unary_expression_t *expression)
8736 expression_t *value = expression->value;
8737 value->base.type = revert_automatic_type_conversion(value);
8739 type_t *orig_type = value->base.type;
8740 type_t *type = skip_typeref(orig_type);
8741 if (!is_type_valid(type))
8745 if (!is_lvalue(value)) {
8746 errorf(&expression->base.source_position, "'&' requires an lvalue");
8748 if (type->kind == TYPE_BITFIELD) {
8749 errorf(&expression->base.source_position,
8750 "'&' not allowed on object with bitfield type '%T'",
8754 set_address_taken(value, false);
8756 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8759 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8760 static expression_t *parse_##unexpression_type(void) \
8762 expression_t *unary_expression \
8763 = allocate_expression_zero(unexpression_type); \
8765 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8767 sfunc(&unary_expression->unary); \
8769 return unary_expression; \
8772 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8773 semantic_unexpr_arithmetic)
8774 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8775 semantic_unexpr_plus)
8776 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8778 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8779 semantic_dereference)
8780 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8782 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8783 semantic_unexpr_integer)
8784 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8786 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8789 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8791 static expression_t *parse_##unexpression_type(expression_t *left) \
8793 expression_t *unary_expression \
8794 = allocate_expression_zero(unexpression_type); \
8796 unary_expression->unary.value = left; \
8798 sfunc(&unary_expression->unary); \
8800 return unary_expression; \
8803 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8804 EXPR_UNARY_POSTFIX_INCREMENT,
8806 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8807 EXPR_UNARY_POSTFIX_DECREMENT,
8810 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8812 /* TODO: handle complex + imaginary types */
8814 type_left = get_unqualified_type(type_left);
8815 type_right = get_unqualified_type(type_right);
8817 /* § 6.3.1.8 Usual arithmetic conversions */
8818 if (type_left == type_long_double || type_right == type_long_double) {
8819 return type_long_double;
8820 } else if (type_left == type_double || type_right == type_double) {
8822 } else if (type_left == type_float || type_right == type_float) {
8826 type_left = promote_integer(type_left);
8827 type_right = promote_integer(type_right);
8829 if (type_left == type_right)
8832 bool const signed_left = is_type_signed(type_left);
8833 bool const signed_right = is_type_signed(type_right);
8834 int const rank_left = get_rank(type_left);
8835 int const rank_right = get_rank(type_right);
8837 if (signed_left == signed_right)
8838 return rank_left >= rank_right ? type_left : type_right;
8847 u_rank = rank_right;
8848 u_type = type_right;
8850 s_rank = rank_right;
8851 s_type = type_right;
8856 if (u_rank >= s_rank)
8859 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8861 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8862 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8866 case ATOMIC_TYPE_INT: return type_unsigned_int;
8867 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8868 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8870 default: panic("invalid atomic type");
8875 * Check the semantic restrictions for a binary expression.
8877 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8879 expression_t *const left = expression->left;
8880 expression_t *const right = expression->right;
8881 type_t *const orig_type_left = left->base.type;
8882 type_t *const orig_type_right = right->base.type;
8883 type_t *const type_left = skip_typeref(orig_type_left);
8884 type_t *const type_right = skip_typeref(orig_type_right);
8886 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8887 /* TODO: improve error message */
8888 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8889 errorf(&expression->base.source_position,
8890 "operation needs arithmetic types");
8895 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8896 expression->left = create_implicit_cast(left, arithmetic_type);
8897 expression->right = create_implicit_cast(right, arithmetic_type);
8898 expression->base.type = arithmetic_type;
8901 static void warn_div_by_zero(binary_expression_t const *const expression)
8903 if (!warning.div_by_zero ||
8904 !is_type_integer(expression->base.type))
8907 expression_t const *const right = expression->right;
8908 /* The type of the right operand can be different for /= */
8909 if (is_type_integer(right->base.type) &&
8910 is_constant_expression(right) &&
8911 fold_constant(right) == 0) {
8912 warningf(&expression->base.source_position, "division by zero");
8917 * Check the semantic restrictions for a div/mod expression.
8919 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8921 semantic_binexpr_arithmetic(expression);
8922 warn_div_by_zero(expression);
8925 static void warn_addsub_in_shift(const expression_t *const expr)
8927 if (expr->base.parenthesized)
8931 switch (expr->kind) {
8932 case EXPR_BINARY_ADD: op = '+'; break;
8933 case EXPR_BINARY_SUB: op = '-'; break;
8937 warningf(&expr->base.source_position,
8938 "suggest parentheses around '%c' inside shift", op);
8941 static void semantic_shift_op(binary_expression_t *expression)
8943 expression_t *const left = expression->left;
8944 expression_t *const right = expression->right;
8945 type_t *const orig_type_left = left->base.type;
8946 type_t *const orig_type_right = right->base.type;
8947 type_t * type_left = skip_typeref(orig_type_left);
8948 type_t * type_right = skip_typeref(orig_type_right);
8950 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8951 /* TODO: improve error message */
8952 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8953 errorf(&expression->base.source_position,
8954 "operands of shift operation must have integer types");
8959 if (warning.parentheses) {
8960 warn_addsub_in_shift(left);
8961 warn_addsub_in_shift(right);
8964 type_left = promote_integer(type_left);
8965 type_right = promote_integer(type_right);
8967 expression->left = create_implicit_cast(left, type_left);
8968 expression->right = create_implicit_cast(right, type_right);
8969 expression->base.type = type_left;
8972 static void semantic_add(binary_expression_t *expression)
8974 expression_t *const left = expression->left;
8975 expression_t *const right = expression->right;
8976 type_t *const orig_type_left = left->base.type;
8977 type_t *const orig_type_right = right->base.type;
8978 type_t *const type_left = skip_typeref(orig_type_left);
8979 type_t *const type_right = skip_typeref(orig_type_right);
8982 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8983 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8984 expression->left = create_implicit_cast(left, arithmetic_type);
8985 expression->right = create_implicit_cast(right, arithmetic_type);
8986 expression->base.type = arithmetic_type;
8987 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8988 check_pointer_arithmetic(&expression->base.source_position,
8989 type_left, orig_type_left);
8990 expression->base.type = type_left;
8991 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8992 check_pointer_arithmetic(&expression->base.source_position,
8993 type_right, orig_type_right);
8994 expression->base.type = type_right;
8995 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8996 errorf(&expression->base.source_position,
8997 "invalid operands to binary + ('%T', '%T')",
8998 orig_type_left, orig_type_right);
9002 static void semantic_sub(binary_expression_t *expression)
9004 expression_t *const left = expression->left;
9005 expression_t *const right = expression->right;
9006 type_t *const orig_type_left = left->base.type;
9007 type_t *const orig_type_right = right->base.type;
9008 type_t *const type_left = skip_typeref(orig_type_left);
9009 type_t *const type_right = skip_typeref(orig_type_right);
9010 source_position_t const *const pos = &expression->base.source_position;
9013 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9014 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9015 expression->left = create_implicit_cast(left, arithmetic_type);
9016 expression->right = create_implicit_cast(right, arithmetic_type);
9017 expression->base.type = arithmetic_type;
9018 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9019 check_pointer_arithmetic(&expression->base.source_position,
9020 type_left, orig_type_left);
9021 expression->base.type = type_left;
9022 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9023 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
9024 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
9025 if (!types_compatible(unqual_left, unqual_right)) {
9027 "subtracting pointers to incompatible types '%T' and '%T'",
9028 orig_type_left, orig_type_right);
9029 } else if (!is_type_object(unqual_left)) {
9030 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
9031 errorf(pos, "subtracting pointers to non-object types '%T'",
9033 } else if (warning.other) {
9034 warningf(pos, "subtracting pointers to void");
9037 expression->base.type = type_ptrdiff_t;
9038 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9039 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
9040 orig_type_left, orig_type_right);
9044 static void warn_string_literal_address(expression_t const* expr)
9046 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
9047 expr = expr->unary.value;
9048 if (expr->kind != EXPR_UNARY_DEREFERENCE)
9050 expr = expr->unary.value;
9053 if (expr->kind == EXPR_STRING_LITERAL ||
9054 expr->kind == EXPR_WIDE_STRING_LITERAL) {
9055 warningf(&expr->base.source_position,
9056 "comparison with string literal results in unspecified behaviour");
9060 static void warn_comparison_in_comparison(const expression_t *const expr)
9062 if (expr->base.parenthesized)
9064 switch (expr->base.kind) {
9065 case EXPR_BINARY_LESS:
9066 case EXPR_BINARY_GREATER:
9067 case EXPR_BINARY_LESSEQUAL:
9068 case EXPR_BINARY_GREATEREQUAL:
9069 case EXPR_BINARY_NOTEQUAL:
9070 case EXPR_BINARY_EQUAL:
9071 warningf(&expr->base.source_position,
9072 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9079 static bool maybe_negative(expression_t const *const expr)
9082 !is_constant_expression(expr) ||
9083 fold_constant(expr) < 0;
9087 * Check the semantics of comparison expressions.
9089 * @param expression The expression to check.
9091 static void semantic_comparison(binary_expression_t *expression)
9093 expression_t *left = expression->left;
9094 expression_t *right = expression->right;
9096 if (warning.address) {
9097 warn_string_literal_address(left);
9098 warn_string_literal_address(right);
9100 expression_t const* const func_left = get_reference_address(left);
9101 if (func_left != NULL && is_null_pointer_constant(right)) {
9102 warningf(&expression->base.source_position,
9103 "the address of '%Y' will never be NULL",
9104 func_left->reference.entity->base.symbol);
9107 expression_t const* const func_right = get_reference_address(right);
9108 if (func_right != NULL && is_null_pointer_constant(right)) {
9109 warningf(&expression->base.source_position,
9110 "the address of '%Y' will never be NULL",
9111 func_right->reference.entity->base.symbol);
9115 if (warning.parentheses) {
9116 warn_comparison_in_comparison(left);
9117 warn_comparison_in_comparison(right);
9120 type_t *orig_type_left = left->base.type;
9121 type_t *orig_type_right = right->base.type;
9122 type_t *type_left = skip_typeref(orig_type_left);
9123 type_t *type_right = skip_typeref(orig_type_right);
9125 /* TODO non-arithmetic types */
9126 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9127 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9129 /* test for signed vs unsigned compares */
9130 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9131 bool const signed_left = is_type_signed(type_left);
9132 bool const signed_right = is_type_signed(type_right);
9133 if (signed_left != signed_right) {
9134 /* FIXME long long needs better const folding magic */
9135 /* TODO check whether constant value can be represented by other type */
9136 if ((signed_left && maybe_negative(left)) ||
9137 (signed_right && maybe_negative(right))) {
9138 warningf(&expression->base.source_position,
9139 "comparison between signed and unsigned");
9144 expression->left = create_implicit_cast(left, arithmetic_type);
9145 expression->right = create_implicit_cast(right, arithmetic_type);
9146 expression->base.type = arithmetic_type;
9147 if (warning.float_equal &&
9148 (expression->base.kind == EXPR_BINARY_EQUAL ||
9149 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9150 is_type_float(arithmetic_type)) {
9151 warningf(&expression->base.source_position,
9152 "comparing floating point with == or != is unsafe");
9154 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9155 /* TODO check compatibility */
9156 } else if (is_type_pointer(type_left)) {
9157 expression->right = create_implicit_cast(right, type_left);
9158 } else if (is_type_pointer(type_right)) {
9159 expression->left = create_implicit_cast(left, type_right);
9160 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9161 type_error_incompatible("invalid operands in comparison",
9162 &expression->base.source_position,
9163 type_left, type_right);
9165 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9169 * Checks if a compound type has constant fields.
9171 static bool has_const_fields(const compound_type_t *type)
9173 compound_t *compound = type->compound;
9174 entity_t *entry = compound->members.entities;
9176 for (; entry != NULL; entry = entry->base.next) {
9177 if (!is_declaration(entry))
9180 const type_t *decl_type = skip_typeref(entry->declaration.type);
9181 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9188 static bool is_valid_assignment_lhs(expression_t const* const left)
9190 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9191 type_t *const type_left = skip_typeref(orig_type_left);
9193 if (!is_lvalue(left)) {
9194 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9199 if (left->kind == EXPR_REFERENCE
9200 && left->reference.entity->kind == ENTITY_FUNCTION) {
9201 errorf(HERE, "cannot assign to function '%E'", left);
9205 if (is_type_array(type_left)) {
9206 errorf(HERE, "cannot assign to array '%E'", left);
9209 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9210 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9214 if (is_type_incomplete(type_left)) {
9215 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9216 left, orig_type_left);
9219 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9220 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9221 left, orig_type_left);
9228 static void semantic_arithmetic_assign(binary_expression_t *expression)
9230 expression_t *left = expression->left;
9231 expression_t *right = expression->right;
9232 type_t *orig_type_left = left->base.type;
9233 type_t *orig_type_right = right->base.type;
9235 if (!is_valid_assignment_lhs(left))
9238 type_t *type_left = skip_typeref(orig_type_left);
9239 type_t *type_right = skip_typeref(orig_type_right);
9241 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9242 /* TODO: improve error message */
9243 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9244 errorf(&expression->base.source_position,
9245 "operation needs arithmetic types");
9250 /* combined instructions are tricky. We can't create an implicit cast on
9251 * the left side, because we need the uncasted form for the store.
9252 * The ast2firm pass has to know that left_type must be right_type
9253 * for the arithmetic operation and create a cast by itself */
9254 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9255 expression->right = create_implicit_cast(right, arithmetic_type);
9256 expression->base.type = type_left;
9259 static void semantic_divmod_assign(binary_expression_t *expression)
9261 semantic_arithmetic_assign(expression);
9262 warn_div_by_zero(expression);
9265 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9267 expression_t *const left = expression->left;
9268 expression_t *const right = expression->right;
9269 type_t *const orig_type_left = left->base.type;
9270 type_t *const orig_type_right = right->base.type;
9271 type_t *const type_left = skip_typeref(orig_type_left);
9272 type_t *const type_right = skip_typeref(orig_type_right);
9274 if (!is_valid_assignment_lhs(left))
9277 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9278 /* combined instructions are tricky. We can't create an implicit cast on
9279 * the left side, because we need the uncasted form for the store.
9280 * The ast2firm pass has to know that left_type must be right_type
9281 * for the arithmetic operation and create a cast by itself */
9282 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9283 expression->right = create_implicit_cast(right, arithmetic_type);
9284 expression->base.type = type_left;
9285 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9286 check_pointer_arithmetic(&expression->base.source_position,
9287 type_left, orig_type_left);
9288 expression->base.type = type_left;
9289 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9290 errorf(&expression->base.source_position,
9291 "incompatible types '%T' and '%T' in assignment",
9292 orig_type_left, orig_type_right);
9296 static void warn_logical_and_within_or(const expression_t *const expr)
9298 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9300 if (expr->base.parenthesized)
9302 warningf(&expr->base.source_position,
9303 "suggest parentheses around && within ||");
9307 * Check the semantic restrictions of a logical expression.
9309 static void semantic_logical_op(binary_expression_t *expression)
9311 /* §6.5.13:2 Each of the operands shall have scalar type.
9312 * §6.5.14:2 Each of the operands shall have scalar type. */
9313 semantic_condition(expression->left, "left operand of logical operator");
9314 semantic_condition(expression->right, "right operand of logical operator");
9315 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9316 warning.parentheses) {
9317 warn_logical_and_within_or(expression->left);
9318 warn_logical_and_within_or(expression->right);
9320 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9324 * Check the semantic restrictions of a binary assign expression.
9326 static void semantic_binexpr_assign(binary_expression_t *expression)
9328 expression_t *left = expression->left;
9329 type_t *orig_type_left = left->base.type;
9331 if (!is_valid_assignment_lhs(left))
9334 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9335 report_assign_error(error, orig_type_left, expression->right,
9336 "assignment", &left->base.source_position);
9337 expression->right = create_implicit_cast(expression->right, orig_type_left);
9338 expression->base.type = orig_type_left;
9342 * Determine if the outermost operation (or parts thereof) of the given
9343 * expression has no effect in order to generate a warning about this fact.
9344 * Therefore in some cases this only examines some of the operands of the
9345 * expression (see comments in the function and examples below).
9347 * f() + 23; // warning, because + has no effect
9348 * x || f(); // no warning, because x controls execution of f()
9349 * x ? y : f(); // warning, because y has no effect
9350 * (void)x; // no warning to be able to suppress the warning
9351 * This function can NOT be used for an "expression has definitely no effect"-
9353 static bool expression_has_effect(const expression_t *const expr)
9355 switch (expr->kind) {
9356 case EXPR_UNKNOWN: break;
9357 case EXPR_INVALID: return true; /* do NOT warn */
9358 case EXPR_REFERENCE: return false;
9359 case EXPR_REFERENCE_ENUM_VALUE: return false;
9360 /* suppress the warning for microsoft __noop operations */
9361 case EXPR_CONST: return expr->conste.is_ms_noop;
9362 case EXPR_CHARACTER_CONSTANT: return false;
9363 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9364 case EXPR_STRING_LITERAL: return false;
9365 case EXPR_WIDE_STRING_LITERAL: return false;
9366 case EXPR_LABEL_ADDRESS: return false;
9369 const call_expression_t *const call = &expr->call;
9370 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9373 switch (call->function->builtin_symbol.symbol->ID) {
9374 case T___builtin_va_end: return true;
9375 default: return false;
9379 /* Generate the warning if either the left or right hand side of a
9380 * conditional expression has no effect */
9381 case EXPR_CONDITIONAL: {
9382 const conditional_expression_t *const cond = &expr->conditional;
9384 expression_has_effect(cond->true_expression) &&
9385 expression_has_effect(cond->false_expression);
9388 case EXPR_SELECT: return false;
9389 case EXPR_ARRAY_ACCESS: return false;
9390 case EXPR_SIZEOF: return false;
9391 case EXPR_CLASSIFY_TYPE: return false;
9392 case EXPR_ALIGNOF: return false;
9394 case EXPR_FUNCNAME: return false;
9395 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9396 case EXPR_BUILTIN_CONSTANT_P: return false;
9397 case EXPR_BUILTIN_PREFETCH: return true;
9398 case EXPR_OFFSETOF: return false;
9399 case EXPR_VA_START: return true;
9400 case EXPR_VA_ARG: return true;
9401 case EXPR_STATEMENT: return true; // TODO
9402 case EXPR_COMPOUND_LITERAL: return false;
9404 case EXPR_UNARY_NEGATE: return false;
9405 case EXPR_UNARY_PLUS: return false;
9406 case EXPR_UNARY_BITWISE_NEGATE: return false;
9407 case EXPR_UNARY_NOT: return false;
9408 case EXPR_UNARY_DEREFERENCE: return false;
9409 case EXPR_UNARY_TAKE_ADDRESS: return false;
9410 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9411 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9412 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9413 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9415 /* Treat void casts as if they have an effect in order to being able to
9416 * suppress the warning */
9417 case EXPR_UNARY_CAST: {
9418 type_t *const type = skip_typeref(expr->base.type);
9419 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9422 case EXPR_UNARY_CAST_IMPLICIT: return true;
9423 case EXPR_UNARY_ASSUME: return true;
9424 case EXPR_UNARY_DELETE: return true;
9425 case EXPR_UNARY_DELETE_ARRAY: return true;
9426 case EXPR_UNARY_THROW: return true;
9428 case EXPR_BINARY_ADD: return false;
9429 case EXPR_BINARY_SUB: return false;
9430 case EXPR_BINARY_MUL: return false;
9431 case EXPR_BINARY_DIV: return false;
9432 case EXPR_BINARY_MOD: return false;
9433 case EXPR_BINARY_EQUAL: return false;
9434 case EXPR_BINARY_NOTEQUAL: return false;
9435 case EXPR_BINARY_LESS: return false;
9436 case EXPR_BINARY_LESSEQUAL: return false;
9437 case EXPR_BINARY_GREATER: return false;
9438 case EXPR_BINARY_GREATEREQUAL: return false;
9439 case EXPR_BINARY_BITWISE_AND: return false;
9440 case EXPR_BINARY_BITWISE_OR: return false;
9441 case EXPR_BINARY_BITWISE_XOR: return false;
9442 case EXPR_BINARY_SHIFTLEFT: return false;
9443 case EXPR_BINARY_SHIFTRIGHT: return false;
9444 case EXPR_BINARY_ASSIGN: return true;
9445 case EXPR_BINARY_MUL_ASSIGN: return true;
9446 case EXPR_BINARY_DIV_ASSIGN: return true;
9447 case EXPR_BINARY_MOD_ASSIGN: return true;
9448 case EXPR_BINARY_ADD_ASSIGN: return true;
9449 case EXPR_BINARY_SUB_ASSIGN: return true;
9450 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9451 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9452 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9453 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9454 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9456 /* Only examine the right hand side of && and ||, because the left hand
9457 * side already has the effect of controlling the execution of the right
9459 case EXPR_BINARY_LOGICAL_AND:
9460 case EXPR_BINARY_LOGICAL_OR:
9461 /* Only examine the right hand side of a comma expression, because the left
9462 * hand side has a separate warning */
9463 case EXPR_BINARY_COMMA:
9464 return expression_has_effect(expr->binary.right);
9466 case EXPR_BINARY_ISGREATER: return false;
9467 case EXPR_BINARY_ISGREATEREQUAL: return false;
9468 case EXPR_BINARY_ISLESS: return false;
9469 case EXPR_BINARY_ISLESSEQUAL: return false;
9470 case EXPR_BINARY_ISLESSGREATER: return false;
9471 case EXPR_BINARY_ISUNORDERED: return false;
9474 internal_errorf(HERE, "unexpected expression");
9477 static void semantic_comma(binary_expression_t *expression)
9479 if (warning.unused_value) {
9480 const expression_t *const left = expression->left;
9481 if (!expression_has_effect(left)) {
9482 warningf(&left->base.source_position,
9483 "left-hand operand of comma expression has no effect");
9486 expression->base.type = expression->right->base.type;
9490 * @param prec_r precedence of the right operand
9492 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9493 static expression_t *parse_##binexpression_type(expression_t *left) \
9495 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9496 binexpr->binary.left = left; \
9499 expression_t *right = parse_sub_expression(prec_r); \
9501 binexpr->binary.right = right; \
9502 sfunc(&binexpr->binary); \
9507 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9508 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9509 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9510 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9511 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9512 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9513 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9514 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9515 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9516 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9517 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9518 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9519 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9520 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9521 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9522 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9523 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9524 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9525 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9526 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9527 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9528 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9529 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9530 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9531 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9532 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9533 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9534 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9535 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9536 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9539 static expression_t *parse_sub_expression(precedence_t precedence)
9541 if (token.type < 0) {
9542 return expected_expression_error();
9545 expression_parser_function_t *parser
9546 = &expression_parsers[token.type];
9547 source_position_t source_position = token.source_position;
9550 if (parser->parser != NULL) {
9551 left = parser->parser();
9553 left = parse_primary_expression();
9555 assert(left != NULL);
9556 left->base.source_position = source_position;
9559 if (token.type < 0) {
9560 return expected_expression_error();
9563 parser = &expression_parsers[token.type];
9564 if (parser->infix_parser == NULL)
9566 if (parser->infix_precedence < precedence)
9569 left = parser->infix_parser(left);
9571 assert(left != NULL);
9572 assert(left->kind != EXPR_UNKNOWN);
9573 left->base.source_position = source_position;
9580 * Parse an expression.
9582 static expression_t *parse_expression(void)
9584 return parse_sub_expression(PREC_EXPRESSION);
9588 * Register a parser for a prefix-like operator.
9590 * @param parser the parser function
9591 * @param token_type the token type of the prefix token
9593 static void register_expression_parser(parse_expression_function parser,
9596 expression_parser_function_t *entry = &expression_parsers[token_type];
9598 if (entry->parser != NULL) {
9599 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9600 panic("trying to register multiple expression parsers for a token");
9602 entry->parser = parser;
9606 * Register a parser for an infix operator with given precedence.
9608 * @param parser the parser function
9609 * @param token_type the token type of the infix operator
9610 * @param precedence the precedence of the operator
9612 static void register_infix_parser(parse_expression_infix_function parser,
9613 int token_type, precedence_t precedence)
9615 expression_parser_function_t *entry = &expression_parsers[token_type];
9617 if (entry->infix_parser != NULL) {
9618 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9619 panic("trying to register multiple infix expression parsers for a "
9622 entry->infix_parser = parser;
9623 entry->infix_precedence = precedence;
9627 * Initialize the expression parsers.
9629 static void init_expression_parsers(void)
9631 memset(&expression_parsers, 0, sizeof(expression_parsers));
9633 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9634 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9635 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9636 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9637 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9638 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9639 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9640 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9641 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9642 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9643 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9644 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9645 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9646 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9647 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9648 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9649 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9650 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9651 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9652 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9653 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9654 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9655 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9656 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9657 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9658 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9659 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9660 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9661 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9662 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9663 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9664 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9665 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9666 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9667 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9668 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9669 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9671 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9672 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9673 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9674 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9675 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9676 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9677 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9678 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9679 register_expression_parser(parse_sizeof, T_sizeof);
9680 register_expression_parser(parse_alignof, T___alignof__);
9681 register_expression_parser(parse_extension, T___extension__);
9682 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9683 register_expression_parser(parse_delete, T_delete);
9684 register_expression_parser(parse_throw, T_throw);
9688 * Parse a asm statement arguments specification.
9690 static asm_argument_t *parse_asm_arguments(bool is_out)
9692 asm_argument_t *result = NULL;
9693 asm_argument_t **anchor = &result;
9695 while (token.type == T_STRING_LITERAL || token.type == '[') {
9696 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9697 memset(argument, 0, sizeof(argument[0]));
9699 if (token.type == '[') {
9701 if (token.type != T_IDENTIFIER) {
9702 parse_error_expected("while parsing asm argument",
9703 T_IDENTIFIER, NULL);
9706 argument->symbol = token.v.symbol;
9708 expect(']', end_error);
9711 argument->constraints = parse_string_literals();
9712 expect('(', end_error);
9713 add_anchor_token(')');
9714 expression_t *expression = parse_expression();
9715 rem_anchor_token(')');
9717 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9718 * change size or type representation (e.g. int -> long is ok, but
9719 * int -> float is not) */
9720 if (expression->kind == EXPR_UNARY_CAST) {
9721 type_t *const type = expression->base.type;
9722 type_kind_t const kind = type->kind;
9723 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9726 if (kind == TYPE_ATOMIC) {
9727 atomic_type_kind_t const akind = type->atomic.akind;
9728 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9729 size = get_atomic_type_size(akind);
9731 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9732 size = get_atomic_type_size(get_intptr_kind());
9736 expression_t *const value = expression->unary.value;
9737 type_t *const value_type = value->base.type;
9738 type_kind_t const value_kind = value_type->kind;
9740 unsigned value_flags;
9741 unsigned value_size;
9742 if (value_kind == TYPE_ATOMIC) {
9743 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9744 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9745 value_size = get_atomic_type_size(value_akind);
9746 } else if (value_kind == TYPE_POINTER) {
9747 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9748 value_size = get_atomic_type_size(get_intptr_kind());
9753 if (value_flags != flags || value_size != size)
9757 } while (expression->kind == EXPR_UNARY_CAST);
9761 if (!is_lvalue(expression)) {
9762 errorf(&expression->base.source_position,
9763 "asm output argument is not an lvalue");
9766 if (argument->constraints.begin[0] == '+')
9767 mark_vars_read(expression, NULL);
9769 mark_vars_read(expression, NULL);
9771 argument->expression = expression;
9772 expect(')', end_error);
9774 set_address_taken(expression, true);
9777 anchor = &argument->next;
9779 if (token.type != ',')
9790 * Parse a asm statement clobber specification.
9792 static asm_clobber_t *parse_asm_clobbers(void)
9794 asm_clobber_t *result = NULL;
9795 asm_clobber_t *last = NULL;
9797 while (token.type == T_STRING_LITERAL) {
9798 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9799 clobber->clobber = parse_string_literals();
9802 last->next = clobber;
9808 if (token.type != ',')
9817 * Parse an asm statement.
9819 static statement_t *parse_asm_statement(void)
9821 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9822 asm_statement_t *asm_statement = &statement->asms;
9826 if (token.type == T_volatile) {
9828 asm_statement->is_volatile = true;
9831 expect('(', end_error);
9832 add_anchor_token(')');
9833 add_anchor_token(':');
9834 asm_statement->asm_text = parse_string_literals();
9836 if (token.type != ':') {
9837 rem_anchor_token(':');
9842 asm_statement->outputs = parse_asm_arguments(true);
9843 if (token.type != ':') {
9844 rem_anchor_token(':');
9849 asm_statement->inputs = parse_asm_arguments(false);
9850 if (token.type != ':') {
9851 rem_anchor_token(':');
9854 rem_anchor_token(':');
9857 asm_statement->clobbers = parse_asm_clobbers();
9860 rem_anchor_token(')');
9861 expect(')', end_error);
9862 expect(';', end_error);
9864 if (asm_statement->outputs == NULL) {
9865 /* GCC: An 'asm' instruction without any output operands will be treated
9866 * identically to a volatile 'asm' instruction. */
9867 asm_statement->is_volatile = true;
9872 return create_invalid_statement();
9876 * Parse a case statement.
9878 static statement_t *parse_case_statement(void)
9880 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9881 source_position_t *const pos = &statement->base.source_position;
9885 expression_t *const expression = parse_expression();
9886 statement->case_label.expression = expression;
9887 if (!is_constant_expression(expression)) {
9888 /* This check does not prevent the error message in all cases of an
9889 * prior error while parsing the expression. At least it catches the
9890 * common case of a mistyped enum entry. */
9891 if (is_type_valid(skip_typeref(expression->base.type))) {
9892 errorf(pos, "case label does not reduce to an integer constant");
9894 statement->case_label.is_bad = true;
9896 long const val = fold_constant(expression);
9897 statement->case_label.first_case = val;
9898 statement->case_label.last_case = val;
9902 if (token.type == T_DOTDOTDOT) {
9904 expression_t *const end_range = parse_expression();
9905 statement->case_label.end_range = end_range;
9906 if (!is_constant_expression(end_range)) {
9907 /* This check does not prevent the error message in all cases of an
9908 * prior error while parsing the expression. At least it catches the
9909 * common case of a mistyped enum entry. */
9910 if (is_type_valid(skip_typeref(end_range->base.type))) {
9911 errorf(pos, "case range does not reduce to an integer constant");
9913 statement->case_label.is_bad = true;
9915 long const val = fold_constant(end_range);
9916 statement->case_label.last_case = val;
9918 if (warning.other && val < statement->case_label.first_case) {
9919 statement->case_label.is_empty_range = true;
9920 warningf(pos, "empty range specified");
9926 PUSH_PARENT(statement);
9928 expect(':', end_error);
9931 if (current_switch != NULL) {
9932 if (! statement->case_label.is_bad) {
9933 /* Check for duplicate case values */
9934 case_label_statement_t *c = &statement->case_label;
9935 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9936 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9939 if (c->last_case < l->first_case || c->first_case > l->last_case)
9942 errorf(pos, "duplicate case value (previously used %P)",
9943 &l->base.source_position);
9947 /* link all cases into the switch statement */
9948 if (current_switch->last_case == NULL) {
9949 current_switch->first_case = &statement->case_label;
9951 current_switch->last_case->next = &statement->case_label;
9953 current_switch->last_case = &statement->case_label;
9955 errorf(pos, "case label not within a switch statement");
9958 statement_t *const inner_stmt = parse_statement();
9959 statement->case_label.statement = inner_stmt;
9960 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9961 errorf(&inner_stmt->base.source_position, "declaration after case label");
9969 * Parse a default statement.
9971 static statement_t *parse_default_statement(void)
9973 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9977 PUSH_PARENT(statement);
9979 expect(':', end_error);
9980 if (current_switch != NULL) {
9981 const case_label_statement_t *def_label = current_switch->default_label;
9982 if (def_label != NULL) {
9983 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9984 &def_label->base.source_position);
9986 current_switch->default_label = &statement->case_label;
9988 /* link all cases into the switch statement */
9989 if (current_switch->last_case == NULL) {
9990 current_switch->first_case = &statement->case_label;
9992 current_switch->last_case->next = &statement->case_label;
9994 current_switch->last_case = &statement->case_label;
9997 errorf(&statement->base.source_position,
9998 "'default' label not within a switch statement");
10001 statement_t *const inner_stmt = parse_statement();
10002 statement->case_label.statement = inner_stmt;
10003 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10004 errorf(&inner_stmt->base.source_position, "declaration after default label");
10011 return create_invalid_statement();
10015 * Parse a label statement.
10017 static statement_t *parse_label_statement(void)
10019 assert(token.type == T_IDENTIFIER);
10020 symbol_t *symbol = token.v.symbol;
10021 label_t *label = get_label(symbol);
10023 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
10024 statement->label.label = label;
10028 PUSH_PARENT(statement);
10030 /* if statement is already set then the label is defined twice,
10031 * otherwise it was just mentioned in a goto/local label declaration so far
10033 if (label->statement != NULL) {
10034 errorf(HERE, "duplicate label '%Y' (declared %P)",
10035 symbol, &label->base.source_position);
10037 label->base.source_position = token.source_position;
10038 label->statement = statement;
10043 if (token.type == '}') {
10044 /* TODO only warn? */
10045 if (warning.other && false) {
10046 warningf(HERE, "label at end of compound statement");
10047 statement->label.statement = create_empty_statement();
10049 errorf(HERE, "label at end of compound statement");
10050 statement->label.statement = create_invalid_statement();
10052 } else if (token.type == ';') {
10053 /* Eat an empty statement here, to avoid the warning about an empty
10054 * statement after a label. label:; is commonly used to have a label
10055 * before a closing brace. */
10056 statement->label.statement = create_empty_statement();
10059 statement_t *const inner_stmt = parse_statement();
10060 statement->label.statement = inner_stmt;
10061 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10062 errorf(&inner_stmt->base.source_position, "declaration after label");
10066 /* remember the labels in a list for later checking */
10067 *label_anchor = &statement->label;
10068 label_anchor = &statement->label.next;
10075 * Parse an if statement.
10077 static statement_t *parse_if(void)
10079 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10083 PUSH_PARENT(statement);
10085 add_anchor_token('{');
10087 expect('(', end_error);
10088 add_anchor_token(')');
10089 expression_t *const expr = parse_expression();
10090 statement->ifs.condition = expr;
10091 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10093 semantic_condition(expr, "condition of 'if'-statment");
10094 mark_vars_read(expr, NULL);
10095 rem_anchor_token(')');
10096 expect(')', end_error);
10099 rem_anchor_token('{');
10101 add_anchor_token(T_else);
10102 statement_t *const true_stmt = parse_statement();
10103 statement->ifs.true_statement = true_stmt;
10104 rem_anchor_token(T_else);
10106 if (token.type == T_else) {
10108 statement->ifs.false_statement = parse_statement();
10109 } else if (warning.parentheses &&
10110 true_stmt->kind == STATEMENT_IF &&
10111 true_stmt->ifs.false_statement != NULL) {
10112 warningf(&true_stmt->base.source_position,
10113 "suggest explicit braces to avoid ambiguous 'else'");
10121 * Check that all enums are handled in a switch.
10123 * @param statement the switch statement to check
10125 static void check_enum_cases(const switch_statement_t *statement)
10127 const type_t *type = skip_typeref(statement->expression->base.type);
10128 if (! is_type_enum(type))
10130 const enum_type_t *enumt = &type->enumt;
10132 /* if we have a default, no warnings */
10133 if (statement->default_label != NULL)
10136 /* FIXME: calculation of value should be done while parsing */
10137 /* TODO: quadratic algorithm here. Change to an n log n one */
10138 long last_value = -1;
10139 const entity_t *entry = enumt->enume->base.next;
10140 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10141 entry = entry->base.next) {
10142 const expression_t *expression = entry->enum_value.value;
10143 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10144 bool found = false;
10145 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10146 if (l->expression == NULL)
10148 if (l->first_case <= value && value <= l->last_case) {
10154 warningf(&statement->base.source_position,
10155 "enumeration value '%Y' not handled in switch",
10156 entry->base.symbol);
10158 last_value = value;
10163 * Parse a switch statement.
10165 static statement_t *parse_switch(void)
10167 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10171 PUSH_PARENT(statement);
10173 expect('(', end_error);
10174 add_anchor_token(')');
10175 expression_t *const expr = parse_expression();
10176 mark_vars_read(expr, NULL);
10177 type_t * type = skip_typeref(expr->base.type);
10178 if (is_type_integer(type)) {
10179 type = promote_integer(type);
10180 if (warning.traditional) {
10181 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10182 warningf(&expr->base.source_position,
10183 "'%T' switch expression not converted to '%T' in ISO C",
10187 } else if (is_type_valid(type)) {
10188 errorf(&expr->base.source_position,
10189 "switch quantity is not an integer, but '%T'", type);
10190 type = type_error_type;
10192 statement->switchs.expression = create_implicit_cast(expr, type);
10193 expect(')', end_error);
10194 rem_anchor_token(')');
10196 switch_statement_t *rem = current_switch;
10197 current_switch = &statement->switchs;
10198 statement->switchs.body = parse_statement();
10199 current_switch = rem;
10201 if (warning.switch_default &&
10202 statement->switchs.default_label == NULL) {
10203 warningf(&statement->base.source_position, "switch has no default case");
10205 if (warning.switch_enum)
10206 check_enum_cases(&statement->switchs);
10212 return create_invalid_statement();
10215 static statement_t *parse_loop_body(statement_t *const loop)
10217 statement_t *const rem = current_loop;
10218 current_loop = loop;
10220 statement_t *const body = parse_statement();
10222 current_loop = rem;
10227 * Parse a while statement.
10229 static statement_t *parse_while(void)
10231 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10235 PUSH_PARENT(statement);
10237 expect('(', end_error);
10238 add_anchor_token(')');
10239 expression_t *const cond = parse_expression();
10240 statement->whiles.condition = cond;
10241 /* §6.8.5:2 The controlling expression of an iteration statement shall
10242 * have scalar type. */
10243 semantic_condition(cond, "condition of 'while'-statement");
10244 mark_vars_read(cond, NULL);
10245 rem_anchor_token(')');
10246 expect(')', end_error);
10248 statement->whiles.body = parse_loop_body(statement);
10254 return create_invalid_statement();
10258 * Parse a do statement.
10260 static statement_t *parse_do(void)
10262 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10266 PUSH_PARENT(statement);
10268 add_anchor_token(T_while);
10269 statement->do_while.body = parse_loop_body(statement);
10270 rem_anchor_token(T_while);
10272 expect(T_while, end_error);
10273 expect('(', end_error);
10274 add_anchor_token(')');
10275 expression_t *const cond = parse_expression();
10276 statement->do_while.condition = cond;
10277 /* §6.8.5:2 The controlling expression of an iteration statement shall
10278 * have scalar type. */
10279 semantic_condition(cond, "condition of 'do-while'-statement");
10280 mark_vars_read(cond, NULL);
10281 rem_anchor_token(')');
10282 expect(')', end_error);
10283 expect(';', end_error);
10289 return create_invalid_statement();
10293 * Parse a for statement.
10295 static statement_t *parse_for(void)
10297 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10301 expect('(', end_error1);
10302 add_anchor_token(')');
10304 PUSH_PARENT(statement);
10306 size_t const top = environment_top();
10307 scope_t *old_scope = scope_push(&statement->fors.scope);
10309 if (token.type == ';') {
10311 } else if (is_declaration_specifier(&token, false)) {
10312 parse_declaration(record_entity, DECL_FLAGS_NONE);
10314 add_anchor_token(';');
10315 expression_t *const init = parse_expression();
10316 statement->fors.initialisation = init;
10317 mark_vars_read(init, ENT_ANY);
10318 if (warning.unused_value && !expression_has_effect(init)) {
10319 warningf(&init->base.source_position,
10320 "initialisation of 'for'-statement has no effect");
10322 rem_anchor_token(';');
10323 expect(';', end_error2);
10326 if (token.type != ';') {
10327 add_anchor_token(';');
10328 expression_t *const cond = parse_expression();
10329 statement->fors.condition = cond;
10330 /* §6.8.5:2 The controlling expression of an iteration statement
10331 * shall have scalar type. */
10332 semantic_condition(cond, "condition of 'for'-statement");
10333 mark_vars_read(cond, NULL);
10334 rem_anchor_token(';');
10336 expect(';', end_error2);
10337 if (token.type != ')') {
10338 expression_t *const step = parse_expression();
10339 statement->fors.step = step;
10340 mark_vars_read(step, ENT_ANY);
10341 if (warning.unused_value && !expression_has_effect(step)) {
10342 warningf(&step->base.source_position,
10343 "step of 'for'-statement has no effect");
10346 expect(')', end_error2);
10347 rem_anchor_token(')');
10348 statement->fors.body = parse_loop_body(statement);
10350 assert(current_scope == &statement->fors.scope);
10351 scope_pop(old_scope);
10352 environment_pop_to(top);
10359 rem_anchor_token(')');
10360 assert(current_scope == &statement->fors.scope);
10361 scope_pop(old_scope);
10362 environment_pop_to(top);
10366 return create_invalid_statement();
10370 * Parse a goto statement.
10372 static statement_t *parse_goto(void)
10374 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10377 if (GNU_MODE && token.type == '*') {
10379 expression_t *expression = parse_expression();
10380 mark_vars_read(expression, NULL);
10382 /* Argh: although documentation says the expression must be of type void*,
10383 * gcc accepts anything that can be casted into void* without error */
10384 type_t *type = expression->base.type;
10386 if (type != type_error_type) {
10387 if (!is_type_pointer(type) && !is_type_integer(type)) {
10388 errorf(&expression->base.source_position,
10389 "cannot convert to a pointer type");
10390 } else if (warning.other && type != type_void_ptr) {
10391 warningf(&expression->base.source_position,
10392 "type of computed goto expression should be 'void*' not '%T'", type);
10394 expression = create_implicit_cast(expression, type_void_ptr);
10397 statement->gotos.expression = expression;
10399 if (token.type != T_IDENTIFIER) {
10401 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10403 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10404 eat_until_anchor();
10407 symbol_t *symbol = token.v.symbol;
10410 statement->gotos.label = get_label(symbol);
10413 /* remember the goto's in a list for later checking */
10414 *goto_anchor = &statement->gotos;
10415 goto_anchor = &statement->gotos.next;
10417 expect(';', end_error);
10421 return create_invalid_statement();
10425 * Parse a continue statement.
10427 static statement_t *parse_continue(void)
10429 if (current_loop == NULL) {
10430 errorf(HERE, "continue statement not within loop");
10433 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10436 expect(';', end_error);
10443 * Parse a break statement.
10445 static statement_t *parse_break(void)
10447 if (current_switch == NULL && current_loop == NULL) {
10448 errorf(HERE, "break statement not within loop or switch");
10451 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10454 expect(';', end_error);
10461 * Parse a __leave statement.
10463 static statement_t *parse_leave_statement(void)
10465 if (current_try == NULL) {
10466 errorf(HERE, "__leave statement not within __try");
10469 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10472 expect(';', end_error);
10479 * Check if a given entity represents a local variable.
10481 static bool is_local_variable(const entity_t *entity)
10483 if (entity->kind != ENTITY_VARIABLE)
10486 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10487 case STORAGE_CLASS_AUTO:
10488 case STORAGE_CLASS_REGISTER: {
10489 const type_t *type = skip_typeref(entity->declaration.type);
10490 if (is_type_function(type)) {
10502 * Check if a given expression represents a local variable.
10504 static bool expression_is_local_variable(const expression_t *expression)
10506 if (expression->base.kind != EXPR_REFERENCE) {
10509 const entity_t *entity = expression->reference.entity;
10510 return is_local_variable(entity);
10514 * Check if a given expression represents a local variable and
10515 * return its declaration then, else return NULL.
10517 entity_t *expression_is_variable(const expression_t *expression)
10519 if (expression->base.kind != EXPR_REFERENCE) {
10522 entity_t *entity = expression->reference.entity;
10523 if (entity->kind != ENTITY_VARIABLE)
10530 * Parse a return statement.
10532 static statement_t *parse_return(void)
10536 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10538 expression_t *return_value = NULL;
10539 if (token.type != ';') {
10540 return_value = parse_expression();
10541 mark_vars_read(return_value, NULL);
10544 const type_t *const func_type = skip_typeref(current_function->base.type);
10545 assert(is_type_function(func_type));
10546 type_t *const return_type = skip_typeref(func_type->function.return_type);
10548 source_position_t const *const pos = &statement->base.source_position;
10549 if (return_value != NULL) {
10550 type_t *return_value_type = skip_typeref(return_value->base.type);
10552 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10553 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10554 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10555 /* Only warn in C mode, because GCC does the same */
10556 if (c_mode & _CXX || strict_mode) {
10558 "'return' with a value, in function returning 'void'");
10559 } else if (warning.other) {
10561 "'return' with a value, in function returning 'void'");
10563 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10564 /* Only warn in C mode, because GCC does the same */
10567 "'return' with expression in function return 'void'");
10568 } else if (warning.other) {
10570 "'return' with expression in function return 'void'");
10574 assign_error_t error = semantic_assign(return_type, return_value);
10575 report_assign_error(error, return_type, return_value, "'return'",
10578 return_value = create_implicit_cast(return_value, return_type);
10579 /* check for returning address of a local var */
10580 if (warning.other && return_value != NULL
10581 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10582 const expression_t *expression = return_value->unary.value;
10583 if (expression_is_local_variable(expression)) {
10584 warningf(pos, "function returns address of local variable");
10587 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10588 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10589 if (c_mode & _CXX || strict_mode) {
10591 "'return' without value, in function returning non-void");
10594 "'return' without value, in function returning non-void");
10597 statement->returns.value = return_value;
10599 expect(';', end_error);
10606 * Parse a declaration statement.
10608 static statement_t *parse_declaration_statement(void)
10610 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10612 entity_t *before = current_scope->last_entity;
10614 parse_external_declaration();
10616 parse_declaration(record_entity, DECL_FLAGS_NONE);
10619 declaration_statement_t *const decl = &statement->declaration;
10620 entity_t *const begin =
10621 before != NULL ? before->base.next : current_scope->entities;
10622 decl->declarations_begin = begin;
10623 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10629 * Parse an expression statement, ie. expr ';'.
10631 static statement_t *parse_expression_statement(void)
10633 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10635 expression_t *const expr = parse_expression();
10636 statement->expression.expression = expr;
10637 mark_vars_read(expr, ENT_ANY);
10639 expect(';', end_error);
10646 * Parse a microsoft __try { } __finally { } or
10647 * __try{ } __except() { }
10649 static statement_t *parse_ms_try_statment(void)
10651 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10654 PUSH_PARENT(statement);
10656 ms_try_statement_t *rem = current_try;
10657 current_try = &statement->ms_try;
10658 statement->ms_try.try_statement = parse_compound_statement(false);
10663 if (token.type == T___except) {
10665 expect('(', end_error);
10666 add_anchor_token(')');
10667 expression_t *const expr = parse_expression();
10668 mark_vars_read(expr, NULL);
10669 type_t * type = skip_typeref(expr->base.type);
10670 if (is_type_integer(type)) {
10671 type = promote_integer(type);
10672 } else if (is_type_valid(type)) {
10673 errorf(&expr->base.source_position,
10674 "__expect expression is not an integer, but '%T'", type);
10675 type = type_error_type;
10677 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10678 rem_anchor_token(')');
10679 expect(')', end_error);
10680 statement->ms_try.final_statement = parse_compound_statement(false);
10681 } else if (token.type == T__finally) {
10683 statement->ms_try.final_statement = parse_compound_statement(false);
10685 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10686 return create_invalid_statement();
10690 return create_invalid_statement();
10693 static statement_t *parse_empty_statement(void)
10695 if (warning.empty_statement) {
10696 warningf(HERE, "statement is empty");
10698 statement_t *const statement = create_empty_statement();
10703 static statement_t *parse_local_label_declaration(void)
10705 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10709 entity_t *begin = NULL, *end = NULL;
10712 if (token.type != T_IDENTIFIER) {
10713 parse_error_expected("while parsing local label declaration",
10714 T_IDENTIFIER, NULL);
10717 symbol_t *symbol = token.v.symbol;
10718 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10719 if (entity != NULL && entity->base.parent_scope == current_scope) {
10720 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10721 symbol, &entity->base.source_position);
10723 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10725 entity->base.parent_scope = current_scope;
10726 entity->base.namespc = NAMESPACE_LABEL;
10727 entity->base.source_position = token.source_position;
10728 entity->base.symbol = symbol;
10731 end->base.next = entity;
10736 environment_push(entity);
10740 if (token.type != ',')
10746 statement->declaration.declarations_begin = begin;
10747 statement->declaration.declarations_end = end;
10751 static void parse_namespace_definition(void)
10755 entity_t *entity = NULL;
10756 symbol_t *symbol = NULL;
10758 if (token.type == T_IDENTIFIER) {
10759 symbol = token.v.symbol;
10762 entity = get_entity(symbol, NAMESPACE_NORMAL);
10763 if (entity != NULL &&
10764 entity->kind != ENTITY_NAMESPACE &&
10765 entity->base.parent_scope == current_scope) {
10766 if (!is_error_entity(entity)) {
10767 error_redefined_as_different_kind(&token.source_position,
10768 entity, ENTITY_NAMESPACE);
10774 if (entity == NULL) {
10775 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10776 entity->base.symbol = symbol;
10777 entity->base.source_position = token.source_position;
10778 entity->base.namespc = NAMESPACE_NORMAL;
10779 entity->base.parent_scope = current_scope;
10782 if (token.type == '=') {
10783 /* TODO: parse namespace alias */
10784 panic("namespace alias definition not supported yet");
10787 environment_push(entity);
10788 append_entity(current_scope, entity);
10790 size_t const top = environment_top();
10791 scope_t *old_scope = scope_push(&entity->namespacee.members);
10793 expect('{', end_error);
10795 expect('}', end_error);
10798 assert(current_scope == &entity->namespacee.members);
10799 scope_pop(old_scope);
10800 environment_pop_to(top);
10804 * Parse a statement.
10805 * There's also parse_statement() which additionally checks for
10806 * "statement has no effect" warnings
10808 static statement_t *intern_parse_statement(void)
10810 statement_t *statement = NULL;
10812 /* declaration or statement */
10813 add_anchor_token(';');
10814 switch (token.type) {
10815 case T_IDENTIFIER: {
10816 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10817 if (la1_type == ':') {
10818 statement = parse_label_statement();
10819 } else if (is_typedef_symbol(token.v.symbol)) {
10820 statement = parse_declaration_statement();
10822 /* it's an identifier, the grammar says this must be an
10823 * expression statement. However it is common that users mistype
10824 * declaration types, so we guess a bit here to improve robustness
10825 * for incorrect programs */
10826 switch (la1_type) {
10829 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10830 goto expression_statment;
10835 statement = parse_declaration_statement();
10839 expression_statment:
10840 statement = parse_expression_statement();
10847 case T___extension__:
10848 /* This can be a prefix to a declaration or an expression statement.
10849 * We simply eat it now and parse the rest with tail recursion. */
10852 } while (token.type == T___extension__);
10853 bool old_gcc_extension = in_gcc_extension;
10854 in_gcc_extension = true;
10855 statement = intern_parse_statement();
10856 in_gcc_extension = old_gcc_extension;
10860 statement = parse_declaration_statement();
10864 statement = parse_local_label_declaration();
10867 case ';': statement = parse_empty_statement(); break;
10868 case '{': statement = parse_compound_statement(false); break;
10869 case T___leave: statement = parse_leave_statement(); break;
10870 case T___try: statement = parse_ms_try_statment(); break;
10871 case T_asm: statement = parse_asm_statement(); break;
10872 case T_break: statement = parse_break(); break;
10873 case T_case: statement = parse_case_statement(); break;
10874 case T_continue: statement = parse_continue(); break;
10875 case T_default: statement = parse_default_statement(); break;
10876 case T_do: statement = parse_do(); break;
10877 case T_for: statement = parse_for(); break;
10878 case T_goto: statement = parse_goto(); break;
10879 case T_if: statement = parse_if(); break;
10880 case T_return: statement = parse_return(); break;
10881 case T_switch: statement = parse_switch(); break;
10882 case T_while: statement = parse_while(); break;
10885 statement = parse_expression_statement();
10889 errorf(HERE, "unexpected token %K while parsing statement", &token);
10890 statement = create_invalid_statement();
10895 rem_anchor_token(';');
10897 assert(statement != NULL
10898 && statement->base.source_position.input_name != NULL);
10904 * parse a statement and emits "statement has no effect" warning if needed
10905 * (This is really a wrapper around intern_parse_statement with check for 1
10906 * single warning. It is needed, because for statement expressions we have
10907 * to avoid the warning on the last statement)
10909 static statement_t *parse_statement(void)
10911 statement_t *statement = intern_parse_statement();
10913 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10914 expression_t *expression = statement->expression.expression;
10915 if (!expression_has_effect(expression)) {
10916 warningf(&expression->base.source_position,
10917 "statement has no effect");
10925 * Parse a compound statement.
10927 static statement_t *parse_compound_statement(bool inside_expression_statement)
10929 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10931 PUSH_PARENT(statement);
10934 add_anchor_token('}');
10935 /* tokens, which can start a statement */
10936 /* TODO MS, __builtin_FOO */
10937 add_anchor_token('!');
10938 add_anchor_token('&');
10939 add_anchor_token('(');
10940 add_anchor_token('*');
10941 add_anchor_token('+');
10942 add_anchor_token('-');
10943 add_anchor_token('{');
10944 add_anchor_token('~');
10945 add_anchor_token(T_CHARACTER_CONSTANT);
10946 add_anchor_token(T_COLONCOLON);
10947 add_anchor_token(T_FLOATINGPOINT);
10948 add_anchor_token(T_IDENTIFIER);
10949 add_anchor_token(T_INTEGER);
10950 add_anchor_token(T_MINUSMINUS);
10951 add_anchor_token(T_PLUSPLUS);
10952 add_anchor_token(T_STRING_LITERAL);
10953 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10954 add_anchor_token(T_WIDE_STRING_LITERAL);
10955 add_anchor_token(T__Bool);
10956 add_anchor_token(T__Complex);
10957 add_anchor_token(T__Imaginary);
10958 add_anchor_token(T___FUNCTION__);
10959 add_anchor_token(T___PRETTY_FUNCTION__);
10960 add_anchor_token(T___alignof__);
10961 add_anchor_token(T___attribute__);
10962 add_anchor_token(T___builtin_va_start);
10963 add_anchor_token(T___extension__);
10964 add_anchor_token(T___func__);
10965 add_anchor_token(T___imag__);
10966 add_anchor_token(T___label__);
10967 add_anchor_token(T___real__);
10968 add_anchor_token(T___thread);
10969 add_anchor_token(T_asm);
10970 add_anchor_token(T_auto);
10971 add_anchor_token(T_bool);
10972 add_anchor_token(T_break);
10973 add_anchor_token(T_case);
10974 add_anchor_token(T_char);
10975 add_anchor_token(T_class);
10976 add_anchor_token(T_const);
10977 add_anchor_token(T_const_cast);
10978 add_anchor_token(T_continue);
10979 add_anchor_token(T_default);
10980 add_anchor_token(T_delete);
10981 add_anchor_token(T_double);
10982 add_anchor_token(T_do);
10983 add_anchor_token(T_dynamic_cast);
10984 add_anchor_token(T_enum);
10985 add_anchor_token(T_extern);
10986 add_anchor_token(T_false);
10987 add_anchor_token(T_float);
10988 add_anchor_token(T_for);
10989 add_anchor_token(T_goto);
10990 add_anchor_token(T_if);
10991 add_anchor_token(T_inline);
10992 add_anchor_token(T_int);
10993 add_anchor_token(T_long);
10994 add_anchor_token(T_new);
10995 add_anchor_token(T_operator);
10996 add_anchor_token(T_register);
10997 add_anchor_token(T_reinterpret_cast);
10998 add_anchor_token(T_restrict);
10999 add_anchor_token(T_return);
11000 add_anchor_token(T_short);
11001 add_anchor_token(T_signed);
11002 add_anchor_token(T_sizeof);
11003 add_anchor_token(T_static);
11004 add_anchor_token(T_static_cast);
11005 add_anchor_token(T_struct);
11006 add_anchor_token(T_switch);
11007 add_anchor_token(T_template);
11008 add_anchor_token(T_this);
11009 add_anchor_token(T_throw);
11010 add_anchor_token(T_true);
11011 add_anchor_token(T_try);
11012 add_anchor_token(T_typedef);
11013 add_anchor_token(T_typeid);
11014 add_anchor_token(T_typename);
11015 add_anchor_token(T_typeof);
11016 add_anchor_token(T_union);
11017 add_anchor_token(T_unsigned);
11018 add_anchor_token(T_using);
11019 add_anchor_token(T_void);
11020 add_anchor_token(T_volatile);
11021 add_anchor_token(T_wchar_t);
11022 add_anchor_token(T_while);
11024 size_t const top = environment_top();
11025 scope_t *old_scope = scope_push(&statement->compound.scope);
11027 statement_t **anchor = &statement->compound.statements;
11028 bool only_decls_so_far = true;
11029 while (token.type != '}') {
11030 if (token.type == T_EOF) {
11031 errorf(&statement->base.source_position,
11032 "EOF while parsing compound statement");
11035 statement_t *sub_statement = intern_parse_statement();
11036 if (is_invalid_statement(sub_statement)) {
11037 /* an error occurred. if we are at an anchor, return */
11043 if (warning.declaration_after_statement) {
11044 if (sub_statement->kind != STATEMENT_DECLARATION) {
11045 only_decls_so_far = false;
11046 } else if (!only_decls_so_far) {
11047 warningf(&sub_statement->base.source_position,
11048 "ISO C90 forbids mixed declarations and code");
11052 *anchor = sub_statement;
11054 while (sub_statement->base.next != NULL)
11055 sub_statement = sub_statement->base.next;
11057 anchor = &sub_statement->base.next;
11061 /* look over all statements again to produce no effect warnings */
11062 if (warning.unused_value) {
11063 statement_t *sub_statement = statement->compound.statements;
11064 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11065 if (sub_statement->kind != STATEMENT_EXPRESSION)
11067 /* don't emit a warning for the last expression in an expression
11068 * statement as it has always an effect */
11069 if (inside_expression_statement && sub_statement->base.next == NULL)
11072 expression_t *expression = sub_statement->expression.expression;
11073 if (!expression_has_effect(expression)) {
11074 warningf(&expression->base.source_position,
11075 "statement has no effect");
11081 rem_anchor_token(T_while);
11082 rem_anchor_token(T_wchar_t);
11083 rem_anchor_token(T_volatile);
11084 rem_anchor_token(T_void);
11085 rem_anchor_token(T_using);
11086 rem_anchor_token(T_unsigned);
11087 rem_anchor_token(T_union);
11088 rem_anchor_token(T_typeof);
11089 rem_anchor_token(T_typename);
11090 rem_anchor_token(T_typeid);
11091 rem_anchor_token(T_typedef);
11092 rem_anchor_token(T_try);
11093 rem_anchor_token(T_true);
11094 rem_anchor_token(T_throw);
11095 rem_anchor_token(T_this);
11096 rem_anchor_token(T_template);
11097 rem_anchor_token(T_switch);
11098 rem_anchor_token(T_struct);
11099 rem_anchor_token(T_static_cast);
11100 rem_anchor_token(T_static);
11101 rem_anchor_token(T_sizeof);
11102 rem_anchor_token(T_signed);
11103 rem_anchor_token(T_short);
11104 rem_anchor_token(T_return);
11105 rem_anchor_token(T_restrict);
11106 rem_anchor_token(T_reinterpret_cast);
11107 rem_anchor_token(T_register);
11108 rem_anchor_token(T_operator);
11109 rem_anchor_token(T_new);
11110 rem_anchor_token(T_long);
11111 rem_anchor_token(T_int);
11112 rem_anchor_token(T_inline);
11113 rem_anchor_token(T_if);
11114 rem_anchor_token(T_goto);
11115 rem_anchor_token(T_for);
11116 rem_anchor_token(T_float);
11117 rem_anchor_token(T_false);
11118 rem_anchor_token(T_extern);
11119 rem_anchor_token(T_enum);
11120 rem_anchor_token(T_dynamic_cast);
11121 rem_anchor_token(T_do);
11122 rem_anchor_token(T_double);
11123 rem_anchor_token(T_delete);
11124 rem_anchor_token(T_default);
11125 rem_anchor_token(T_continue);
11126 rem_anchor_token(T_const_cast);
11127 rem_anchor_token(T_const);
11128 rem_anchor_token(T_class);
11129 rem_anchor_token(T_char);
11130 rem_anchor_token(T_case);
11131 rem_anchor_token(T_break);
11132 rem_anchor_token(T_bool);
11133 rem_anchor_token(T_auto);
11134 rem_anchor_token(T_asm);
11135 rem_anchor_token(T___thread);
11136 rem_anchor_token(T___real__);
11137 rem_anchor_token(T___label__);
11138 rem_anchor_token(T___imag__);
11139 rem_anchor_token(T___func__);
11140 rem_anchor_token(T___extension__);
11141 rem_anchor_token(T___builtin_va_start);
11142 rem_anchor_token(T___attribute__);
11143 rem_anchor_token(T___alignof__);
11144 rem_anchor_token(T___PRETTY_FUNCTION__);
11145 rem_anchor_token(T___FUNCTION__);
11146 rem_anchor_token(T__Imaginary);
11147 rem_anchor_token(T__Complex);
11148 rem_anchor_token(T__Bool);
11149 rem_anchor_token(T_WIDE_STRING_LITERAL);
11150 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11151 rem_anchor_token(T_STRING_LITERAL);
11152 rem_anchor_token(T_PLUSPLUS);
11153 rem_anchor_token(T_MINUSMINUS);
11154 rem_anchor_token(T_INTEGER);
11155 rem_anchor_token(T_IDENTIFIER);
11156 rem_anchor_token(T_FLOATINGPOINT);
11157 rem_anchor_token(T_COLONCOLON);
11158 rem_anchor_token(T_CHARACTER_CONSTANT);
11159 rem_anchor_token('~');
11160 rem_anchor_token('{');
11161 rem_anchor_token('-');
11162 rem_anchor_token('+');
11163 rem_anchor_token('*');
11164 rem_anchor_token('(');
11165 rem_anchor_token('&');
11166 rem_anchor_token('!');
11167 rem_anchor_token('}');
11168 assert(current_scope == &statement->compound.scope);
11169 scope_pop(old_scope);
11170 environment_pop_to(top);
11177 * Check for unused global static functions and variables
11179 static void check_unused_globals(void)
11181 if (!warning.unused_function && !warning.unused_variable)
11184 for (const entity_t *entity = file_scope->entities; entity != NULL;
11185 entity = entity->base.next) {
11186 if (!is_declaration(entity))
11189 const declaration_t *declaration = &entity->declaration;
11190 if (declaration->used ||
11191 declaration->modifiers & DM_UNUSED ||
11192 declaration->modifiers & DM_USED ||
11193 declaration->storage_class != STORAGE_CLASS_STATIC)
11196 type_t *const type = declaration->type;
11198 if (entity->kind == ENTITY_FUNCTION) {
11199 /* inhibit warning for static inline functions */
11200 if (entity->function.is_inline)
11203 s = entity->function.statement != NULL ? "defined" : "declared";
11208 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11209 type, declaration->base.symbol, s);
11213 static void parse_global_asm(void)
11215 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11218 expect('(', end_error);
11220 statement->asms.asm_text = parse_string_literals();
11221 statement->base.next = unit->global_asm;
11222 unit->global_asm = statement;
11224 expect(')', end_error);
11225 expect(';', end_error);
11230 static void parse_linkage_specification(void)
11233 assert(token.type == T_STRING_LITERAL);
11235 const char *linkage = parse_string_literals().begin;
11237 linkage_kind_t old_linkage = current_linkage;
11238 linkage_kind_t new_linkage;
11239 if (strcmp(linkage, "C") == 0) {
11240 new_linkage = LINKAGE_C;
11241 } else if (strcmp(linkage, "C++") == 0) {
11242 new_linkage = LINKAGE_CXX;
11244 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11245 new_linkage = LINKAGE_INVALID;
11247 current_linkage = new_linkage;
11249 if (token.type == '{') {
11252 expect('}', end_error);
11258 assert(current_linkage == new_linkage);
11259 current_linkage = old_linkage;
11262 static void parse_external(void)
11264 switch (token.type) {
11265 DECLARATION_START_NO_EXTERN
11267 case T___extension__:
11268 /* tokens below are for implicit int */
11269 case '&': /* & x; -> int& x; (and error later, because C++ has no
11271 case '*': /* * x; -> int* x; */
11272 case '(': /* (x); -> int (x); */
11273 parse_external_declaration();
11277 if (look_ahead(1)->type == T_STRING_LITERAL) {
11278 parse_linkage_specification();
11280 parse_external_declaration();
11285 parse_global_asm();
11289 parse_namespace_definition();
11293 if (!strict_mode) {
11295 warningf(HERE, "stray ';' outside of function");
11302 errorf(HERE, "stray %K outside of function", &token);
11303 if (token.type == '(' || token.type == '{' || token.type == '[')
11304 eat_until_matching_token(token.type);
11310 static void parse_externals(void)
11312 add_anchor_token('}');
11313 add_anchor_token(T_EOF);
11316 unsigned char token_anchor_copy[T_LAST_TOKEN];
11317 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11320 while (token.type != T_EOF && token.type != '}') {
11322 bool anchor_leak = false;
11323 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11324 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11326 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11327 anchor_leak = true;
11330 if (in_gcc_extension) {
11331 errorf(HERE, "Leaked __extension__");
11332 anchor_leak = true;
11342 rem_anchor_token(T_EOF);
11343 rem_anchor_token('}');
11347 * Parse a translation unit.
11349 static void parse_translation_unit(void)
11351 add_anchor_token(T_EOF);
11356 if (token.type == T_EOF)
11359 errorf(HERE, "stray %K outside of function", &token);
11360 if (token.type == '(' || token.type == '{' || token.type == '[')
11361 eat_until_matching_token(token.type);
11369 * @return the translation unit or NULL if errors occurred.
11371 void start_parsing(void)
11373 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11374 label_stack = NEW_ARR_F(stack_entry_t, 0);
11375 diagnostic_count = 0;
11379 type_set_output(stderr);
11380 ast_set_output(stderr);
11382 assert(unit == NULL);
11383 unit = allocate_ast_zero(sizeof(unit[0]));
11385 assert(file_scope == NULL);
11386 file_scope = &unit->scope;
11388 assert(current_scope == NULL);
11389 scope_push(&unit->scope);
11392 translation_unit_t *finish_parsing(void)
11394 assert(current_scope == &unit->scope);
11397 assert(file_scope == &unit->scope);
11398 check_unused_globals();
11401 DEL_ARR_F(environment_stack);
11402 DEL_ARR_F(label_stack);
11404 translation_unit_t *result = unit;
11409 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
11410 * are given length one. */
11411 static void complete_incomplete_arrays(void)
11413 size_t n = ARR_LEN(incomplete_arrays);
11414 for (size_t i = 0; i != n; ++i) {
11415 declaration_t *const decl = incomplete_arrays[i];
11416 type_t *const orig_type = decl->type;
11417 type_t *const type = skip_typeref(orig_type);
11419 if (!is_type_incomplete(type))
11422 if (warning.other) {
11423 warningf(&decl->base.source_position,
11424 "array '%#T' assumed to have one element",
11425 orig_type, decl->base.symbol);
11428 type_t *const new_type = duplicate_type(type);
11429 new_type->array.size_constant = true;
11430 new_type->array.has_implicit_size = true;
11431 new_type->array.size = 1;
11433 type_t *const result = identify_new_type(new_type);
11435 decl->type = result;
11441 lookahead_bufpos = 0;
11442 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11445 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11446 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11447 parse_translation_unit();
11448 complete_incomplete_arrays();
11449 DEL_ARR_F(incomplete_arrays);
11450 incomplete_arrays = NULL;
11454 * Initialize the parser.
11456 void init_parser(void)
11458 sym_anonymous = symbol_table_insert("<anonymous>");
11460 if (c_mode & _MS) {
11461 /* add predefined symbols for extended-decl-modifier */
11462 sym_align = symbol_table_insert("align");
11463 sym_allocate = symbol_table_insert("allocate");
11464 sym_dllimport = symbol_table_insert("dllimport");
11465 sym_dllexport = symbol_table_insert("dllexport");
11466 sym_naked = symbol_table_insert("naked");
11467 sym_noinline = symbol_table_insert("noinline");
11468 sym_returns_twice = symbol_table_insert("returns_twice");
11469 sym_noreturn = symbol_table_insert("noreturn");
11470 sym_nothrow = symbol_table_insert("nothrow");
11471 sym_novtable = symbol_table_insert("novtable");
11472 sym_property = symbol_table_insert("property");
11473 sym_get = symbol_table_insert("get");
11474 sym_put = symbol_table_insert("put");
11475 sym_selectany = symbol_table_insert("selectany");
11476 sym_thread = symbol_table_insert("thread");
11477 sym_uuid = symbol_table_insert("uuid");
11478 sym_deprecated = symbol_table_insert("deprecated");
11479 sym_restrict = symbol_table_insert("restrict");
11480 sym_noalias = symbol_table_insert("noalias");
11482 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11484 init_expression_parsers();
11485 obstack_init(&temp_obst);
11487 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11488 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11492 * Terminate the parser.
11494 void exit_parser(void)
11496 obstack_free(&temp_obst, NULL);