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_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_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_TYPES_COMPATIBLE_P:
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 = revert_automatic_type_conversion(expression);
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 if (parameter->kind != ENTITY_PARAMETER)
5538 type_t *parameter_type = parameter->declaration.type;
5539 if (parameter_type == NULL) {
5541 errorf(HERE, "no type specified for function parameter '%Y'",
5542 parameter->base.symbol);
5544 if (warning.implicit_int) {
5545 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5546 parameter->base.symbol);
5548 parameter_type = type_int;
5549 parameter->declaration.type = parameter_type;
5553 semantic_parameter_incomplete(parameter);
5554 parameter_type = parameter->declaration.type;
5557 * we need the default promoted types for the function type
5559 parameter_type = get_default_promoted_type(parameter_type);
5561 function_parameter_t *function_parameter
5562 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5563 memset(function_parameter, 0, sizeof(function_parameter[0]));
5565 function_parameter->type = parameter_type;
5566 if (last_parameter != NULL) {
5567 last_parameter->next = function_parameter;
5569 parameters = function_parameter;
5571 last_parameter = function_parameter;
5574 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5576 new_type->function.parameters = parameters;
5577 new_type->function.unspecified_parameters = true;
5579 new_type = identify_new_type(new_type);
5581 entity->declaration.type = new_type;
5583 rem_anchor_token('{');
5586 static bool first_err = true;
5589 * When called with first_err set, prints the name of the current function,
5592 static void print_in_function(void)
5596 diagnosticf("%s: In function '%Y':\n",
5597 current_function->base.base.source_position.input_name,
5598 current_function->base.base.symbol);
5603 * Check if all labels are defined in the current function.
5604 * Check if all labels are used in the current function.
5606 static void check_labels(void)
5608 for (const goto_statement_t *goto_statement = goto_first;
5609 goto_statement != NULL;
5610 goto_statement = goto_statement->next) {
5611 /* skip computed gotos */
5612 if (goto_statement->expression != NULL)
5615 label_t *label = goto_statement->label;
5618 if (label->base.source_position.input_name == NULL) {
5619 print_in_function();
5620 errorf(&goto_statement->base.source_position,
5621 "label '%Y' used but not defined", label->base.symbol);
5625 if (warning.unused_label) {
5626 for (const label_statement_t *label_statement = label_first;
5627 label_statement != NULL;
5628 label_statement = label_statement->next) {
5629 label_t *label = label_statement->label;
5631 if (! label->used) {
5632 print_in_function();
5633 warningf(&label_statement->base.source_position,
5634 "label '%Y' defined but not used", label->base.symbol);
5640 static void warn_unused_entity(entity_t *entity, entity_t *last)
5642 entity_t const *const end = last != NULL ? last->base.next : NULL;
5643 for (; entity != end; entity = entity->base.next) {
5644 if (!is_declaration(entity))
5647 declaration_t *declaration = &entity->declaration;
5648 if (declaration->implicit)
5651 if (!declaration->used) {
5652 print_in_function();
5653 const char *what = get_entity_kind_name(entity->kind);
5654 warningf(&entity->base.source_position, "%s '%Y' is unused",
5655 what, entity->base.symbol);
5656 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5657 print_in_function();
5658 const char *what = get_entity_kind_name(entity->kind);
5659 warningf(&entity->base.source_position, "%s '%Y' is never read",
5660 what, entity->base.symbol);
5665 static void check_unused_variables(statement_t *const stmt, void *const env)
5669 switch (stmt->kind) {
5670 case STATEMENT_DECLARATION: {
5671 declaration_statement_t const *const decls = &stmt->declaration;
5672 warn_unused_entity(decls->declarations_begin,
5673 decls->declarations_end);
5678 warn_unused_entity(stmt->fors.scope.entities, NULL);
5687 * Check declarations of current_function for unused entities.
5689 static void check_declarations(void)
5691 if (warning.unused_parameter) {
5692 const scope_t *scope = ¤t_function->parameters;
5694 /* do not issue unused warnings for main */
5695 if (!is_sym_main(current_function->base.base.symbol)) {
5696 warn_unused_entity(scope->entities, NULL);
5699 if (warning.unused_variable) {
5700 walk_statements(current_function->statement, check_unused_variables,
5705 static int determine_truth(expression_t const* const cond)
5708 !is_constant_expression(cond) ? 0 :
5709 fold_constant(cond) != 0 ? 1 :
5713 static void check_reachable(statement_t *);
5714 static bool reaches_end;
5716 static bool expression_returns(expression_t const *const expr)
5718 switch (expr->kind) {
5720 expression_t const *const func = expr->call.function;
5721 if (func->kind == EXPR_REFERENCE) {
5722 entity_t *entity = func->reference.entity;
5723 if (entity->kind == ENTITY_FUNCTION
5724 && entity->declaration.modifiers & DM_NORETURN)
5728 if (!expression_returns(func))
5731 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5732 if (!expression_returns(arg->expression))
5739 case EXPR_REFERENCE:
5740 case EXPR_REFERENCE_ENUM_VALUE:
5742 case EXPR_CHARACTER_CONSTANT:
5743 case EXPR_WIDE_CHARACTER_CONSTANT:
5744 case EXPR_STRING_LITERAL:
5745 case EXPR_WIDE_STRING_LITERAL:
5746 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5747 case EXPR_LABEL_ADDRESS:
5748 case EXPR_CLASSIFY_TYPE:
5749 case EXPR_SIZEOF: // TODO handle obscure VLA case
5752 case EXPR_BUILTIN_SYMBOL:
5753 case EXPR_BUILTIN_CONSTANT_P:
5754 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5755 case EXPR_BUILTIN_PREFETCH:
5760 case EXPR_STATEMENT: {
5761 bool old_reaches_end = reaches_end;
5762 reaches_end = false;
5763 check_reachable(expr->statement.statement);
5764 bool returns = reaches_end;
5765 reaches_end = old_reaches_end;
5769 case EXPR_CONDITIONAL:
5770 // TODO handle constant expression
5772 if (!expression_returns(expr->conditional.condition))
5775 if (expr->conditional.true_expression != NULL
5776 && expression_returns(expr->conditional.true_expression))
5779 return expression_returns(expr->conditional.false_expression);
5782 return expression_returns(expr->select.compound);
5784 case EXPR_ARRAY_ACCESS:
5786 expression_returns(expr->array_access.array_ref) &&
5787 expression_returns(expr->array_access.index);
5790 return expression_returns(expr->va_starte.ap);
5793 return expression_returns(expr->va_arge.ap);
5795 EXPR_UNARY_CASES_MANDATORY
5796 return expression_returns(expr->unary.value);
5798 case EXPR_UNARY_THROW:
5802 // TODO handle constant lhs of && and ||
5804 expression_returns(expr->binary.left) &&
5805 expression_returns(expr->binary.right);
5811 panic("unhandled expression");
5814 static bool initializer_returns(initializer_t const *const init)
5816 switch (init->kind) {
5817 case INITIALIZER_VALUE:
5818 return expression_returns(init->value.value);
5820 case INITIALIZER_LIST: {
5821 initializer_t * const* i = init->list.initializers;
5822 initializer_t * const* const end = i + init->list.len;
5823 bool returns = true;
5824 for (; i != end; ++i) {
5825 if (!initializer_returns(*i))
5831 case INITIALIZER_STRING:
5832 case INITIALIZER_WIDE_STRING:
5833 case INITIALIZER_DESIGNATOR: // designators have no payload
5836 panic("unhandled initializer");
5839 static bool noreturn_candidate;
5841 static void check_reachable(statement_t *const stmt)
5843 if (stmt->base.reachable)
5845 if (stmt->kind != STATEMENT_DO_WHILE)
5846 stmt->base.reachable = true;
5848 statement_t *last = stmt;
5850 switch (stmt->kind) {
5851 case STATEMENT_INVALID:
5852 case STATEMENT_EMPTY:
5854 next = stmt->base.next;
5857 case STATEMENT_DECLARATION: {
5858 declaration_statement_t const *const decl = &stmt->declaration;
5859 entity_t const * ent = decl->declarations_begin;
5860 entity_t const *const last = decl->declarations_end;
5862 for (;; ent = ent->base.next) {
5863 if (ent->kind == ENTITY_VARIABLE &&
5864 ent->variable.initializer != NULL &&
5865 !initializer_returns(ent->variable.initializer)) {
5872 next = stmt->base.next;
5876 case STATEMENT_COMPOUND:
5877 next = stmt->compound.statements;
5879 next = stmt->base.next;
5882 case STATEMENT_RETURN: {
5883 expression_t const *const val = stmt->returns.value;
5884 if (val == NULL || expression_returns(val))
5885 noreturn_candidate = false;
5889 case STATEMENT_IF: {
5890 if_statement_t const *const ifs = &stmt->ifs;
5891 expression_t const *const cond = ifs->condition;
5893 if (!expression_returns(cond))
5896 int const val = determine_truth(cond);
5899 check_reachable(ifs->true_statement);
5904 if (ifs->false_statement != NULL) {
5905 check_reachable(ifs->false_statement);
5909 next = stmt->base.next;
5913 case STATEMENT_SWITCH: {
5914 switch_statement_t const *const switchs = &stmt->switchs;
5915 expression_t const *const expr = switchs->expression;
5917 if (!expression_returns(expr))
5920 if (is_constant_expression(expr)) {
5921 long const val = fold_constant(expr);
5922 case_label_statement_t * defaults = NULL;
5923 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5924 if (i->expression == NULL) {
5929 if (i->first_case <= val && val <= i->last_case) {
5930 check_reachable((statement_t*)i);
5935 if (defaults != NULL) {
5936 check_reachable((statement_t*)defaults);
5940 bool has_default = false;
5941 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5942 if (i->expression == NULL)
5945 check_reachable((statement_t*)i);
5952 next = stmt->base.next;
5956 case STATEMENT_EXPRESSION: {
5957 /* Check for noreturn function call */
5958 expression_t const *const expr = stmt->expression.expression;
5959 if (!expression_returns(expr))
5962 next = stmt->base.next;
5966 case STATEMENT_CONTINUE: {
5967 statement_t *parent = stmt;
5969 parent = parent->base.parent;
5970 if (parent == NULL) /* continue not within loop */
5974 switch (parent->kind) {
5975 case STATEMENT_WHILE: goto continue_while;
5976 case STATEMENT_DO_WHILE: goto continue_do_while;
5977 case STATEMENT_FOR: goto continue_for;
5984 case STATEMENT_BREAK: {
5985 statement_t *parent = stmt;
5987 parent = parent->base.parent;
5988 if (parent == NULL) /* break not within loop/switch */
5991 switch (parent->kind) {
5992 case STATEMENT_SWITCH:
5993 case STATEMENT_WHILE:
5994 case STATEMENT_DO_WHILE:
5997 next = parent->base.next;
5998 goto found_break_parent;
6007 case STATEMENT_GOTO:
6008 if (stmt->gotos.expression) {
6009 if (!expression_returns(stmt->gotos.expression))
6012 statement_t *parent = stmt->base.parent;
6013 if (parent == NULL) /* top level goto */
6017 next = stmt->gotos.label->statement;
6018 if (next == NULL) /* missing label */
6023 case STATEMENT_LABEL:
6024 next = stmt->label.statement;
6027 case STATEMENT_CASE_LABEL:
6028 next = stmt->case_label.statement;
6031 case STATEMENT_WHILE: {
6032 while_statement_t const *const whiles = &stmt->whiles;
6033 expression_t const *const cond = whiles->condition;
6035 if (!expression_returns(cond))
6038 int const val = determine_truth(cond);
6041 check_reachable(whiles->body);
6046 next = stmt->base.next;
6050 case STATEMENT_DO_WHILE:
6051 next = stmt->do_while.body;
6054 case STATEMENT_FOR: {
6055 for_statement_t *const fors = &stmt->fors;
6057 if (fors->condition_reachable)
6059 fors->condition_reachable = true;
6061 expression_t const *const cond = fors->condition;
6066 } else if (expression_returns(cond)) {
6067 val = determine_truth(cond);
6073 check_reachable(fors->body);
6078 next = stmt->base.next;
6082 case STATEMENT_MS_TRY: {
6083 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6084 check_reachable(ms_try->try_statement);
6085 next = ms_try->final_statement;
6089 case STATEMENT_LEAVE: {
6090 statement_t *parent = stmt;
6092 parent = parent->base.parent;
6093 if (parent == NULL) /* __leave not within __try */
6096 if (parent->kind == STATEMENT_MS_TRY) {
6098 next = parent->ms_try.final_statement;
6106 panic("invalid statement kind");
6109 while (next == NULL) {
6110 next = last->base.parent;
6112 noreturn_candidate = false;
6114 type_t *const type = skip_typeref(current_function->base.type);
6115 assert(is_type_function(type));
6116 type_t *const ret = skip_typeref(type->function.return_type);
6117 if (warning.return_type &&
6118 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6119 is_type_valid(ret) &&
6120 !is_sym_main(current_function->base.base.symbol)) {
6121 warningf(&stmt->base.source_position,
6122 "control reaches end of non-void function");
6127 switch (next->kind) {
6128 case STATEMENT_INVALID:
6129 case STATEMENT_EMPTY:
6130 case STATEMENT_DECLARATION:
6131 case STATEMENT_EXPRESSION:
6133 case STATEMENT_RETURN:
6134 case STATEMENT_CONTINUE:
6135 case STATEMENT_BREAK:
6136 case STATEMENT_GOTO:
6137 case STATEMENT_LEAVE:
6138 panic("invalid control flow in function");
6140 case STATEMENT_COMPOUND:
6141 if (next->compound.stmt_expr) {
6147 case STATEMENT_SWITCH:
6148 case STATEMENT_LABEL:
6149 case STATEMENT_CASE_LABEL:
6151 next = next->base.next;
6154 case STATEMENT_WHILE: {
6156 if (next->base.reachable)
6158 next->base.reachable = true;
6160 while_statement_t const *const whiles = &next->whiles;
6161 expression_t const *const cond = whiles->condition;
6163 if (!expression_returns(cond))
6166 int const val = determine_truth(cond);
6169 check_reachable(whiles->body);
6175 next = next->base.next;
6179 case STATEMENT_DO_WHILE: {
6181 if (next->base.reachable)
6183 next->base.reachable = true;
6185 do_while_statement_t const *const dw = &next->do_while;
6186 expression_t const *const cond = dw->condition;
6188 if (!expression_returns(cond))
6191 int const val = determine_truth(cond);
6194 check_reachable(dw->body);
6200 next = next->base.next;
6204 case STATEMENT_FOR: {
6206 for_statement_t *const fors = &next->fors;
6208 fors->step_reachable = true;
6210 if (fors->condition_reachable)
6212 fors->condition_reachable = true;
6214 expression_t const *const cond = fors->condition;
6219 } else if (expression_returns(cond)) {
6220 val = determine_truth(cond);
6226 check_reachable(fors->body);
6232 next = next->base.next;
6236 case STATEMENT_MS_TRY:
6238 next = next->ms_try.final_statement;
6243 check_reachable(next);
6246 static void check_unreachable(statement_t* const stmt, void *const env)
6250 switch (stmt->kind) {
6251 case STATEMENT_DO_WHILE:
6252 if (!stmt->base.reachable) {
6253 expression_t const *const cond = stmt->do_while.condition;
6254 if (determine_truth(cond) >= 0) {
6255 warningf(&cond->base.source_position,
6256 "condition of do-while-loop is unreachable");
6261 case STATEMENT_FOR: {
6262 for_statement_t const* const fors = &stmt->fors;
6264 // if init and step are unreachable, cond is unreachable, too
6265 if (!stmt->base.reachable && !fors->step_reachable) {
6266 warningf(&stmt->base.source_position, "statement is unreachable");
6268 if (!stmt->base.reachable && fors->initialisation != NULL) {
6269 warningf(&fors->initialisation->base.source_position,
6270 "initialisation of for-statement is unreachable");
6273 if (!fors->condition_reachable && fors->condition != NULL) {
6274 warningf(&fors->condition->base.source_position,
6275 "condition of for-statement is unreachable");
6278 if (!fors->step_reachable && fors->step != NULL) {
6279 warningf(&fors->step->base.source_position,
6280 "step of for-statement is unreachable");
6286 case STATEMENT_COMPOUND:
6287 if (stmt->compound.statements != NULL)
6289 goto warn_unreachable;
6291 case STATEMENT_DECLARATION: {
6292 /* Only warn if there is at least one declarator with an initializer.
6293 * This typically occurs in switch statements. */
6294 declaration_statement_t const *const decl = &stmt->declaration;
6295 entity_t const * ent = decl->declarations_begin;
6296 entity_t const *const last = decl->declarations_end;
6298 for (;; ent = ent->base.next) {
6299 if (ent->kind == ENTITY_VARIABLE &&
6300 ent->variable.initializer != NULL) {
6301 goto warn_unreachable;
6311 if (!stmt->base.reachable)
6312 warningf(&stmt->base.source_position, "statement is unreachable");
6317 static void parse_external_declaration(void)
6319 /* function-definitions and declarations both start with declaration
6321 declaration_specifiers_t specifiers;
6322 memset(&specifiers, 0, sizeof(specifiers));
6324 add_anchor_token(';');
6325 parse_declaration_specifiers(&specifiers);
6326 rem_anchor_token(';');
6328 /* must be a declaration */
6329 if (token.type == ';') {
6330 parse_anonymous_declaration_rest(&specifiers);
6334 add_anchor_token(',');
6335 add_anchor_token('=');
6336 add_anchor_token(';');
6337 add_anchor_token('{');
6339 /* declarator is common to both function-definitions and declarations */
6340 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6342 rem_anchor_token('{');
6343 rem_anchor_token(';');
6344 rem_anchor_token('=');
6345 rem_anchor_token(',');
6347 /* must be a declaration */
6348 switch (token.type) {
6352 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6357 /* must be a function definition */
6358 parse_kr_declaration_list(ndeclaration);
6360 if (token.type != '{') {
6361 parse_error_expected("while parsing function definition", '{', NULL);
6362 eat_until_matching_token(';');
6366 assert(is_declaration(ndeclaration));
6367 type_t *const orig_type = ndeclaration->declaration.type;
6368 type_t * type = skip_typeref(orig_type);
6370 if (!is_type_function(type)) {
6371 if (is_type_valid(type)) {
6372 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6373 type, ndeclaration->base.symbol);
6377 } else if (is_typeref(orig_type)) {
6379 errorf(&ndeclaration->base.source_position,
6380 "type of function definition '%#T' is a typedef",
6381 orig_type, ndeclaration->base.symbol);
6384 if (warning.aggregate_return &&
6385 is_type_compound(skip_typeref(type->function.return_type))) {
6386 warningf(HERE, "function '%Y' returns an aggregate",
6387 ndeclaration->base.symbol);
6389 if (warning.traditional && !type->function.unspecified_parameters) {
6390 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6391 ndeclaration->base.symbol);
6393 if (warning.old_style_definition && type->function.unspecified_parameters) {
6394 warningf(HERE, "old-style function definition '%Y'",
6395 ndeclaration->base.symbol);
6398 /* § 6.7.5.3:14 a function definition with () means no
6399 * parameters (and not unspecified parameters) */
6400 if (type->function.unspecified_parameters &&
6401 type->function.parameters == NULL &&
6402 !type->function.kr_style_parameters) {
6403 type_t *copy = duplicate_type(type);
6404 copy->function.unspecified_parameters = false;
6405 type = identify_new_type(copy);
6407 ndeclaration->declaration.type = type;
6410 entity_t *const entity = record_entity(ndeclaration, true);
6411 assert(entity->kind == ENTITY_FUNCTION);
6412 assert(ndeclaration->kind == ENTITY_FUNCTION);
6414 function_t *function = &entity->function;
6415 if (ndeclaration != entity) {
6416 function->parameters = ndeclaration->function.parameters;
6418 assert(is_declaration(entity));
6419 type = skip_typeref(entity->declaration.type);
6421 /* push function parameters and switch scope */
6422 size_t const top = environment_top();
6423 scope_t *old_scope = scope_push(&function->parameters);
6425 entity_t *parameter = function->parameters.entities;
6426 for (; parameter != NULL; parameter = parameter->base.next) {
6427 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6428 parameter->base.parent_scope = current_scope;
6430 assert(parameter->base.parent_scope == NULL
6431 || parameter->base.parent_scope == current_scope);
6432 parameter->base.parent_scope = current_scope;
6433 if (parameter->base.symbol == NULL) {
6434 errorf(¶meter->base.source_position, "parameter name omitted");
6437 environment_push(parameter);
6440 if (function->statement != NULL) {
6441 parser_error_multiple_definition(entity, HERE);
6444 /* parse function body */
6445 int label_stack_top = label_top();
6446 function_t *old_current_function = current_function;
6447 current_function = function;
6448 current_parent = NULL;
6451 goto_anchor = &goto_first;
6453 label_anchor = &label_first;
6455 statement_t *const body = parse_compound_statement(false);
6456 function->statement = body;
6459 check_declarations();
6460 if (warning.return_type ||
6461 warning.unreachable_code ||
6462 (warning.missing_noreturn
6463 && !(function->base.modifiers & DM_NORETURN))) {
6464 noreturn_candidate = true;
6465 check_reachable(body);
6466 if (warning.unreachable_code)
6467 walk_statements(body, check_unreachable, NULL);
6468 if (warning.missing_noreturn &&
6469 noreturn_candidate &&
6470 !(function->base.modifiers & DM_NORETURN)) {
6471 warningf(&body->base.source_position,
6472 "function '%#T' is candidate for attribute 'noreturn'",
6473 type, entity->base.symbol);
6477 assert(current_parent == NULL);
6478 assert(current_function == function);
6479 current_function = old_current_function;
6480 label_pop_to(label_stack_top);
6483 assert(current_scope == &function->parameters);
6484 scope_pop(old_scope);
6485 environment_pop_to(top);
6488 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6489 source_position_t *source_position,
6490 const symbol_t *symbol)
6492 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6494 type->bitfield.base_type = base_type;
6495 type->bitfield.size_expression = size;
6498 type_t *skipped_type = skip_typeref(base_type);
6499 if (!is_type_integer(skipped_type)) {
6500 errorf(HERE, "bitfield base type '%T' is not an integer type",
6504 bit_size = skipped_type->base.size * 8;
6507 if (is_constant_expression(size)) {
6508 long v = fold_constant(size);
6511 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6512 } else if (v == 0) {
6513 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6514 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6515 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6517 type->bitfield.bit_size = v;
6524 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6526 entity_t *iter = compound->members.entities;
6527 for (; iter != NULL; iter = iter->base.next) {
6528 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6531 if (iter->base.symbol == symbol) {
6533 } else if (iter->base.symbol == NULL) {
6534 type_t *type = skip_typeref(iter->declaration.type);
6535 if (is_type_compound(type)) {
6537 = find_compound_entry(type->compound.compound, symbol);
6548 static void parse_compound_declarators(compound_t *compound,
6549 const declaration_specifiers_t *specifiers)
6554 if (token.type == ':') {
6555 source_position_t source_position = *HERE;
6558 type_t *base_type = specifiers->type;
6559 expression_t *size = parse_constant_expression();
6561 type_t *type = make_bitfield_type(base_type, size,
6562 &source_position, sym_anonymous);
6564 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6565 entity->base.namespc = NAMESPACE_NORMAL;
6566 entity->base.source_position = source_position;
6567 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6568 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6569 entity->declaration.modifiers = specifiers->modifiers;
6570 entity->declaration.type = type;
6571 append_entity(&compound->members, entity);
6573 entity = parse_declarator(specifiers,
6574 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6575 if (entity->kind == ENTITY_TYPEDEF) {
6576 errorf(&entity->base.source_position,
6577 "typedef not allowed as compound member");
6579 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6581 /* make sure we don't define a symbol multiple times */
6582 symbol_t *symbol = entity->base.symbol;
6583 if (symbol != NULL) {
6584 entity_t *prev = find_compound_entry(compound, symbol);
6586 errorf(&entity->base.source_position,
6587 "multiple declarations of symbol '%Y' (declared %P)",
6588 symbol, &prev->base.source_position);
6592 if (token.type == ':') {
6593 source_position_t source_position = *HERE;
6595 expression_t *size = parse_constant_expression();
6597 type_t *type = entity->declaration.type;
6598 type_t *bitfield_type = make_bitfield_type(type, size,
6599 &source_position, entity->base.symbol);
6600 entity->declaration.type = bitfield_type;
6602 type_t *orig_type = entity->declaration.type;
6603 type_t *type = skip_typeref(orig_type);
6604 if (is_type_function(type)) {
6605 errorf(&entity->base.source_position,
6606 "compound member '%Y' must not have function type '%T'",
6607 entity->base.symbol, orig_type);
6608 } else if (is_type_incomplete(type)) {
6609 /* §6.7.2.1:16 flexible array member */
6610 if (is_type_array(type) &&
6611 token.type == ';' &&
6612 look_ahead(1)->type == '}') {
6613 compound->has_flexible_member = true;
6615 errorf(&entity->base.source_position,
6616 "compound member '%Y' has incomplete type '%T'",
6617 entity->base.symbol, orig_type);
6622 append_entity(&compound->members, entity);
6626 if (token.type != ',')
6630 expect(';', end_error);
6633 anonymous_entity = NULL;
6636 static void parse_compound_type_entries(compound_t *compound)
6639 add_anchor_token('}');
6641 while (token.type != '}') {
6642 if (token.type == T_EOF) {
6643 errorf(HERE, "EOF while parsing struct");
6646 declaration_specifiers_t specifiers;
6647 memset(&specifiers, 0, sizeof(specifiers));
6648 parse_declaration_specifiers(&specifiers);
6650 parse_compound_declarators(compound, &specifiers);
6652 rem_anchor_token('}');
6656 compound->complete = true;
6659 static type_t *parse_typename(void)
6661 declaration_specifiers_t specifiers;
6662 memset(&specifiers, 0, sizeof(specifiers));
6663 parse_declaration_specifiers(&specifiers);
6664 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6665 specifiers.thread_local) {
6666 /* TODO: improve error message, user does probably not know what a
6667 * storage class is...
6669 errorf(HERE, "typename may not have a storage class");
6672 type_t *result = parse_abstract_declarator(specifiers.type);
6680 typedef expression_t* (*parse_expression_function)(void);
6681 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6683 typedef struct expression_parser_function_t expression_parser_function_t;
6684 struct expression_parser_function_t {
6685 parse_expression_function parser;
6686 precedence_t infix_precedence;
6687 parse_expression_infix_function infix_parser;
6690 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6693 * Prints an error message if an expression was expected but not read
6695 static expression_t *expected_expression_error(void)
6697 /* skip the error message if the error token was read */
6698 if (token.type != T_ERROR) {
6699 errorf(HERE, "expected expression, got token %K", &token);
6703 return create_invalid_expression();
6707 * Parse a string constant.
6709 static expression_t *parse_string_const(void)
6712 if (token.type == T_STRING_LITERAL) {
6713 string_t res = token.v.string;
6715 while (token.type == T_STRING_LITERAL) {
6716 res = concat_strings(&res, &token.v.string);
6719 if (token.type != T_WIDE_STRING_LITERAL) {
6720 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6721 /* note: that we use type_char_ptr here, which is already the
6722 * automatic converted type. revert_automatic_type_conversion
6723 * will construct the array type */
6724 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6725 cnst->string.value = res;
6729 wres = concat_string_wide_string(&res, &token.v.wide_string);
6731 wres = token.v.wide_string;
6736 switch (token.type) {
6737 case T_WIDE_STRING_LITERAL:
6738 wres = concat_wide_strings(&wres, &token.v.wide_string);
6741 case T_STRING_LITERAL:
6742 wres = concat_wide_string_string(&wres, &token.v.string);
6746 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6747 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6748 cnst->wide_string.value = wres;
6757 * Parse a boolean constant.
6759 static expression_t *parse_bool_const(bool value)
6761 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6762 cnst->base.type = type_bool;
6763 cnst->conste.v.int_value = value;
6771 * Parse an integer constant.
6773 static expression_t *parse_int_const(void)
6775 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6776 cnst->base.type = token.datatype;
6777 cnst->conste.v.int_value = token.v.intvalue;
6785 * Parse a character constant.
6787 static expression_t *parse_character_constant(void)
6789 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6790 cnst->base.type = token.datatype;
6791 cnst->conste.v.character = token.v.string;
6793 if (cnst->conste.v.character.size != 1) {
6795 errorf(HERE, "more than 1 character in character constant");
6796 } else if (warning.multichar) {
6797 warningf(HERE, "multi-character character constant");
6806 * Parse a wide character constant.
6808 static expression_t *parse_wide_character_constant(void)
6810 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6811 cnst->base.type = token.datatype;
6812 cnst->conste.v.wide_character = token.v.wide_string;
6814 if (cnst->conste.v.wide_character.size != 1) {
6816 errorf(HERE, "more than 1 character in character constant");
6817 } else if (warning.multichar) {
6818 warningf(HERE, "multi-character character constant");
6827 * Parse a float constant.
6829 static expression_t *parse_float_const(void)
6831 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6832 cnst->base.type = token.datatype;
6833 cnst->conste.v.float_value = token.v.floatvalue;
6840 static entity_t *create_implicit_function(symbol_t *symbol,
6841 const source_position_t *source_position)
6843 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6844 ntype->function.return_type = type_int;
6845 ntype->function.unspecified_parameters = true;
6846 ntype->function.linkage = LINKAGE_C;
6847 type_t *type = identify_new_type(ntype);
6849 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6850 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6851 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6852 entity->declaration.type = type;
6853 entity->declaration.implicit = true;
6854 entity->base.symbol = symbol;
6855 entity->base.source_position = *source_position;
6857 bool strict_prototypes_old = warning.strict_prototypes;
6858 warning.strict_prototypes = false;
6859 record_entity(entity, false);
6860 warning.strict_prototypes = strict_prototypes_old;
6866 * Creates a return_type (func)(argument_type) function type if not
6869 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6870 type_t *argument_type2)
6872 function_parameter_t *parameter2
6873 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6874 memset(parameter2, 0, sizeof(parameter2[0]));
6875 parameter2->type = argument_type2;
6877 function_parameter_t *parameter1
6878 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6879 memset(parameter1, 0, sizeof(parameter1[0]));
6880 parameter1->type = argument_type1;
6881 parameter1->next = parameter2;
6883 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6884 type->function.return_type = return_type;
6885 type->function.parameters = parameter1;
6887 return identify_new_type(type);
6891 * Creates a return_type (func)(argument_type) function type if not
6894 * @param return_type the return type
6895 * @param argument_type the argument type
6897 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6899 function_parameter_t *parameter
6900 = obstack_alloc(type_obst, sizeof(parameter[0]));
6901 memset(parameter, 0, sizeof(parameter[0]));
6902 parameter->type = argument_type;
6904 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6905 type->function.return_type = return_type;
6906 type->function.parameters = parameter;
6908 return identify_new_type(type);
6911 static type_t *make_function_0_type(type_t *return_type)
6913 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6914 type->function.return_type = return_type;
6915 type->function.parameters = NULL;
6917 return identify_new_type(type);
6921 * Creates a function type for some function like builtins.
6923 * @param symbol the symbol describing the builtin
6925 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6927 switch (symbol->ID) {
6928 case T___builtin_alloca:
6929 return make_function_1_type(type_void_ptr, type_size_t);
6930 case T___builtin_huge_val:
6931 return make_function_0_type(type_double);
6932 case T___builtin_inf:
6933 return make_function_0_type(type_double);
6934 case T___builtin_inff:
6935 return make_function_0_type(type_float);
6936 case T___builtin_infl:
6937 return make_function_0_type(type_long_double);
6938 case T___builtin_nan:
6939 return make_function_1_type(type_double, type_char_ptr);
6940 case T___builtin_nanf:
6941 return make_function_1_type(type_float, type_char_ptr);
6942 case T___builtin_nanl:
6943 return make_function_1_type(type_long_double, type_char_ptr);
6944 case T___builtin_va_end:
6945 return make_function_1_type(type_void, type_valist);
6946 case T___builtin_expect:
6947 return make_function_2_type(type_long, type_long, type_long);
6948 case T___builtin_return_address:
6949 case T___builtin_frame_address:
6950 return make_function_1_type(type_void_ptr, type_unsigned_int);
6952 internal_errorf(HERE, "not implemented builtin identifier found");
6957 * Performs automatic type cast as described in § 6.3.2.1.
6959 * @param orig_type the original type
6961 static type_t *automatic_type_conversion(type_t *orig_type)
6963 type_t *type = skip_typeref(orig_type);
6964 if (is_type_array(type)) {
6965 array_type_t *array_type = &type->array;
6966 type_t *element_type = array_type->element_type;
6967 unsigned qualifiers = array_type->base.qualifiers;
6969 return make_pointer_type(element_type, qualifiers);
6972 if (is_type_function(type)) {
6973 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6980 * reverts the automatic casts of array to pointer types and function
6981 * to function-pointer types as defined § 6.3.2.1
6983 type_t *revert_automatic_type_conversion(const expression_t *expression)
6985 switch (expression->kind) {
6986 case EXPR_REFERENCE: {
6987 entity_t *entity = expression->reference.entity;
6988 if (is_declaration(entity)) {
6989 return entity->declaration.type;
6990 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6991 return entity->enum_value.enum_type;
6993 panic("no declaration or enum in reference");
6998 entity_t *entity = expression->select.compound_entry;
6999 assert(is_declaration(entity));
7000 type_t *type = entity->declaration.type;
7001 return get_qualified_type(type,
7002 expression->base.type->base.qualifiers);
7005 case EXPR_UNARY_DEREFERENCE: {
7006 const expression_t *const value = expression->unary.value;
7007 type_t *const type = skip_typeref(value->base.type);
7008 if (!is_type_pointer(type))
7009 return type_error_type;
7010 return type->pointer.points_to;
7013 case EXPR_BUILTIN_SYMBOL:
7014 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
7016 case EXPR_ARRAY_ACCESS: {
7017 const expression_t *array_ref = expression->array_access.array_ref;
7018 type_t *type_left = skip_typeref(array_ref->base.type);
7019 if (!is_type_pointer(type_left))
7020 return type_error_type;
7021 return type_left->pointer.points_to;
7024 case EXPR_STRING_LITERAL: {
7025 size_t size = expression->string.value.size;
7026 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7029 case EXPR_WIDE_STRING_LITERAL: {
7030 size_t size = expression->wide_string.value.size;
7031 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7034 case EXPR_COMPOUND_LITERAL:
7035 return expression->compound_literal.type;
7038 return expression->base.type;
7042 static expression_t *parse_reference(void)
7044 symbol_t *const symbol = token.v.symbol;
7046 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7048 if (entity == NULL) {
7049 if (!strict_mode && look_ahead(1)->type == '(') {
7050 /* an implicitly declared function */
7051 if (warning.error_implicit_function_declaration) {
7052 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7053 } else if (warning.implicit_function_declaration) {
7054 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7057 entity = create_implicit_function(symbol, HERE);
7059 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7060 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7066 if (is_declaration(entity)) {
7067 orig_type = entity->declaration.type;
7068 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7069 orig_type = entity->enum_value.enum_type;
7070 } else if (entity->kind == ENTITY_TYPEDEF) {
7071 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7074 return create_invalid_expression();
7076 panic("expected declaration or enum value in reference");
7079 /* we always do the auto-type conversions; the & and sizeof parser contains
7080 * code to revert this! */
7081 type_t *type = automatic_type_conversion(orig_type);
7083 expression_kind_t kind = EXPR_REFERENCE;
7084 if (entity->kind == ENTITY_ENUM_VALUE)
7085 kind = EXPR_REFERENCE_ENUM_VALUE;
7087 expression_t *expression = allocate_expression_zero(kind);
7088 expression->reference.entity = entity;
7089 expression->base.type = type;
7091 /* this declaration is used */
7092 if (is_declaration(entity)) {
7093 entity->declaration.used = true;
7096 if (entity->base.parent_scope != file_scope
7097 && entity->base.parent_scope->depth < current_function->parameters.depth
7098 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7099 if (entity->kind == ENTITY_VARIABLE) {
7100 /* access of a variable from an outer function */
7101 entity->variable.address_taken = true;
7102 } else if (entity->kind == ENTITY_PARAMETER) {
7103 entity->parameter.address_taken = true;
7105 current_function->need_closure = true;
7108 /* check for deprecated functions */
7109 if (warning.deprecated_declarations
7110 && is_declaration(entity)
7111 && entity->declaration.modifiers & DM_DEPRECATED) {
7112 declaration_t *declaration = &entity->declaration;
7114 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7115 "function" : "variable";
7117 if (declaration->deprecated_string != NULL) {
7118 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7119 prefix, entity->base.symbol, &entity->base.source_position,
7120 declaration->deprecated_string);
7122 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7123 entity->base.symbol, &entity->base.source_position);
7127 if (warning.init_self && entity == current_init_decl && !in_type_prop
7128 && entity->kind == ENTITY_VARIABLE) {
7129 current_init_decl = NULL;
7130 warningf(HERE, "variable '%#T' is initialized by itself",
7131 entity->declaration.type, entity->base.symbol);
7138 static bool semantic_cast(expression_t *cast)
7140 expression_t *expression = cast->unary.value;
7141 type_t *orig_dest_type = cast->base.type;
7142 type_t *orig_type_right = expression->base.type;
7143 type_t const *dst_type = skip_typeref(orig_dest_type);
7144 type_t const *src_type = skip_typeref(orig_type_right);
7145 source_position_t const *pos = &cast->base.source_position;
7147 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7148 if (dst_type == type_void)
7151 /* only integer and pointer can be casted to pointer */
7152 if (is_type_pointer(dst_type) &&
7153 !is_type_pointer(src_type) &&
7154 !is_type_integer(src_type) &&
7155 is_type_valid(src_type)) {
7156 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7160 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7161 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7165 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7166 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7170 if (warning.cast_qual &&
7171 is_type_pointer(src_type) &&
7172 is_type_pointer(dst_type)) {
7173 type_t *src = skip_typeref(src_type->pointer.points_to);
7174 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7175 unsigned missing_qualifiers =
7176 src->base.qualifiers & ~dst->base.qualifiers;
7177 if (missing_qualifiers != 0) {
7179 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7180 missing_qualifiers, orig_type_right);
7186 static expression_t *parse_compound_literal(type_t *type)
7188 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7190 parse_initializer_env_t env;
7193 env.must_be_constant = false;
7194 initializer_t *initializer = parse_initializer(&env);
7197 expression->compound_literal.initializer = initializer;
7198 expression->compound_literal.type = type;
7199 expression->base.type = automatic_type_conversion(type);
7205 * Parse a cast expression.
7207 static expression_t *parse_cast(void)
7209 add_anchor_token(')');
7211 source_position_t source_position = token.source_position;
7213 type_t *type = parse_typename();
7215 rem_anchor_token(')');
7216 expect(')', end_error);
7218 if (token.type == '{') {
7219 return parse_compound_literal(type);
7222 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7223 cast->base.source_position = source_position;
7225 expression_t *value = parse_sub_expression(PREC_CAST);
7226 cast->base.type = type;
7227 cast->unary.value = value;
7229 if (! semantic_cast(cast)) {
7230 /* TODO: record the error in the AST. else it is impossible to detect it */
7235 return create_invalid_expression();
7239 * Parse a statement expression.
7241 static expression_t *parse_statement_expression(void)
7243 add_anchor_token(')');
7245 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7247 statement_t *statement = parse_compound_statement(true);
7248 statement->compound.stmt_expr = true;
7249 expression->statement.statement = statement;
7251 /* find last statement and use its type */
7252 type_t *type = type_void;
7253 const statement_t *stmt = statement->compound.statements;
7255 while (stmt->base.next != NULL)
7256 stmt = stmt->base.next;
7258 if (stmt->kind == STATEMENT_EXPRESSION) {
7259 type = stmt->expression.expression->base.type;
7261 } else if (warning.other) {
7262 warningf(&expression->base.source_position, "empty statement expression ({})");
7264 expression->base.type = type;
7266 rem_anchor_token(')');
7267 expect(')', end_error);
7274 * Parse a parenthesized expression.
7276 static expression_t *parse_parenthesized_expression(void)
7280 switch (token.type) {
7282 /* gcc extension: a statement expression */
7283 return parse_statement_expression();
7287 return parse_cast();
7289 if (is_typedef_symbol(token.v.symbol)) {
7290 return parse_cast();
7294 add_anchor_token(')');
7295 expression_t *result = parse_expression();
7296 result->base.parenthesized = true;
7297 rem_anchor_token(')');
7298 expect(')', end_error);
7304 static expression_t *parse_function_keyword(void)
7308 if (current_function == NULL) {
7309 errorf(HERE, "'__func__' used outside of a function");
7312 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7313 expression->base.type = type_char_ptr;
7314 expression->funcname.kind = FUNCNAME_FUNCTION;
7321 static expression_t *parse_pretty_function_keyword(void)
7323 if (current_function == NULL) {
7324 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7327 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7328 expression->base.type = type_char_ptr;
7329 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7331 eat(T___PRETTY_FUNCTION__);
7336 static expression_t *parse_funcsig_keyword(void)
7338 if (current_function == NULL) {
7339 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7342 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7343 expression->base.type = type_char_ptr;
7344 expression->funcname.kind = FUNCNAME_FUNCSIG;
7351 static expression_t *parse_funcdname_keyword(void)
7353 if (current_function == NULL) {
7354 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7357 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7358 expression->base.type = type_char_ptr;
7359 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7361 eat(T___FUNCDNAME__);
7366 static designator_t *parse_designator(void)
7368 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7369 result->source_position = *HERE;
7371 if (token.type != T_IDENTIFIER) {
7372 parse_error_expected("while parsing member designator",
7373 T_IDENTIFIER, NULL);
7376 result->symbol = token.v.symbol;
7379 designator_t *last_designator = result;
7381 if (token.type == '.') {
7383 if (token.type != T_IDENTIFIER) {
7384 parse_error_expected("while parsing member designator",
7385 T_IDENTIFIER, NULL);
7388 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7389 designator->source_position = *HERE;
7390 designator->symbol = token.v.symbol;
7393 last_designator->next = designator;
7394 last_designator = designator;
7397 if (token.type == '[') {
7399 add_anchor_token(']');
7400 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7401 designator->source_position = *HERE;
7402 designator->array_index = parse_expression();
7403 rem_anchor_token(']');
7404 expect(']', end_error);
7405 if (designator->array_index == NULL) {
7409 last_designator->next = designator;
7410 last_designator = designator;
7422 * Parse the __builtin_offsetof() expression.
7424 static expression_t *parse_offsetof(void)
7426 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7427 expression->base.type = type_size_t;
7429 eat(T___builtin_offsetof);
7431 expect('(', end_error);
7432 add_anchor_token(',');
7433 type_t *type = parse_typename();
7434 rem_anchor_token(',');
7435 expect(',', end_error);
7436 add_anchor_token(')');
7437 designator_t *designator = parse_designator();
7438 rem_anchor_token(')');
7439 expect(')', end_error);
7441 expression->offsetofe.type = type;
7442 expression->offsetofe.designator = designator;
7445 memset(&path, 0, sizeof(path));
7446 path.top_type = type;
7447 path.path = NEW_ARR_F(type_path_entry_t, 0);
7449 descend_into_subtype(&path);
7451 if (!walk_designator(&path, designator, true)) {
7452 return create_invalid_expression();
7455 DEL_ARR_F(path.path);
7459 return create_invalid_expression();
7463 * Parses a _builtin_va_start() expression.
7465 static expression_t *parse_va_start(void)
7467 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7469 eat(T___builtin_va_start);
7471 expect('(', end_error);
7472 add_anchor_token(',');
7473 expression->va_starte.ap = parse_assignment_expression();
7474 rem_anchor_token(',');
7475 expect(',', end_error);
7476 expression_t *const expr = parse_assignment_expression();
7477 if (expr->kind == EXPR_REFERENCE) {
7478 entity_t *const entity = expr->reference.entity;
7479 if (entity->base.parent_scope != ¤t_function->parameters
7480 || entity->base.next != NULL
7481 || entity->kind != ENTITY_PARAMETER) {
7482 errorf(&expr->base.source_position,
7483 "second argument of 'va_start' must be last parameter of the current function");
7485 expression->va_starte.parameter = &entity->variable;
7487 expect(')', end_error);
7490 expect(')', end_error);
7492 return create_invalid_expression();
7496 * Parses a _builtin_va_arg() expression.
7498 static expression_t *parse_va_arg(void)
7500 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7502 eat(T___builtin_va_arg);
7504 expect('(', end_error);
7505 expression->va_arge.ap = parse_assignment_expression();
7506 expect(',', end_error);
7507 expression->base.type = parse_typename();
7508 expect(')', end_error);
7512 return create_invalid_expression();
7515 static expression_t *parse_builtin_symbol(void)
7517 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7519 symbol_t *symbol = token.v.symbol;
7521 expression->builtin_symbol.symbol = symbol;
7524 type_t *type = get_builtin_symbol_type(symbol);
7525 type = automatic_type_conversion(type);
7527 expression->base.type = type;
7532 * Parses a __builtin_constant_p() expression.
7534 static expression_t *parse_builtin_constant(void)
7536 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7538 eat(T___builtin_constant_p);
7540 expect('(', end_error);
7541 add_anchor_token(')');
7542 expression->builtin_constant.value = parse_assignment_expression();
7543 rem_anchor_token(')');
7544 expect(')', end_error);
7545 expression->base.type = type_int;
7549 return create_invalid_expression();
7553 * Parses a __builtin_types_compatible_p() expression.
7555 static expression_t *parse_builtin_types_compatible(void)
7557 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7559 eat(T___builtin_types_compatible_p);
7561 expect('(', end_error);
7562 add_anchor_token(')');
7563 add_anchor_token(',');
7564 expression->builtin_types_compatible.left = parse_typename();
7565 rem_anchor_token(',');
7566 expect(',', end_error);
7567 expression->builtin_types_compatible.right = parse_typename();
7568 rem_anchor_token(')');
7569 expect(')', end_error);
7570 expression->base.type = type_int;
7574 return create_invalid_expression();
7578 * Parses a __builtin_prefetch() expression.
7580 static expression_t *parse_builtin_prefetch(void)
7582 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7584 eat(T___builtin_prefetch);
7586 expect('(', end_error);
7587 add_anchor_token(')');
7588 expression->builtin_prefetch.adr = parse_assignment_expression();
7589 if (token.type == ',') {
7591 expression->builtin_prefetch.rw = parse_assignment_expression();
7593 if (token.type == ',') {
7595 expression->builtin_prefetch.locality = parse_assignment_expression();
7597 rem_anchor_token(')');
7598 expect(')', end_error);
7599 expression->base.type = type_void;
7603 return create_invalid_expression();
7607 * Parses a __builtin_is_*() compare expression.
7609 static expression_t *parse_compare_builtin(void)
7611 expression_t *expression;
7613 switch (token.type) {
7614 case T___builtin_isgreater:
7615 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7617 case T___builtin_isgreaterequal:
7618 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7620 case T___builtin_isless:
7621 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7623 case T___builtin_islessequal:
7624 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7626 case T___builtin_islessgreater:
7627 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7629 case T___builtin_isunordered:
7630 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7633 internal_errorf(HERE, "invalid compare builtin found");
7635 expression->base.source_position = *HERE;
7638 expect('(', end_error);
7639 expression->binary.left = parse_assignment_expression();
7640 expect(',', end_error);
7641 expression->binary.right = parse_assignment_expression();
7642 expect(')', end_error);
7644 type_t *const orig_type_left = expression->binary.left->base.type;
7645 type_t *const orig_type_right = expression->binary.right->base.type;
7647 type_t *const type_left = skip_typeref(orig_type_left);
7648 type_t *const type_right = skip_typeref(orig_type_right);
7649 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7650 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7651 type_error_incompatible("invalid operands in comparison",
7652 &expression->base.source_position, orig_type_left, orig_type_right);
7655 semantic_comparison(&expression->binary);
7660 return create_invalid_expression();
7665 * Parses a __builtin_expect(, end_error) expression.
7667 static expression_t *parse_builtin_expect(void, end_error)
7669 expression_t *expression
7670 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7672 eat(T___builtin_expect);
7674 expect('(', end_error);
7675 expression->binary.left = parse_assignment_expression();
7676 expect(',', end_error);
7677 expression->binary.right = parse_constant_expression();
7678 expect(')', end_error);
7680 expression->base.type = expression->binary.left->base.type;
7684 return create_invalid_expression();
7689 * Parses a MS assume() expression.
7691 static expression_t *parse_assume(void)
7693 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7697 expect('(', end_error);
7698 add_anchor_token(')');
7699 expression->unary.value = parse_assignment_expression();
7700 rem_anchor_token(')');
7701 expect(')', end_error);
7703 expression->base.type = type_void;
7706 return create_invalid_expression();
7710 * Return the declaration for a given label symbol or create a new one.
7712 * @param symbol the symbol of the label
7714 static label_t *get_label(symbol_t *symbol)
7717 assert(current_function != NULL);
7719 label = get_entity(symbol, NAMESPACE_LABEL);
7720 /* if we found a local label, we already created the declaration */
7721 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7722 if (label->base.parent_scope != current_scope) {
7723 assert(label->base.parent_scope->depth < current_scope->depth);
7724 current_function->goto_to_outer = true;
7726 return &label->label;
7729 label = get_entity(symbol, NAMESPACE_LABEL);
7730 /* if we found a label in the same function, then we already created the
7733 && label->base.parent_scope == ¤t_function->parameters) {
7734 return &label->label;
7737 /* otherwise we need to create a new one */
7738 label = allocate_entity_zero(ENTITY_LABEL);
7739 label->base.namespc = NAMESPACE_LABEL;
7740 label->base.symbol = symbol;
7744 return &label->label;
7748 * Parses a GNU && label address expression.
7750 static expression_t *parse_label_address(void)
7752 source_position_t source_position = token.source_position;
7754 if (token.type != T_IDENTIFIER) {
7755 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7758 symbol_t *symbol = token.v.symbol;
7761 label_t *label = get_label(symbol);
7763 label->address_taken = true;
7765 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7766 expression->base.source_position = source_position;
7768 /* label address is threaten as a void pointer */
7769 expression->base.type = type_void_ptr;
7770 expression->label_address.label = label;
7773 return create_invalid_expression();
7777 * Parse a microsoft __noop expression.
7779 static expression_t *parse_noop_expression(void)
7781 /* the result is a (int)0 */
7782 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7783 cnst->base.type = type_int;
7784 cnst->conste.v.int_value = 0;
7785 cnst->conste.is_ms_noop = true;
7789 if (token.type == '(') {
7790 /* parse arguments */
7792 add_anchor_token(')');
7793 add_anchor_token(',');
7795 if (token.type != ')') {
7797 (void)parse_assignment_expression();
7798 if (token.type != ',')
7804 rem_anchor_token(',');
7805 rem_anchor_token(')');
7806 expect(')', end_error);
7813 * Parses a primary expression.
7815 static expression_t *parse_primary_expression(void)
7817 switch (token.type) {
7818 case T_false: return parse_bool_const(false);
7819 case T_true: return parse_bool_const(true);
7820 case T_INTEGER: return parse_int_const();
7821 case T_CHARACTER_CONSTANT: return parse_character_constant();
7822 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7823 case T_FLOATINGPOINT: return parse_float_const();
7824 case T_STRING_LITERAL:
7825 case T_WIDE_STRING_LITERAL: return parse_string_const();
7826 case T_IDENTIFIER: return parse_reference();
7827 case T___FUNCTION__:
7828 case T___func__: return parse_function_keyword();
7829 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7830 case T___FUNCSIG__: return parse_funcsig_keyword();
7831 case T___FUNCDNAME__: return parse_funcdname_keyword();
7832 case T___builtin_offsetof: return parse_offsetof();
7833 case T___builtin_va_start: return parse_va_start();
7834 case T___builtin_va_arg: return parse_va_arg();
7835 case T___builtin_expect:
7836 case T___builtin_alloca:
7837 case T___builtin_inf:
7838 case T___builtin_inff:
7839 case T___builtin_infl:
7840 case T___builtin_nan:
7841 case T___builtin_nanf:
7842 case T___builtin_nanl:
7843 case T___builtin_huge_val:
7844 case T___builtin_va_end:
7845 case T___builtin_return_address:
7846 case T___builtin_frame_address: return parse_builtin_symbol();
7847 case T___builtin_isgreater:
7848 case T___builtin_isgreaterequal:
7849 case T___builtin_isless:
7850 case T___builtin_islessequal:
7851 case T___builtin_islessgreater:
7852 case T___builtin_isunordered: return parse_compare_builtin();
7853 case T___builtin_constant_p: return parse_builtin_constant();
7854 case T___builtin_prefetch: return parse_builtin_prefetch();
7855 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7856 case T__assume: return parse_assume();
7859 return parse_label_address();
7862 case '(': return parse_parenthesized_expression();
7863 case T___noop: return parse_noop_expression();
7866 errorf(HERE, "unexpected token %K, expected an expression", &token);
7867 return create_invalid_expression();
7871 * Check if the expression has the character type and issue a warning then.
7873 static void check_for_char_index_type(const expression_t *expression)
7875 type_t *const type = expression->base.type;
7876 const type_t *const base_type = skip_typeref(type);
7878 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7879 warning.char_subscripts) {
7880 warningf(&expression->base.source_position,
7881 "array subscript has type '%T'", type);
7885 static expression_t *parse_array_expression(expression_t *left)
7887 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7890 add_anchor_token(']');
7892 expression_t *inside = parse_expression();
7894 type_t *const orig_type_left = left->base.type;
7895 type_t *const orig_type_inside = inside->base.type;
7897 type_t *const type_left = skip_typeref(orig_type_left);
7898 type_t *const type_inside = skip_typeref(orig_type_inside);
7900 type_t *return_type;
7901 array_access_expression_t *array_access = &expression->array_access;
7902 if (is_type_pointer(type_left)) {
7903 return_type = type_left->pointer.points_to;
7904 array_access->array_ref = left;
7905 array_access->index = inside;
7906 check_for_char_index_type(inside);
7907 } else if (is_type_pointer(type_inside)) {
7908 return_type = type_inside->pointer.points_to;
7909 array_access->array_ref = inside;
7910 array_access->index = left;
7911 array_access->flipped = true;
7912 check_for_char_index_type(left);
7914 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7916 "array access on object with non-pointer types '%T', '%T'",
7917 orig_type_left, orig_type_inside);
7919 return_type = type_error_type;
7920 array_access->array_ref = left;
7921 array_access->index = inside;
7924 expression->base.type = automatic_type_conversion(return_type);
7926 rem_anchor_token(']');
7927 expect(']', end_error);
7932 static expression_t *parse_typeprop(expression_kind_t const kind)
7934 expression_t *tp_expression = allocate_expression_zero(kind);
7935 tp_expression->base.type = type_size_t;
7937 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7939 /* we only refer to a type property, mark this case */
7940 bool old = in_type_prop;
7941 in_type_prop = true;
7944 expression_t *expression;
7945 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7947 add_anchor_token(')');
7948 orig_type = parse_typename();
7949 rem_anchor_token(')');
7950 expect(')', end_error);
7952 if (token.type == '{') {
7953 /* It was not sizeof(type) after all. It is sizeof of an expression
7954 * starting with a compound literal */
7955 expression = parse_compound_literal(orig_type);
7956 goto typeprop_expression;
7959 expression = parse_sub_expression(PREC_UNARY);
7961 typeprop_expression:
7962 tp_expression->typeprop.tp_expression = expression;
7964 orig_type = revert_automatic_type_conversion(expression);
7965 expression->base.type = orig_type;
7968 tp_expression->typeprop.type = orig_type;
7969 type_t const* const type = skip_typeref(orig_type);
7970 char const* const wrong_type =
7971 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7972 is_type_incomplete(type) ? "incomplete" :
7973 type->kind == TYPE_FUNCTION ? "function designator" :
7974 type->kind == TYPE_BITFIELD ? "bitfield" :
7976 if (wrong_type != NULL) {
7977 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7978 errorf(&tp_expression->base.source_position,
7979 "operand of %s expression must not be of %s type '%T'",
7980 what, wrong_type, orig_type);
7985 return tp_expression;
7988 static expression_t *parse_sizeof(void)
7990 return parse_typeprop(EXPR_SIZEOF);
7993 static expression_t *parse_alignof(void)
7995 return parse_typeprop(EXPR_ALIGNOF);
7998 static expression_t *parse_select_expression(expression_t *compound)
8000 expression_t *select = allocate_expression_zero(EXPR_SELECT);
8001 select->select.compound = compound;
8003 assert(token.type == '.' || token.type == T_MINUSGREATER);
8004 bool is_pointer = (token.type == T_MINUSGREATER);
8007 if (token.type != T_IDENTIFIER) {
8008 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
8011 symbol_t *symbol = token.v.symbol;
8014 type_t *const orig_type = compound->base.type;
8015 type_t *const type = skip_typeref(orig_type);
8018 bool saw_error = false;
8019 if (is_type_pointer(type)) {
8022 "request for member '%Y' in something not a struct or union, but '%T'",
8026 type_left = skip_typeref(type->pointer.points_to);
8028 if (is_pointer && is_type_valid(type)) {
8029 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
8036 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
8037 type_left->kind == TYPE_COMPOUND_UNION) {
8038 compound_t *compound = type_left->compound.compound;
8040 if (!compound->complete) {
8041 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
8043 goto create_error_entry;
8046 entry = find_compound_entry(compound, symbol);
8047 if (entry == NULL) {
8048 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
8049 goto create_error_entry;
8052 if (is_type_valid(type_left) && !saw_error) {
8054 "request for member '%Y' in something not a struct or union, but '%T'",
8058 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8061 assert(is_declaration(entry));
8062 select->select.compound_entry = entry;
8064 type_t *entry_type = entry->declaration.type;
8066 = get_qualified_type(entry_type, type_left->base.qualifiers);
8068 /* we always do the auto-type conversions; the & and sizeof parser contains
8069 * code to revert this! */
8070 select->base.type = automatic_type_conversion(res_type);
8072 type_t *skipped = skip_typeref(res_type);
8073 if (skipped->kind == TYPE_BITFIELD) {
8074 select->base.type = skipped->bitfield.base_type;
8080 static void check_call_argument(const function_parameter_t *parameter,
8081 call_argument_t *argument, unsigned pos)
8083 type_t *expected_type = parameter->type;
8084 type_t *expected_type_skip = skip_typeref(expected_type);
8085 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8086 expression_t *arg_expr = argument->expression;
8087 type_t *arg_type = skip_typeref(arg_expr->base.type);
8089 /* handle transparent union gnu extension */
8090 if (is_type_union(expected_type_skip)
8091 && (expected_type_skip->base.modifiers
8092 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8093 compound_t *union_decl = expected_type_skip->compound.compound;
8094 type_t *best_type = NULL;
8095 entity_t *entry = union_decl->members.entities;
8096 for ( ; entry != NULL; entry = entry->base.next) {
8097 assert(is_declaration(entry));
8098 type_t *decl_type = entry->declaration.type;
8099 error = semantic_assign(decl_type, arg_expr);
8100 if (error == ASSIGN_ERROR_INCOMPATIBLE
8101 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8104 if (error == ASSIGN_SUCCESS) {
8105 best_type = decl_type;
8106 } else if (best_type == NULL) {
8107 best_type = decl_type;
8111 if (best_type != NULL) {
8112 expected_type = best_type;
8116 error = semantic_assign(expected_type, arg_expr);
8117 argument->expression = create_implicit_cast(argument->expression,
8120 if (error != ASSIGN_SUCCESS) {
8121 /* report exact scope in error messages (like "in argument 3") */
8123 snprintf(buf, sizeof(buf), "call argument %u", pos);
8124 report_assign_error(error, expected_type, arg_expr, buf,
8125 &arg_expr->base.source_position);
8126 } else if (warning.traditional || warning.conversion) {
8127 type_t *const promoted_type = get_default_promoted_type(arg_type);
8128 if (!types_compatible(expected_type_skip, promoted_type) &&
8129 !types_compatible(expected_type_skip, type_void_ptr) &&
8130 !types_compatible(type_void_ptr, promoted_type)) {
8131 /* Deliberately show the skipped types in this warning */
8132 warningf(&arg_expr->base.source_position,
8133 "passing call argument %u as '%T' rather than '%T' due to prototype",
8134 pos, expected_type_skip, promoted_type);
8140 * Handle the semantic restrictions of builtin calls
8142 static void handle_builtin_argument_restrictions(call_expression_t *call) {
8143 switch (call->function->builtin_symbol.symbol->ID) {
8144 case T___builtin_return_address:
8145 case T___builtin_frame_address: {
8146 /* argument must be constant */
8147 call_argument_t *argument = call->arguments;
8149 if (! is_constant_expression(argument->expression)) {
8150 errorf(&call->base.source_position,
8151 "argument of '%Y' must be a constant expression",
8152 call->function->builtin_symbol.symbol);
8162 * Parse a call expression, ie. expression '( ... )'.
8164 * @param expression the function address
8166 static expression_t *parse_call_expression(expression_t *expression)
8168 expression_t *result = allocate_expression_zero(EXPR_CALL);
8169 call_expression_t *call = &result->call;
8170 call->function = expression;
8172 type_t *const orig_type = expression->base.type;
8173 type_t *const type = skip_typeref(orig_type);
8175 function_type_t *function_type = NULL;
8176 if (is_type_pointer(type)) {
8177 type_t *const to_type = skip_typeref(type->pointer.points_to);
8179 if (is_type_function(to_type)) {
8180 function_type = &to_type->function;
8181 call->base.type = function_type->return_type;
8185 if (function_type == NULL && is_type_valid(type)) {
8186 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8189 /* parse arguments */
8191 add_anchor_token(')');
8192 add_anchor_token(',');
8194 if (token.type != ')') {
8195 call_argument_t *last_argument = NULL;
8198 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8200 argument->expression = parse_assignment_expression();
8201 if (last_argument == NULL) {
8202 call->arguments = argument;
8204 last_argument->next = argument;
8206 last_argument = argument;
8208 if (token.type != ',')
8213 rem_anchor_token(',');
8214 rem_anchor_token(')');
8215 expect(')', end_error);
8217 if (function_type == NULL)
8220 function_parameter_t *parameter = function_type->parameters;
8221 call_argument_t *argument = call->arguments;
8222 if (!function_type->unspecified_parameters) {
8223 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8224 parameter = parameter->next, argument = argument->next) {
8225 check_call_argument(parameter, argument, ++pos);
8228 if (parameter != NULL) {
8229 errorf(HERE, "too few arguments to function '%E'", expression);
8230 } else if (argument != NULL && !function_type->variadic) {
8231 errorf(HERE, "too many arguments to function '%E'", expression);
8235 /* do default promotion */
8236 for (; argument != NULL; argument = argument->next) {
8237 type_t *type = argument->expression->base.type;
8239 type = get_default_promoted_type(type);
8241 argument->expression
8242 = create_implicit_cast(argument->expression, type);
8245 check_format(&result->call);
8247 if (warning.aggregate_return &&
8248 is_type_compound(skip_typeref(function_type->return_type))) {
8249 warningf(&result->base.source_position,
8250 "function call has aggregate value");
8253 if (call->function->kind == EXPR_BUILTIN_SYMBOL) {
8254 handle_builtin_argument_restrictions(&result->call);
8261 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8263 static bool same_compound_type(const type_t *type1, const type_t *type2)
8266 is_type_compound(type1) &&
8267 type1->kind == type2->kind &&
8268 type1->compound.compound == type2->compound.compound;
8271 static expression_t const *get_reference_address(expression_t const *expr)
8273 bool regular_take_address = true;
8275 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8276 expr = expr->unary.value;
8278 regular_take_address = false;
8281 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8284 expr = expr->unary.value;
8287 if (expr->kind != EXPR_REFERENCE)
8290 /* special case for functions which are automatically converted to a
8291 * pointer to function without an extra TAKE_ADDRESS operation */
8292 if (!regular_take_address &&
8293 expr->reference.entity->kind != ENTITY_FUNCTION) {
8300 static void warn_reference_address_as_bool(expression_t const* expr)
8302 if (!warning.address)
8305 expr = get_reference_address(expr);
8307 warningf(&expr->base.source_position,
8308 "the address of '%Y' will always evaluate as 'true'",
8309 expr->reference.entity->base.symbol);
8313 static void warn_assignment_in_condition(const expression_t *const expr)
8315 if (!warning.parentheses)
8317 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8319 if (expr->base.parenthesized)
8321 warningf(&expr->base.source_position,
8322 "suggest parentheses around assignment used as truth value");
8325 static void semantic_condition(expression_t const *const expr,
8326 char const *const context)
8328 type_t *const type = skip_typeref(expr->base.type);
8329 if (is_type_scalar(type)) {
8330 warn_reference_address_as_bool(expr);
8331 warn_assignment_in_condition(expr);
8332 } else if (is_type_valid(type)) {
8333 errorf(&expr->base.source_position,
8334 "%s must have scalar type", context);
8339 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8341 * @param expression the conditional expression
8343 static expression_t *parse_conditional_expression(expression_t *expression)
8345 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8347 conditional_expression_t *conditional = &result->conditional;
8348 conditional->condition = expression;
8351 add_anchor_token(':');
8353 /* §6.5.15:2 The first operand shall have scalar type. */
8354 semantic_condition(expression, "condition of conditional operator");
8356 expression_t *true_expression = expression;
8357 bool gnu_cond = false;
8358 if (GNU_MODE && token.type == ':') {
8361 true_expression = parse_expression();
8363 rem_anchor_token(':');
8364 expect(':', end_error);
8366 expression_t *false_expression =
8367 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8369 type_t *const orig_true_type = true_expression->base.type;
8370 type_t *const orig_false_type = false_expression->base.type;
8371 type_t *const true_type = skip_typeref(orig_true_type);
8372 type_t *const false_type = skip_typeref(orig_false_type);
8375 type_t *result_type;
8376 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8377 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8378 /* ISO/IEC 14882:1998(E) §5.16:2 */
8379 if (true_expression->kind == EXPR_UNARY_THROW) {
8380 result_type = false_type;
8381 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8382 result_type = true_type;
8384 if (warning.other && (
8385 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8386 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8388 warningf(&conditional->base.source_position,
8389 "ISO C forbids conditional expression with only one void side");
8391 result_type = type_void;
8393 } else if (is_type_arithmetic(true_type)
8394 && is_type_arithmetic(false_type)) {
8395 result_type = semantic_arithmetic(true_type, false_type);
8397 true_expression = create_implicit_cast(true_expression, result_type);
8398 false_expression = create_implicit_cast(false_expression, result_type);
8400 conditional->true_expression = true_expression;
8401 conditional->false_expression = false_expression;
8402 conditional->base.type = result_type;
8403 } else if (same_compound_type(true_type, false_type)) {
8404 /* just take 1 of the 2 types */
8405 result_type = true_type;
8406 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8407 type_t *pointer_type;
8409 expression_t *other_expression;
8410 if (is_type_pointer(true_type) &&
8411 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8412 pointer_type = true_type;
8413 other_type = false_type;
8414 other_expression = false_expression;
8416 pointer_type = false_type;
8417 other_type = true_type;
8418 other_expression = true_expression;
8421 if (is_null_pointer_constant(other_expression)) {
8422 result_type = pointer_type;
8423 } else if (is_type_pointer(other_type)) {
8424 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8425 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8428 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8429 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8431 } else if (types_compatible(get_unqualified_type(to1),
8432 get_unqualified_type(to2))) {
8435 if (warning.other) {
8436 warningf(&conditional->base.source_position,
8437 "pointer types '%T' and '%T' in conditional expression are incompatible",
8438 true_type, false_type);
8443 type_t *const type =
8444 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8445 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8446 } else if (is_type_integer(other_type)) {
8447 if (warning.other) {
8448 warningf(&conditional->base.source_position,
8449 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8451 result_type = pointer_type;
8453 if (is_type_valid(other_type)) {
8454 type_error_incompatible("while parsing conditional",
8455 &expression->base.source_position, true_type, false_type);
8457 result_type = type_error_type;
8460 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8461 type_error_incompatible("while parsing conditional",
8462 &conditional->base.source_position, true_type,
8465 result_type = type_error_type;
8468 conditional->true_expression
8469 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8470 conditional->false_expression
8471 = create_implicit_cast(false_expression, result_type);
8472 conditional->base.type = result_type;
8477 * Parse an extension expression.
8479 static expression_t *parse_extension(void)
8481 eat(T___extension__);
8483 bool old_gcc_extension = in_gcc_extension;
8484 in_gcc_extension = true;
8485 expression_t *expression = parse_sub_expression(PREC_UNARY);
8486 in_gcc_extension = old_gcc_extension;
8491 * Parse a __builtin_classify_type() expression.
8493 static expression_t *parse_builtin_classify_type(void)
8495 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8496 result->base.type = type_int;
8498 eat(T___builtin_classify_type);
8500 expect('(', end_error);
8501 add_anchor_token(')');
8502 expression_t *expression = parse_expression();
8503 rem_anchor_token(')');
8504 expect(')', end_error);
8505 result->classify_type.type_expression = expression;
8509 return create_invalid_expression();
8513 * Parse a delete expression
8514 * ISO/IEC 14882:1998(E) §5.3.5
8516 static expression_t *parse_delete(void)
8518 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8519 result->base.type = type_void;
8523 if (token.type == '[') {
8525 result->kind = EXPR_UNARY_DELETE_ARRAY;
8526 expect(']', end_error);
8530 expression_t *const value = parse_sub_expression(PREC_CAST);
8531 result->unary.value = value;
8533 type_t *const type = skip_typeref(value->base.type);
8534 if (!is_type_pointer(type)) {
8535 if (is_type_valid(type)) {
8536 errorf(&value->base.source_position,
8537 "operand of delete must have pointer type");
8539 } else if (warning.other &&
8540 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8541 warningf(&value->base.source_position,
8542 "deleting 'void*' is undefined");
8549 * Parse a throw expression
8550 * ISO/IEC 14882:1998(E) §15:1
8552 static expression_t *parse_throw(void)
8554 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8555 result->base.type = type_void;
8559 expression_t *value = NULL;
8560 switch (token.type) {
8562 value = parse_assignment_expression();
8563 /* ISO/IEC 14882:1998(E) §15.1:3 */
8564 type_t *const orig_type = value->base.type;
8565 type_t *const type = skip_typeref(orig_type);
8566 if (is_type_incomplete(type)) {
8567 errorf(&value->base.source_position,
8568 "cannot throw object of incomplete type '%T'", orig_type);
8569 } else if (is_type_pointer(type)) {
8570 type_t *const points_to = skip_typeref(type->pointer.points_to);
8571 if (is_type_incomplete(points_to) &&
8572 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8573 errorf(&value->base.source_position,
8574 "cannot throw pointer to incomplete type '%T'", orig_type);
8582 result->unary.value = value;
8587 static bool check_pointer_arithmetic(const source_position_t *source_position,
8588 type_t *pointer_type,
8589 type_t *orig_pointer_type)
8591 type_t *points_to = pointer_type->pointer.points_to;
8592 points_to = skip_typeref(points_to);
8594 if (is_type_incomplete(points_to)) {
8595 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8596 errorf(source_position,
8597 "arithmetic with pointer to incomplete type '%T' not allowed",
8600 } else if (warning.pointer_arith) {
8601 warningf(source_position,
8602 "pointer of type '%T' used in arithmetic",
8605 } else if (is_type_function(points_to)) {
8607 errorf(source_position,
8608 "arithmetic with pointer to function type '%T' not allowed",
8611 } else if (warning.pointer_arith) {
8612 warningf(source_position,
8613 "pointer to a function '%T' used in arithmetic",
8620 static bool is_lvalue(const expression_t *expression)
8622 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8623 switch (expression->kind) {
8624 case EXPR_ARRAY_ACCESS:
8625 case EXPR_COMPOUND_LITERAL:
8626 case EXPR_REFERENCE:
8628 case EXPR_UNARY_DEREFERENCE:
8632 type_t *type = skip_typeref(expression->base.type);
8634 /* ISO/IEC 14882:1998(E) §3.10:3 */
8635 is_type_reference(type) ||
8636 /* Claim it is an lvalue, if the type is invalid. There was a parse
8637 * error before, which maybe prevented properly recognizing it as
8639 !is_type_valid(type);
8644 static void semantic_incdec(unary_expression_t *expression)
8646 type_t *const orig_type = expression->value->base.type;
8647 type_t *const type = skip_typeref(orig_type);
8648 if (is_type_pointer(type)) {
8649 if (!check_pointer_arithmetic(&expression->base.source_position,
8653 } else if (!is_type_real(type) && is_type_valid(type)) {
8654 /* TODO: improve error message */
8655 errorf(&expression->base.source_position,
8656 "operation needs an arithmetic or pointer type");
8659 if (!is_lvalue(expression->value)) {
8660 /* TODO: improve error message */
8661 errorf(&expression->base.source_position, "lvalue required as operand");
8663 expression->base.type = orig_type;
8666 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8668 type_t *const orig_type = expression->value->base.type;
8669 type_t *const type = skip_typeref(orig_type);
8670 if (!is_type_arithmetic(type)) {
8671 if (is_type_valid(type)) {
8672 /* TODO: improve error message */
8673 errorf(&expression->base.source_position,
8674 "operation needs an arithmetic type");
8679 expression->base.type = orig_type;
8682 static void semantic_unexpr_plus(unary_expression_t *expression)
8684 semantic_unexpr_arithmetic(expression);
8685 if (warning.traditional)
8686 warningf(&expression->base.source_position,
8687 "traditional C rejects the unary plus operator");
8690 static void semantic_not(unary_expression_t *expression)
8692 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8693 semantic_condition(expression->value, "operand of !");
8694 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8697 static void semantic_unexpr_integer(unary_expression_t *expression)
8699 type_t *const orig_type = expression->value->base.type;
8700 type_t *const type = skip_typeref(orig_type);
8701 if (!is_type_integer(type)) {
8702 if (is_type_valid(type)) {
8703 errorf(&expression->base.source_position,
8704 "operand of ~ must be of integer type");
8709 expression->base.type = orig_type;
8712 static void semantic_dereference(unary_expression_t *expression)
8714 type_t *const orig_type = expression->value->base.type;
8715 type_t *const type = skip_typeref(orig_type);
8716 if (!is_type_pointer(type)) {
8717 if (is_type_valid(type)) {
8718 errorf(&expression->base.source_position,
8719 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8724 type_t *result_type = type->pointer.points_to;
8725 result_type = automatic_type_conversion(result_type);
8726 expression->base.type = result_type;
8730 * Record that an address is taken (expression represents an lvalue).
8732 * @param expression the expression
8733 * @param may_be_register if true, the expression might be an register
8735 static void set_address_taken(expression_t *expression, bool may_be_register)
8737 if (expression->kind != EXPR_REFERENCE)
8740 entity_t *const entity = expression->reference.entity;
8742 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8745 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8746 && !may_be_register) {
8747 errorf(&expression->base.source_position,
8748 "address of register %s '%Y' requested",
8749 get_entity_kind_name(entity->kind), entity->base.symbol);
8752 if (entity->kind == ENTITY_VARIABLE) {
8753 entity->variable.address_taken = true;
8755 assert(entity->kind == ENTITY_PARAMETER);
8756 entity->parameter.address_taken = true;
8761 * Check the semantic of the address taken expression.
8763 static void semantic_take_addr(unary_expression_t *expression)
8765 expression_t *value = expression->value;
8766 value->base.type = revert_automatic_type_conversion(value);
8768 type_t *orig_type = value->base.type;
8769 type_t *type = skip_typeref(orig_type);
8770 if (!is_type_valid(type))
8774 if (!is_lvalue(value)) {
8775 errorf(&expression->base.source_position, "'&' requires an lvalue");
8777 if (type->kind == TYPE_BITFIELD) {
8778 errorf(&expression->base.source_position,
8779 "'&' not allowed on object with bitfield type '%T'",
8783 set_address_taken(value, false);
8785 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8788 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8789 static expression_t *parse_##unexpression_type(void) \
8791 expression_t *unary_expression \
8792 = allocate_expression_zero(unexpression_type); \
8794 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8796 sfunc(&unary_expression->unary); \
8798 return unary_expression; \
8801 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8802 semantic_unexpr_arithmetic)
8803 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8804 semantic_unexpr_plus)
8805 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8807 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8808 semantic_dereference)
8809 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8811 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8812 semantic_unexpr_integer)
8813 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8815 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8818 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8820 static expression_t *parse_##unexpression_type(expression_t *left) \
8822 expression_t *unary_expression \
8823 = allocate_expression_zero(unexpression_type); \
8825 unary_expression->unary.value = left; \
8827 sfunc(&unary_expression->unary); \
8829 return unary_expression; \
8832 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8833 EXPR_UNARY_POSTFIX_INCREMENT,
8835 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8836 EXPR_UNARY_POSTFIX_DECREMENT,
8839 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8841 /* TODO: handle complex + imaginary types */
8843 type_left = get_unqualified_type(type_left);
8844 type_right = get_unqualified_type(type_right);
8846 /* § 6.3.1.8 Usual arithmetic conversions */
8847 if (type_left == type_long_double || type_right == type_long_double) {
8848 return type_long_double;
8849 } else if (type_left == type_double || type_right == type_double) {
8851 } else if (type_left == type_float || type_right == type_float) {
8855 type_left = promote_integer(type_left);
8856 type_right = promote_integer(type_right);
8858 if (type_left == type_right)
8861 bool const signed_left = is_type_signed(type_left);
8862 bool const signed_right = is_type_signed(type_right);
8863 int const rank_left = get_rank(type_left);
8864 int const rank_right = get_rank(type_right);
8866 if (signed_left == signed_right)
8867 return rank_left >= rank_right ? type_left : type_right;
8876 u_rank = rank_right;
8877 u_type = type_right;
8879 s_rank = rank_right;
8880 s_type = type_right;
8885 if (u_rank >= s_rank)
8888 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8890 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8891 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8895 case ATOMIC_TYPE_INT: return type_unsigned_int;
8896 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8897 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8899 default: panic("invalid atomic type");
8904 * Check the semantic restrictions for a binary expression.
8906 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8908 expression_t *const left = expression->left;
8909 expression_t *const right = expression->right;
8910 type_t *const orig_type_left = left->base.type;
8911 type_t *const orig_type_right = right->base.type;
8912 type_t *const type_left = skip_typeref(orig_type_left);
8913 type_t *const type_right = skip_typeref(orig_type_right);
8915 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8916 /* TODO: improve error message */
8917 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8918 errorf(&expression->base.source_position,
8919 "operation needs arithmetic types");
8924 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8925 expression->left = create_implicit_cast(left, arithmetic_type);
8926 expression->right = create_implicit_cast(right, arithmetic_type);
8927 expression->base.type = arithmetic_type;
8930 static void warn_div_by_zero(binary_expression_t const *const expression)
8932 if (!warning.div_by_zero ||
8933 !is_type_integer(expression->base.type))
8936 expression_t const *const right = expression->right;
8937 /* The type of the right operand can be different for /= */
8938 if (is_type_integer(right->base.type) &&
8939 is_constant_expression(right) &&
8940 fold_constant(right) == 0) {
8941 warningf(&expression->base.source_position, "division by zero");
8946 * Check the semantic restrictions for a div/mod expression.
8948 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8950 semantic_binexpr_arithmetic(expression);
8951 warn_div_by_zero(expression);
8954 static void warn_addsub_in_shift(const expression_t *const expr)
8956 if (expr->base.parenthesized)
8960 switch (expr->kind) {
8961 case EXPR_BINARY_ADD: op = '+'; break;
8962 case EXPR_BINARY_SUB: op = '-'; break;
8966 warningf(&expr->base.source_position,
8967 "suggest parentheses around '%c' inside shift", op);
8970 static void semantic_shift_op(binary_expression_t *expression)
8972 expression_t *const left = expression->left;
8973 expression_t *const right = expression->right;
8974 type_t *const orig_type_left = left->base.type;
8975 type_t *const orig_type_right = right->base.type;
8976 type_t * type_left = skip_typeref(orig_type_left);
8977 type_t * type_right = skip_typeref(orig_type_right);
8979 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8980 /* TODO: improve error message */
8981 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8982 errorf(&expression->base.source_position,
8983 "operands of shift operation must have integer types");
8988 if (warning.parentheses) {
8989 warn_addsub_in_shift(left);
8990 warn_addsub_in_shift(right);
8993 type_left = promote_integer(type_left);
8994 type_right = promote_integer(type_right);
8996 expression->left = create_implicit_cast(left, type_left);
8997 expression->right = create_implicit_cast(right, type_right);
8998 expression->base.type = type_left;
9001 static void semantic_add(binary_expression_t *expression)
9003 expression_t *const left = expression->left;
9004 expression_t *const right = expression->right;
9005 type_t *const orig_type_left = left->base.type;
9006 type_t *const orig_type_right = right->base.type;
9007 type_t *const type_left = skip_typeref(orig_type_left);
9008 type_t *const type_right = skip_typeref(orig_type_right);
9011 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9012 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9013 expression->left = create_implicit_cast(left, arithmetic_type);
9014 expression->right = create_implicit_cast(right, arithmetic_type);
9015 expression->base.type = arithmetic_type;
9016 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9017 check_pointer_arithmetic(&expression->base.source_position,
9018 type_left, orig_type_left);
9019 expression->base.type = type_left;
9020 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
9021 check_pointer_arithmetic(&expression->base.source_position,
9022 type_right, orig_type_right);
9023 expression->base.type = type_right;
9024 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9025 errorf(&expression->base.source_position,
9026 "invalid operands to binary + ('%T', '%T')",
9027 orig_type_left, orig_type_right);
9031 static void semantic_sub(binary_expression_t *expression)
9033 expression_t *const left = expression->left;
9034 expression_t *const right = expression->right;
9035 type_t *const orig_type_left = left->base.type;
9036 type_t *const orig_type_right = right->base.type;
9037 type_t *const type_left = skip_typeref(orig_type_left);
9038 type_t *const type_right = skip_typeref(orig_type_right);
9039 source_position_t const *const pos = &expression->base.source_position;
9042 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9043 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9044 expression->left = create_implicit_cast(left, arithmetic_type);
9045 expression->right = create_implicit_cast(right, arithmetic_type);
9046 expression->base.type = arithmetic_type;
9047 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9048 check_pointer_arithmetic(&expression->base.source_position,
9049 type_left, orig_type_left);
9050 expression->base.type = type_left;
9051 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9052 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
9053 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
9054 if (!types_compatible(unqual_left, unqual_right)) {
9056 "subtracting pointers to incompatible types '%T' and '%T'",
9057 orig_type_left, orig_type_right);
9058 } else if (!is_type_object(unqual_left)) {
9059 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
9060 errorf(pos, "subtracting pointers to non-object types '%T'",
9062 } else if (warning.other) {
9063 warningf(pos, "subtracting pointers to void");
9066 expression->base.type = type_ptrdiff_t;
9067 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9068 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
9069 orig_type_left, orig_type_right);
9073 static void warn_string_literal_address(expression_t const* expr)
9075 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
9076 expr = expr->unary.value;
9077 if (expr->kind != EXPR_UNARY_DEREFERENCE)
9079 expr = expr->unary.value;
9082 if (expr->kind == EXPR_STRING_LITERAL ||
9083 expr->kind == EXPR_WIDE_STRING_LITERAL) {
9084 warningf(&expr->base.source_position,
9085 "comparison with string literal results in unspecified behaviour");
9089 static void warn_comparison_in_comparison(const expression_t *const expr)
9091 if (expr->base.parenthesized)
9093 switch (expr->base.kind) {
9094 case EXPR_BINARY_LESS:
9095 case EXPR_BINARY_GREATER:
9096 case EXPR_BINARY_LESSEQUAL:
9097 case EXPR_BINARY_GREATEREQUAL:
9098 case EXPR_BINARY_NOTEQUAL:
9099 case EXPR_BINARY_EQUAL:
9100 warningf(&expr->base.source_position,
9101 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9108 static bool maybe_negative(expression_t const *const expr)
9111 !is_constant_expression(expr) ||
9112 fold_constant(expr) < 0;
9116 * Check the semantics of comparison expressions.
9118 * @param expression The expression to check.
9120 static void semantic_comparison(binary_expression_t *expression)
9122 expression_t *left = expression->left;
9123 expression_t *right = expression->right;
9125 if (warning.address) {
9126 warn_string_literal_address(left);
9127 warn_string_literal_address(right);
9129 expression_t const* const func_left = get_reference_address(left);
9130 if (func_left != NULL && is_null_pointer_constant(right)) {
9131 warningf(&expression->base.source_position,
9132 "the address of '%Y' will never be NULL",
9133 func_left->reference.entity->base.symbol);
9136 expression_t const* const func_right = get_reference_address(right);
9137 if (func_right != NULL && is_null_pointer_constant(right)) {
9138 warningf(&expression->base.source_position,
9139 "the address of '%Y' will never be NULL",
9140 func_right->reference.entity->base.symbol);
9144 if (warning.parentheses) {
9145 warn_comparison_in_comparison(left);
9146 warn_comparison_in_comparison(right);
9149 type_t *orig_type_left = left->base.type;
9150 type_t *orig_type_right = right->base.type;
9151 type_t *type_left = skip_typeref(orig_type_left);
9152 type_t *type_right = skip_typeref(orig_type_right);
9154 /* TODO non-arithmetic types */
9155 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9156 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9158 /* test for signed vs unsigned compares */
9159 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9160 bool const signed_left = is_type_signed(type_left);
9161 bool const signed_right = is_type_signed(type_right);
9162 if (signed_left != signed_right) {
9163 /* FIXME long long needs better const folding magic */
9164 /* TODO check whether constant value can be represented by other type */
9165 if ((signed_left && maybe_negative(left)) ||
9166 (signed_right && maybe_negative(right))) {
9167 warningf(&expression->base.source_position,
9168 "comparison between signed and unsigned");
9173 expression->left = create_implicit_cast(left, arithmetic_type);
9174 expression->right = create_implicit_cast(right, arithmetic_type);
9175 expression->base.type = arithmetic_type;
9176 if (warning.float_equal &&
9177 (expression->base.kind == EXPR_BINARY_EQUAL ||
9178 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9179 is_type_float(arithmetic_type)) {
9180 warningf(&expression->base.source_position,
9181 "comparing floating point with == or != is unsafe");
9183 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9184 /* TODO check compatibility */
9185 } else if (is_type_pointer(type_left)) {
9186 expression->right = create_implicit_cast(right, type_left);
9187 } else if (is_type_pointer(type_right)) {
9188 expression->left = create_implicit_cast(left, type_right);
9189 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9190 type_error_incompatible("invalid operands in comparison",
9191 &expression->base.source_position,
9192 type_left, type_right);
9194 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9198 * Checks if a compound type has constant fields.
9200 static bool has_const_fields(const compound_type_t *type)
9202 compound_t *compound = type->compound;
9203 entity_t *entry = compound->members.entities;
9205 for (; entry != NULL; entry = entry->base.next) {
9206 if (!is_declaration(entry))
9209 const type_t *decl_type = skip_typeref(entry->declaration.type);
9210 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9217 static bool is_valid_assignment_lhs(expression_t const* const left)
9219 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9220 type_t *const type_left = skip_typeref(orig_type_left);
9222 if (!is_lvalue(left)) {
9223 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9228 if (left->kind == EXPR_REFERENCE
9229 && left->reference.entity->kind == ENTITY_FUNCTION) {
9230 errorf(HERE, "cannot assign to function '%E'", left);
9234 if (is_type_array(type_left)) {
9235 errorf(HERE, "cannot assign to array '%E'", left);
9238 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9239 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9243 if (is_type_incomplete(type_left)) {
9244 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9245 left, orig_type_left);
9248 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9249 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9250 left, orig_type_left);
9257 static void semantic_arithmetic_assign(binary_expression_t *expression)
9259 expression_t *left = expression->left;
9260 expression_t *right = expression->right;
9261 type_t *orig_type_left = left->base.type;
9262 type_t *orig_type_right = right->base.type;
9264 if (!is_valid_assignment_lhs(left))
9267 type_t *type_left = skip_typeref(orig_type_left);
9268 type_t *type_right = skip_typeref(orig_type_right);
9270 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9271 /* TODO: improve error message */
9272 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9273 errorf(&expression->base.source_position,
9274 "operation needs arithmetic types");
9279 /* combined instructions are tricky. We can't create an implicit cast on
9280 * the left side, because we need the uncasted form for the store.
9281 * The ast2firm pass has to know that left_type must be right_type
9282 * for the arithmetic operation and create a cast by itself */
9283 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9284 expression->right = create_implicit_cast(right, arithmetic_type);
9285 expression->base.type = type_left;
9288 static void semantic_divmod_assign(binary_expression_t *expression)
9290 semantic_arithmetic_assign(expression);
9291 warn_div_by_zero(expression);
9294 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9296 expression_t *const left = expression->left;
9297 expression_t *const right = expression->right;
9298 type_t *const orig_type_left = left->base.type;
9299 type_t *const orig_type_right = right->base.type;
9300 type_t *const type_left = skip_typeref(orig_type_left);
9301 type_t *const type_right = skip_typeref(orig_type_right);
9303 if (!is_valid_assignment_lhs(left))
9306 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9307 /* combined instructions are tricky. We can't create an implicit cast on
9308 * the left side, because we need the uncasted form for the store.
9309 * The ast2firm pass has to know that left_type must be right_type
9310 * for the arithmetic operation and create a cast by itself */
9311 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9312 expression->right = create_implicit_cast(right, arithmetic_type);
9313 expression->base.type = type_left;
9314 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9315 check_pointer_arithmetic(&expression->base.source_position,
9316 type_left, orig_type_left);
9317 expression->base.type = type_left;
9318 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9319 errorf(&expression->base.source_position,
9320 "incompatible types '%T' and '%T' in assignment",
9321 orig_type_left, orig_type_right);
9325 static void warn_logical_and_within_or(const expression_t *const expr)
9327 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9329 if (expr->base.parenthesized)
9331 warningf(&expr->base.source_position,
9332 "suggest parentheses around && within ||");
9336 * Check the semantic restrictions of a logical expression.
9338 static void semantic_logical_op(binary_expression_t *expression)
9340 /* §6.5.13:2 Each of the operands shall have scalar type.
9341 * §6.5.14:2 Each of the operands shall have scalar type. */
9342 semantic_condition(expression->left, "left operand of logical operator");
9343 semantic_condition(expression->right, "right operand of logical operator");
9344 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9345 warning.parentheses) {
9346 warn_logical_and_within_or(expression->left);
9347 warn_logical_and_within_or(expression->right);
9349 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9353 * Check the semantic restrictions of a binary assign expression.
9355 static void semantic_binexpr_assign(binary_expression_t *expression)
9357 expression_t *left = expression->left;
9358 type_t *orig_type_left = left->base.type;
9360 if (!is_valid_assignment_lhs(left))
9363 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9364 report_assign_error(error, orig_type_left, expression->right,
9365 "assignment", &left->base.source_position);
9366 expression->right = create_implicit_cast(expression->right, orig_type_left);
9367 expression->base.type = orig_type_left;
9371 * Determine if the outermost operation (or parts thereof) of the given
9372 * expression has no effect in order to generate a warning about this fact.
9373 * Therefore in some cases this only examines some of the operands of the
9374 * expression (see comments in the function and examples below).
9376 * f() + 23; // warning, because + has no effect
9377 * x || f(); // no warning, because x controls execution of f()
9378 * x ? y : f(); // warning, because y has no effect
9379 * (void)x; // no warning to be able to suppress the warning
9380 * This function can NOT be used for an "expression has definitely no effect"-
9382 static bool expression_has_effect(const expression_t *const expr)
9384 switch (expr->kind) {
9385 case EXPR_UNKNOWN: break;
9386 case EXPR_INVALID: return true; /* do NOT warn */
9387 case EXPR_REFERENCE: return false;
9388 case EXPR_REFERENCE_ENUM_VALUE: return false;
9389 /* suppress the warning for microsoft __noop operations */
9390 case EXPR_CONST: return expr->conste.is_ms_noop;
9391 case EXPR_CHARACTER_CONSTANT: return false;
9392 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9393 case EXPR_STRING_LITERAL: return false;
9394 case EXPR_WIDE_STRING_LITERAL: return false;
9395 case EXPR_LABEL_ADDRESS: return false;
9398 const call_expression_t *const call = &expr->call;
9399 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9402 switch (call->function->builtin_symbol.symbol->ID) {
9403 case T___builtin_va_end: return true;
9404 default: return false;
9408 /* Generate the warning if either the left or right hand side of a
9409 * conditional expression has no effect */
9410 case EXPR_CONDITIONAL: {
9411 conditional_expression_t const *const cond = &expr->conditional;
9412 expression_t const *const t = cond->true_expression;
9414 (t == NULL || expression_has_effect(t)) &&
9415 expression_has_effect(cond->false_expression);
9418 case EXPR_SELECT: return false;
9419 case EXPR_ARRAY_ACCESS: return false;
9420 case EXPR_SIZEOF: return false;
9421 case EXPR_CLASSIFY_TYPE: return false;
9422 case EXPR_ALIGNOF: return false;
9424 case EXPR_FUNCNAME: return false;
9425 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9426 case EXPR_BUILTIN_CONSTANT_P: return false;
9427 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
9428 case EXPR_BUILTIN_PREFETCH: return true;
9429 case EXPR_OFFSETOF: return false;
9430 case EXPR_VA_START: return true;
9431 case EXPR_VA_ARG: return true;
9432 case EXPR_STATEMENT: return true; // TODO
9433 case EXPR_COMPOUND_LITERAL: return false;
9435 case EXPR_UNARY_NEGATE: return false;
9436 case EXPR_UNARY_PLUS: return false;
9437 case EXPR_UNARY_BITWISE_NEGATE: return false;
9438 case EXPR_UNARY_NOT: return false;
9439 case EXPR_UNARY_DEREFERENCE: return false;
9440 case EXPR_UNARY_TAKE_ADDRESS: return false;
9441 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9442 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9443 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9444 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9446 /* Treat void casts as if they have an effect in order to being able to
9447 * suppress the warning */
9448 case EXPR_UNARY_CAST: {
9449 type_t *const type = skip_typeref(expr->base.type);
9450 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9453 case EXPR_UNARY_CAST_IMPLICIT: return true;
9454 case EXPR_UNARY_ASSUME: return true;
9455 case EXPR_UNARY_DELETE: return true;
9456 case EXPR_UNARY_DELETE_ARRAY: return true;
9457 case EXPR_UNARY_THROW: return true;
9459 case EXPR_BINARY_ADD: return false;
9460 case EXPR_BINARY_SUB: return false;
9461 case EXPR_BINARY_MUL: return false;
9462 case EXPR_BINARY_DIV: return false;
9463 case EXPR_BINARY_MOD: return false;
9464 case EXPR_BINARY_EQUAL: return false;
9465 case EXPR_BINARY_NOTEQUAL: return false;
9466 case EXPR_BINARY_LESS: return false;
9467 case EXPR_BINARY_LESSEQUAL: return false;
9468 case EXPR_BINARY_GREATER: return false;
9469 case EXPR_BINARY_GREATEREQUAL: return false;
9470 case EXPR_BINARY_BITWISE_AND: return false;
9471 case EXPR_BINARY_BITWISE_OR: return false;
9472 case EXPR_BINARY_BITWISE_XOR: return false;
9473 case EXPR_BINARY_SHIFTLEFT: return false;
9474 case EXPR_BINARY_SHIFTRIGHT: return false;
9475 case EXPR_BINARY_ASSIGN: return true;
9476 case EXPR_BINARY_MUL_ASSIGN: return true;
9477 case EXPR_BINARY_DIV_ASSIGN: return true;
9478 case EXPR_BINARY_MOD_ASSIGN: return true;
9479 case EXPR_BINARY_ADD_ASSIGN: return true;
9480 case EXPR_BINARY_SUB_ASSIGN: return true;
9481 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9482 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9483 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9484 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9485 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9487 /* Only examine the right hand side of && and ||, because the left hand
9488 * side already has the effect of controlling the execution of the right
9490 case EXPR_BINARY_LOGICAL_AND:
9491 case EXPR_BINARY_LOGICAL_OR:
9492 /* Only examine the right hand side of a comma expression, because the left
9493 * hand side has a separate warning */
9494 case EXPR_BINARY_COMMA:
9495 return expression_has_effect(expr->binary.right);
9497 case EXPR_BINARY_ISGREATER: return false;
9498 case EXPR_BINARY_ISGREATEREQUAL: return false;
9499 case EXPR_BINARY_ISLESS: return false;
9500 case EXPR_BINARY_ISLESSEQUAL: return false;
9501 case EXPR_BINARY_ISLESSGREATER: return false;
9502 case EXPR_BINARY_ISUNORDERED: return false;
9505 internal_errorf(HERE, "unexpected expression");
9508 static void semantic_comma(binary_expression_t *expression)
9510 if (warning.unused_value) {
9511 const expression_t *const left = expression->left;
9512 if (!expression_has_effect(left)) {
9513 warningf(&left->base.source_position,
9514 "left-hand operand of comma expression has no effect");
9517 expression->base.type = expression->right->base.type;
9521 * @param prec_r precedence of the right operand
9523 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9524 static expression_t *parse_##binexpression_type(expression_t *left) \
9526 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9527 binexpr->binary.left = left; \
9530 expression_t *right = parse_sub_expression(prec_r); \
9532 binexpr->binary.right = right; \
9533 sfunc(&binexpr->binary); \
9538 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9539 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9540 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9541 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9542 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9543 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9544 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9545 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9546 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9547 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9548 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9549 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9550 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9551 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9552 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9553 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9554 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9555 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9556 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9557 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9558 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9559 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9560 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9561 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9562 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9563 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9564 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9565 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9566 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9567 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9570 static expression_t *parse_sub_expression(precedence_t precedence)
9572 if (token.type < 0) {
9573 return expected_expression_error();
9576 expression_parser_function_t *parser
9577 = &expression_parsers[token.type];
9578 source_position_t source_position = token.source_position;
9581 if (parser->parser != NULL) {
9582 left = parser->parser();
9584 left = parse_primary_expression();
9586 assert(left != NULL);
9587 left->base.source_position = source_position;
9590 if (token.type < 0) {
9591 return expected_expression_error();
9594 parser = &expression_parsers[token.type];
9595 if (parser->infix_parser == NULL)
9597 if (parser->infix_precedence < precedence)
9600 left = parser->infix_parser(left);
9602 assert(left != NULL);
9603 assert(left->kind != EXPR_UNKNOWN);
9604 left->base.source_position = source_position;
9611 * Parse an expression.
9613 static expression_t *parse_expression(void)
9615 return parse_sub_expression(PREC_EXPRESSION);
9619 * Register a parser for a prefix-like operator.
9621 * @param parser the parser function
9622 * @param token_type the token type of the prefix token
9624 static void register_expression_parser(parse_expression_function parser,
9627 expression_parser_function_t *entry = &expression_parsers[token_type];
9629 if (entry->parser != NULL) {
9630 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9631 panic("trying to register multiple expression parsers for a token");
9633 entry->parser = parser;
9637 * Register a parser for an infix operator with given precedence.
9639 * @param parser the parser function
9640 * @param token_type the token type of the infix operator
9641 * @param precedence the precedence of the operator
9643 static void register_infix_parser(parse_expression_infix_function parser,
9644 int token_type, precedence_t precedence)
9646 expression_parser_function_t *entry = &expression_parsers[token_type];
9648 if (entry->infix_parser != NULL) {
9649 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9650 panic("trying to register multiple infix expression parsers for a "
9653 entry->infix_parser = parser;
9654 entry->infix_precedence = precedence;
9658 * Initialize the expression parsers.
9660 static void init_expression_parsers(void)
9662 memset(&expression_parsers, 0, sizeof(expression_parsers));
9664 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9665 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9666 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9667 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9668 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9669 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9670 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9671 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9672 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9673 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9674 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9675 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9676 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9677 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9678 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9679 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9680 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9681 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9682 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9683 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9684 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9685 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9686 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9687 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9688 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9689 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9690 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9691 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9692 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9693 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9694 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9695 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9696 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9697 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9698 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9699 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9700 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9702 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9703 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9704 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9705 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9706 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9707 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9708 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9709 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9710 register_expression_parser(parse_sizeof, T_sizeof);
9711 register_expression_parser(parse_alignof, T___alignof__);
9712 register_expression_parser(parse_extension, T___extension__);
9713 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9714 register_expression_parser(parse_delete, T_delete);
9715 register_expression_parser(parse_throw, T_throw);
9719 * Parse a asm statement arguments specification.
9721 static asm_argument_t *parse_asm_arguments(bool is_out)
9723 asm_argument_t *result = NULL;
9724 asm_argument_t **anchor = &result;
9726 while (token.type == T_STRING_LITERAL || token.type == '[') {
9727 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9728 memset(argument, 0, sizeof(argument[0]));
9730 if (token.type == '[') {
9732 if (token.type != T_IDENTIFIER) {
9733 parse_error_expected("while parsing asm argument",
9734 T_IDENTIFIER, NULL);
9737 argument->symbol = token.v.symbol;
9739 expect(']', end_error);
9742 argument->constraints = parse_string_literals();
9743 expect('(', end_error);
9744 add_anchor_token(')');
9745 expression_t *expression = parse_expression();
9746 rem_anchor_token(')');
9748 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9749 * change size or type representation (e.g. int -> long is ok, but
9750 * int -> float is not) */
9751 if (expression->kind == EXPR_UNARY_CAST) {
9752 type_t *const type = expression->base.type;
9753 type_kind_t const kind = type->kind;
9754 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9757 if (kind == TYPE_ATOMIC) {
9758 atomic_type_kind_t const akind = type->atomic.akind;
9759 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9760 size = get_atomic_type_size(akind);
9762 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9763 size = get_atomic_type_size(get_intptr_kind());
9767 expression_t *const value = expression->unary.value;
9768 type_t *const value_type = value->base.type;
9769 type_kind_t const value_kind = value_type->kind;
9771 unsigned value_flags;
9772 unsigned value_size;
9773 if (value_kind == TYPE_ATOMIC) {
9774 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9775 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9776 value_size = get_atomic_type_size(value_akind);
9777 } else if (value_kind == TYPE_POINTER) {
9778 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9779 value_size = get_atomic_type_size(get_intptr_kind());
9784 if (value_flags != flags || value_size != size)
9788 } while (expression->kind == EXPR_UNARY_CAST);
9792 if (!is_lvalue(expression)) {
9793 errorf(&expression->base.source_position,
9794 "asm output argument is not an lvalue");
9797 if (argument->constraints.begin[0] == '+')
9798 mark_vars_read(expression, NULL);
9800 mark_vars_read(expression, NULL);
9802 argument->expression = expression;
9803 expect(')', end_error);
9805 set_address_taken(expression, true);
9808 anchor = &argument->next;
9810 if (token.type != ',')
9821 * Parse a asm statement clobber specification.
9823 static asm_clobber_t *parse_asm_clobbers(void)
9825 asm_clobber_t *result = NULL;
9826 asm_clobber_t *last = NULL;
9828 while (token.type == T_STRING_LITERAL) {
9829 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9830 clobber->clobber = parse_string_literals();
9833 last->next = clobber;
9839 if (token.type != ',')
9848 * Parse an asm statement.
9850 static statement_t *parse_asm_statement(void)
9852 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9853 asm_statement_t *asm_statement = &statement->asms;
9857 if (token.type == T_volatile) {
9859 asm_statement->is_volatile = true;
9862 expect('(', end_error);
9863 add_anchor_token(')');
9864 add_anchor_token(':');
9865 asm_statement->asm_text = parse_string_literals();
9867 if (token.type != ':') {
9868 rem_anchor_token(':');
9873 asm_statement->outputs = parse_asm_arguments(true);
9874 if (token.type != ':') {
9875 rem_anchor_token(':');
9880 asm_statement->inputs = parse_asm_arguments(false);
9881 if (token.type != ':') {
9882 rem_anchor_token(':');
9885 rem_anchor_token(':');
9888 asm_statement->clobbers = parse_asm_clobbers();
9891 rem_anchor_token(')');
9892 expect(')', end_error);
9893 expect(';', end_error);
9895 if (asm_statement->outputs == NULL) {
9896 /* GCC: An 'asm' instruction without any output operands will be treated
9897 * identically to a volatile 'asm' instruction. */
9898 asm_statement->is_volatile = true;
9903 return create_invalid_statement();
9907 * Parse a case statement.
9909 static statement_t *parse_case_statement(void)
9911 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9912 source_position_t *const pos = &statement->base.source_position;
9916 expression_t *const expression = parse_expression();
9917 statement->case_label.expression = expression;
9918 if (!is_constant_expression(expression)) {
9919 /* This check does not prevent the error message in all cases of an
9920 * prior error while parsing the expression. At least it catches the
9921 * common case of a mistyped enum entry. */
9922 if (is_type_valid(skip_typeref(expression->base.type))) {
9923 errorf(pos, "case label does not reduce to an integer constant");
9925 statement->case_label.is_bad = true;
9927 long const val = fold_constant(expression);
9928 statement->case_label.first_case = val;
9929 statement->case_label.last_case = val;
9933 if (token.type == T_DOTDOTDOT) {
9935 expression_t *const end_range = parse_expression();
9936 statement->case_label.end_range = end_range;
9937 if (!is_constant_expression(end_range)) {
9938 /* This check does not prevent the error message in all cases of an
9939 * prior error while parsing the expression. At least it catches the
9940 * common case of a mistyped enum entry. */
9941 if (is_type_valid(skip_typeref(end_range->base.type))) {
9942 errorf(pos, "case range does not reduce to an integer constant");
9944 statement->case_label.is_bad = true;
9946 long const val = fold_constant(end_range);
9947 statement->case_label.last_case = val;
9949 if (warning.other && val < statement->case_label.first_case) {
9950 statement->case_label.is_empty_range = true;
9951 warningf(pos, "empty range specified");
9957 PUSH_PARENT(statement);
9959 expect(':', end_error);
9962 if (current_switch != NULL) {
9963 if (! statement->case_label.is_bad) {
9964 /* Check for duplicate case values */
9965 case_label_statement_t *c = &statement->case_label;
9966 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9967 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9970 if (c->last_case < l->first_case || c->first_case > l->last_case)
9973 errorf(pos, "duplicate case value (previously used %P)",
9974 &l->base.source_position);
9978 /* link all cases into the switch statement */
9979 if (current_switch->last_case == NULL) {
9980 current_switch->first_case = &statement->case_label;
9982 current_switch->last_case->next = &statement->case_label;
9984 current_switch->last_case = &statement->case_label;
9986 errorf(pos, "case label not within a switch statement");
9989 statement_t *const inner_stmt = parse_statement();
9990 statement->case_label.statement = inner_stmt;
9991 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9992 errorf(&inner_stmt->base.source_position, "declaration after case label");
10000 * Parse a default statement.
10002 static statement_t *parse_default_statement(void)
10004 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
10008 PUSH_PARENT(statement);
10010 expect(':', end_error);
10011 if (current_switch != NULL) {
10012 const case_label_statement_t *def_label = current_switch->default_label;
10013 if (def_label != NULL) {
10014 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
10015 &def_label->base.source_position);
10017 current_switch->default_label = &statement->case_label;
10019 /* link all cases into the switch statement */
10020 if (current_switch->last_case == NULL) {
10021 current_switch->first_case = &statement->case_label;
10023 current_switch->last_case->next = &statement->case_label;
10025 current_switch->last_case = &statement->case_label;
10028 errorf(&statement->base.source_position,
10029 "'default' label not within a switch statement");
10032 statement_t *const inner_stmt = parse_statement();
10033 statement->case_label.statement = inner_stmt;
10034 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10035 errorf(&inner_stmt->base.source_position, "declaration after default label");
10042 return create_invalid_statement();
10046 * Parse a label statement.
10048 static statement_t *parse_label_statement(void)
10050 assert(token.type == T_IDENTIFIER);
10051 symbol_t *symbol = token.v.symbol;
10052 label_t *label = get_label(symbol);
10054 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
10055 statement->label.label = label;
10059 PUSH_PARENT(statement);
10061 /* if statement is already set then the label is defined twice,
10062 * otherwise it was just mentioned in a goto/local label declaration so far
10064 if (label->statement != NULL) {
10065 errorf(HERE, "duplicate label '%Y' (declared %P)",
10066 symbol, &label->base.source_position);
10068 label->base.source_position = token.source_position;
10069 label->statement = statement;
10074 if (token.type == '}') {
10075 /* TODO only warn? */
10076 if (warning.other && false) {
10077 warningf(HERE, "label at end of compound statement");
10078 statement->label.statement = create_empty_statement();
10080 errorf(HERE, "label at end of compound statement");
10081 statement->label.statement = create_invalid_statement();
10083 } else if (token.type == ';') {
10084 /* Eat an empty statement here, to avoid the warning about an empty
10085 * statement after a label. label:; is commonly used to have a label
10086 * before a closing brace. */
10087 statement->label.statement = create_empty_statement();
10090 statement_t *const inner_stmt = parse_statement();
10091 statement->label.statement = inner_stmt;
10092 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10093 errorf(&inner_stmt->base.source_position, "declaration after label");
10097 /* remember the labels in a list for later checking */
10098 *label_anchor = &statement->label;
10099 label_anchor = &statement->label.next;
10106 * Parse an if statement.
10108 static statement_t *parse_if(void)
10110 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10114 PUSH_PARENT(statement);
10116 add_anchor_token('{');
10118 expect('(', end_error);
10119 add_anchor_token(')');
10120 expression_t *const expr = parse_expression();
10121 statement->ifs.condition = expr;
10122 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10124 semantic_condition(expr, "condition of 'if'-statment");
10125 mark_vars_read(expr, NULL);
10126 rem_anchor_token(')');
10127 expect(')', end_error);
10130 rem_anchor_token('{');
10132 add_anchor_token(T_else);
10133 statement_t *const true_stmt = parse_statement();
10134 statement->ifs.true_statement = true_stmt;
10135 rem_anchor_token(T_else);
10137 if (token.type == T_else) {
10139 statement->ifs.false_statement = parse_statement();
10140 } else if (warning.parentheses &&
10141 true_stmt->kind == STATEMENT_IF &&
10142 true_stmt->ifs.false_statement != NULL) {
10143 warningf(&true_stmt->base.source_position,
10144 "suggest explicit braces to avoid ambiguous 'else'");
10152 * Check that all enums are handled in a switch.
10154 * @param statement the switch statement to check
10156 static void check_enum_cases(const switch_statement_t *statement)
10158 const type_t *type = skip_typeref(statement->expression->base.type);
10159 if (! is_type_enum(type))
10161 const enum_type_t *enumt = &type->enumt;
10163 /* if we have a default, no warnings */
10164 if (statement->default_label != NULL)
10167 /* FIXME: calculation of value should be done while parsing */
10168 /* TODO: quadratic algorithm here. Change to an n log n one */
10169 long last_value = -1;
10170 const entity_t *entry = enumt->enume->base.next;
10171 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10172 entry = entry->base.next) {
10173 const expression_t *expression = entry->enum_value.value;
10174 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10175 bool found = false;
10176 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10177 if (l->expression == NULL)
10179 if (l->first_case <= value && value <= l->last_case) {
10185 warningf(&statement->base.source_position,
10186 "enumeration value '%Y' not handled in switch",
10187 entry->base.symbol);
10189 last_value = value;
10194 * Parse a switch statement.
10196 static statement_t *parse_switch(void)
10198 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10202 PUSH_PARENT(statement);
10204 expect('(', end_error);
10205 add_anchor_token(')');
10206 expression_t *const expr = parse_expression();
10207 mark_vars_read(expr, NULL);
10208 type_t * type = skip_typeref(expr->base.type);
10209 if (is_type_integer(type)) {
10210 type = promote_integer(type);
10211 if (warning.traditional) {
10212 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10213 warningf(&expr->base.source_position,
10214 "'%T' switch expression not converted to '%T' in ISO C",
10218 } else if (is_type_valid(type)) {
10219 errorf(&expr->base.source_position,
10220 "switch quantity is not an integer, but '%T'", type);
10221 type = type_error_type;
10223 statement->switchs.expression = create_implicit_cast(expr, type);
10224 expect(')', end_error);
10225 rem_anchor_token(')');
10227 switch_statement_t *rem = current_switch;
10228 current_switch = &statement->switchs;
10229 statement->switchs.body = parse_statement();
10230 current_switch = rem;
10232 if (warning.switch_default &&
10233 statement->switchs.default_label == NULL) {
10234 warningf(&statement->base.source_position, "switch has no default case");
10236 if (warning.switch_enum)
10237 check_enum_cases(&statement->switchs);
10243 return create_invalid_statement();
10246 static statement_t *parse_loop_body(statement_t *const loop)
10248 statement_t *const rem = current_loop;
10249 current_loop = loop;
10251 statement_t *const body = parse_statement();
10253 current_loop = rem;
10258 * Parse a while statement.
10260 static statement_t *parse_while(void)
10262 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10266 PUSH_PARENT(statement);
10268 expect('(', end_error);
10269 add_anchor_token(')');
10270 expression_t *const cond = parse_expression();
10271 statement->whiles.condition = cond;
10272 /* §6.8.5:2 The controlling expression of an iteration statement shall
10273 * have scalar type. */
10274 semantic_condition(cond, "condition of 'while'-statement");
10275 mark_vars_read(cond, NULL);
10276 rem_anchor_token(')');
10277 expect(')', end_error);
10279 statement->whiles.body = parse_loop_body(statement);
10285 return create_invalid_statement();
10289 * Parse a do statement.
10291 static statement_t *parse_do(void)
10293 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10297 PUSH_PARENT(statement);
10299 add_anchor_token(T_while);
10300 statement->do_while.body = parse_loop_body(statement);
10301 rem_anchor_token(T_while);
10303 expect(T_while, end_error);
10304 expect('(', end_error);
10305 add_anchor_token(')');
10306 expression_t *const cond = parse_expression();
10307 statement->do_while.condition = cond;
10308 /* §6.8.5:2 The controlling expression of an iteration statement shall
10309 * have scalar type. */
10310 semantic_condition(cond, "condition of 'do-while'-statement");
10311 mark_vars_read(cond, NULL);
10312 rem_anchor_token(')');
10313 expect(')', end_error);
10314 expect(';', end_error);
10320 return create_invalid_statement();
10324 * Parse a for statement.
10326 static statement_t *parse_for(void)
10328 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10332 expect('(', end_error1);
10333 add_anchor_token(')');
10335 PUSH_PARENT(statement);
10337 size_t const top = environment_top();
10338 scope_t *old_scope = scope_push(&statement->fors.scope);
10340 if (token.type == ';') {
10342 } else if (is_declaration_specifier(&token, false)) {
10343 parse_declaration(record_entity, DECL_FLAGS_NONE);
10345 add_anchor_token(';');
10346 expression_t *const init = parse_expression();
10347 statement->fors.initialisation = init;
10348 mark_vars_read(init, ENT_ANY);
10349 if (warning.unused_value && !expression_has_effect(init)) {
10350 warningf(&init->base.source_position,
10351 "initialisation of 'for'-statement has no effect");
10353 rem_anchor_token(';');
10354 expect(';', end_error2);
10357 if (token.type != ';') {
10358 add_anchor_token(';');
10359 expression_t *const cond = parse_expression();
10360 statement->fors.condition = cond;
10361 /* §6.8.5:2 The controlling expression of an iteration statement
10362 * shall have scalar type. */
10363 semantic_condition(cond, "condition of 'for'-statement");
10364 mark_vars_read(cond, NULL);
10365 rem_anchor_token(';');
10367 expect(';', end_error2);
10368 if (token.type != ')') {
10369 expression_t *const step = parse_expression();
10370 statement->fors.step = step;
10371 mark_vars_read(step, ENT_ANY);
10372 if (warning.unused_value && !expression_has_effect(step)) {
10373 warningf(&step->base.source_position,
10374 "step of 'for'-statement has no effect");
10377 expect(')', end_error2);
10378 rem_anchor_token(')');
10379 statement->fors.body = parse_loop_body(statement);
10381 assert(current_scope == &statement->fors.scope);
10382 scope_pop(old_scope);
10383 environment_pop_to(top);
10390 rem_anchor_token(')');
10391 assert(current_scope == &statement->fors.scope);
10392 scope_pop(old_scope);
10393 environment_pop_to(top);
10397 return create_invalid_statement();
10401 * Parse a goto statement.
10403 static statement_t *parse_goto(void)
10405 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10408 if (GNU_MODE && token.type == '*') {
10410 expression_t *expression = parse_expression();
10411 mark_vars_read(expression, NULL);
10413 /* Argh: although documentation says the expression must be of type void*,
10414 * gcc accepts anything that can be casted into void* without error */
10415 type_t *type = expression->base.type;
10417 if (type != type_error_type) {
10418 if (!is_type_pointer(type) && !is_type_integer(type)) {
10419 errorf(&expression->base.source_position,
10420 "cannot convert to a pointer type");
10421 } else if (warning.other && type != type_void_ptr) {
10422 warningf(&expression->base.source_position,
10423 "type of computed goto expression should be 'void*' not '%T'", type);
10425 expression = create_implicit_cast(expression, type_void_ptr);
10428 statement->gotos.expression = expression;
10430 if (token.type != T_IDENTIFIER) {
10432 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10434 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10435 eat_until_anchor();
10438 symbol_t *symbol = token.v.symbol;
10441 statement->gotos.label = get_label(symbol);
10444 /* remember the goto's in a list for later checking */
10445 *goto_anchor = &statement->gotos;
10446 goto_anchor = &statement->gotos.next;
10448 expect(';', end_error);
10452 return create_invalid_statement();
10456 * Parse a continue statement.
10458 static statement_t *parse_continue(void)
10460 if (current_loop == NULL) {
10461 errorf(HERE, "continue statement not within loop");
10464 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10467 expect(';', end_error);
10474 * Parse a break statement.
10476 static statement_t *parse_break(void)
10478 if (current_switch == NULL && current_loop == NULL) {
10479 errorf(HERE, "break statement not within loop or switch");
10482 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10485 expect(';', end_error);
10492 * Parse a __leave statement.
10494 static statement_t *parse_leave_statement(void)
10496 if (current_try == NULL) {
10497 errorf(HERE, "__leave statement not within __try");
10500 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10503 expect(';', end_error);
10510 * Check if a given entity represents a local variable.
10512 static bool is_local_variable(const entity_t *entity)
10514 if (entity->kind != ENTITY_VARIABLE)
10517 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10518 case STORAGE_CLASS_AUTO:
10519 case STORAGE_CLASS_REGISTER: {
10520 const type_t *type = skip_typeref(entity->declaration.type);
10521 if (is_type_function(type)) {
10533 * Check if a given expression represents a local variable.
10535 static bool expression_is_local_variable(const expression_t *expression)
10537 if (expression->base.kind != EXPR_REFERENCE) {
10540 const entity_t *entity = expression->reference.entity;
10541 return is_local_variable(entity);
10545 * Check if a given expression represents a local variable and
10546 * return its declaration then, else return NULL.
10548 entity_t *expression_is_variable(const expression_t *expression)
10550 if (expression->base.kind != EXPR_REFERENCE) {
10553 entity_t *entity = expression->reference.entity;
10554 if (entity->kind != ENTITY_VARIABLE)
10561 * Parse a return statement.
10563 static statement_t *parse_return(void)
10567 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10569 expression_t *return_value = NULL;
10570 if (token.type != ';') {
10571 return_value = parse_expression();
10572 mark_vars_read(return_value, NULL);
10575 const type_t *const func_type = skip_typeref(current_function->base.type);
10576 assert(is_type_function(func_type));
10577 type_t *const return_type = skip_typeref(func_type->function.return_type);
10579 source_position_t const *const pos = &statement->base.source_position;
10580 if (return_value != NULL) {
10581 type_t *return_value_type = skip_typeref(return_value->base.type);
10583 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10584 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10585 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10586 /* Only warn in C mode, because GCC does the same */
10587 if (c_mode & _CXX || strict_mode) {
10589 "'return' with a value, in function returning 'void'");
10590 } else if (warning.other) {
10592 "'return' with a value, in function returning 'void'");
10594 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10595 /* Only warn in C mode, because GCC does the same */
10598 "'return' with expression in function return 'void'");
10599 } else if (warning.other) {
10601 "'return' with expression in function return 'void'");
10605 assign_error_t error = semantic_assign(return_type, return_value);
10606 report_assign_error(error, return_type, return_value, "'return'",
10609 return_value = create_implicit_cast(return_value, return_type);
10610 /* check for returning address of a local var */
10611 if (warning.other && return_value != NULL
10612 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10613 const expression_t *expression = return_value->unary.value;
10614 if (expression_is_local_variable(expression)) {
10615 warningf(pos, "function returns address of local variable");
10618 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10619 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10620 if (c_mode & _CXX || strict_mode) {
10622 "'return' without value, in function returning non-void");
10625 "'return' without value, in function returning non-void");
10628 statement->returns.value = return_value;
10630 expect(';', end_error);
10637 * Parse a declaration statement.
10639 static statement_t *parse_declaration_statement(void)
10641 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10643 entity_t *before = current_scope->last_entity;
10645 parse_external_declaration();
10647 parse_declaration(record_entity, DECL_FLAGS_NONE);
10650 declaration_statement_t *const decl = &statement->declaration;
10651 entity_t *const begin =
10652 before != NULL ? before->base.next : current_scope->entities;
10653 decl->declarations_begin = begin;
10654 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10660 * Parse an expression statement, ie. expr ';'.
10662 static statement_t *parse_expression_statement(void)
10664 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10666 expression_t *const expr = parse_expression();
10667 statement->expression.expression = expr;
10668 mark_vars_read(expr, ENT_ANY);
10670 expect(';', end_error);
10677 * Parse a microsoft __try { } __finally { } or
10678 * __try{ } __except() { }
10680 static statement_t *parse_ms_try_statment(void)
10682 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10685 PUSH_PARENT(statement);
10687 ms_try_statement_t *rem = current_try;
10688 current_try = &statement->ms_try;
10689 statement->ms_try.try_statement = parse_compound_statement(false);
10694 if (token.type == T___except) {
10696 expect('(', end_error);
10697 add_anchor_token(')');
10698 expression_t *const expr = parse_expression();
10699 mark_vars_read(expr, NULL);
10700 type_t * type = skip_typeref(expr->base.type);
10701 if (is_type_integer(type)) {
10702 type = promote_integer(type);
10703 } else if (is_type_valid(type)) {
10704 errorf(&expr->base.source_position,
10705 "__expect expression is not an integer, but '%T'", type);
10706 type = type_error_type;
10708 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10709 rem_anchor_token(')');
10710 expect(')', end_error);
10711 statement->ms_try.final_statement = parse_compound_statement(false);
10712 } else if (token.type == T__finally) {
10714 statement->ms_try.final_statement = parse_compound_statement(false);
10716 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10717 return create_invalid_statement();
10721 return create_invalid_statement();
10724 static statement_t *parse_empty_statement(void)
10726 if (warning.empty_statement) {
10727 warningf(HERE, "statement is empty");
10729 statement_t *const statement = create_empty_statement();
10734 static statement_t *parse_local_label_declaration(void)
10736 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10740 entity_t *begin = NULL, *end = NULL;
10743 if (token.type != T_IDENTIFIER) {
10744 parse_error_expected("while parsing local label declaration",
10745 T_IDENTIFIER, NULL);
10748 symbol_t *symbol = token.v.symbol;
10749 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10750 if (entity != NULL && entity->base.parent_scope == current_scope) {
10751 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10752 symbol, &entity->base.source_position);
10754 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10756 entity->base.parent_scope = current_scope;
10757 entity->base.namespc = NAMESPACE_LABEL;
10758 entity->base.source_position = token.source_position;
10759 entity->base.symbol = symbol;
10762 end->base.next = entity;
10767 environment_push(entity);
10771 if (token.type != ',')
10777 statement->declaration.declarations_begin = begin;
10778 statement->declaration.declarations_end = end;
10782 static void parse_namespace_definition(void)
10786 entity_t *entity = NULL;
10787 symbol_t *symbol = NULL;
10789 if (token.type == T_IDENTIFIER) {
10790 symbol = token.v.symbol;
10793 entity = get_entity(symbol, NAMESPACE_NORMAL);
10794 if (entity != NULL &&
10795 entity->kind != ENTITY_NAMESPACE &&
10796 entity->base.parent_scope == current_scope) {
10797 if (!is_error_entity(entity)) {
10798 error_redefined_as_different_kind(&token.source_position,
10799 entity, ENTITY_NAMESPACE);
10805 if (entity == NULL) {
10806 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10807 entity->base.symbol = symbol;
10808 entity->base.source_position = token.source_position;
10809 entity->base.namespc = NAMESPACE_NORMAL;
10810 entity->base.parent_scope = current_scope;
10813 if (token.type == '=') {
10814 /* TODO: parse namespace alias */
10815 panic("namespace alias definition not supported yet");
10818 environment_push(entity);
10819 append_entity(current_scope, entity);
10821 size_t const top = environment_top();
10822 scope_t *old_scope = scope_push(&entity->namespacee.members);
10824 expect('{', end_error);
10826 expect('}', end_error);
10829 assert(current_scope == &entity->namespacee.members);
10830 scope_pop(old_scope);
10831 environment_pop_to(top);
10835 * Parse a statement.
10836 * There's also parse_statement() which additionally checks for
10837 * "statement has no effect" warnings
10839 static statement_t *intern_parse_statement(void)
10841 statement_t *statement = NULL;
10843 /* declaration or statement */
10844 add_anchor_token(';');
10845 switch (token.type) {
10846 case T_IDENTIFIER: {
10847 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10848 if (la1_type == ':') {
10849 statement = parse_label_statement();
10850 } else if (is_typedef_symbol(token.v.symbol)) {
10851 statement = parse_declaration_statement();
10853 /* it's an identifier, the grammar says this must be an
10854 * expression statement. However it is common that users mistype
10855 * declaration types, so we guess a bit here to improve robustness
10856 * for incorrect programs */
10857 switch (la1_type) {
10860 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10861 goto expression_statment;
10866 statement = parse_declaration_statement();
10870 expression_statment:
10871 statement = parse_expression_statement();
10878 case T___extension__:
10879 /* This can be a prefix to a declaration or an expression statement.
10880 * We simply eat it now and parse the rest with tail recursion. */
10883 } while (token.type == T___extension__);
10884 bool old_gcc_extension = in_gcc_extension;
10885 in_gcc_extension = true;
10886 statement = intern_parse_statement();
10887 in_gcc_extension = old_gcc_extension;
10891 statement = parse_declaration_statement();
10895 statement = parse_local_label_declaration();
10898 case ';': statement = parse_empty_statement(); break;
10899 case '{': statement = parse_compound_statement(false); break;
10900 case T___leave: statement = parse_leave_statement(); break;
10901 case T___try: statement = parse_ms_try_statment(); break;
10902 case T_asm: statement = parse_asm_statement(); break;
10903 case T_break: statement = parse_break(); break;
10904 case T_case: statement = parse_case_statement(); break;
10905 case T_continue: statement = parse_continue(); break;
10906 case T_default: statement = parse_default_statement(); break;
10907 case T_do: statement = parse_do(); break;
10908 case T_for: statement = parse_for(); break;
10909 case T_goto: statement = parse_goto(); break;
10910 case T_if: statement = parse_if(); break;
10911 case T_return: statement = parse_return(); break;
10912 case T_switch: statement = parse_switch(); break;
10913 case T_while: statement = parse_while(); break;
10916 statement = parse_expression_statement();
10920 errorf(HERE, "unexpected token %K while parsing statement", &token);
10921 statement = create_invalid_statement();
10926 rem_anchor_token(';');
10928 assert(statement != NULL
10929 && statement->base.source_position.input_name != NULL);
10935 * parse a statement and emits "statement has no effect" warning if needed
10936 * (This is really a wrapper around intern_parse_statement with check for 1
10937 * single warning. It is needed, because for statement expressions we have
10938 * to avoid the warning on the last statement)
10940 static statement_t *parse_statement(void)
10942 statement_t *statement = intern_parse_statement();
10944 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10945 expression_t *expression = statement->expression.expression;
10946 if (!expression_has_effect(expression)) {
10947 warningf(&expression->base.source_position,
10948 "statement has no effect");
10956 * Parse a compound statement.
10958 static statement_t *parse_compound_statement(bool inside_expression_statement)
10960 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10962 PUSH_PARENT(statement);
10965 add_anchor_token('}');
10966 /* tokens, which can start a statement */
10967 /* TODO MS, __builtin_FOO */
10968 add_anchor_token('!');
10969 add_anchor_token('&');
10970 add_anchor_token('(');
10971 add_anchor_token('*');
10972 add_anchor_token('+');
10973 add_anchor_token('-');
10974 add_anchor_token('{');
10975 add_anchor_token('~');
10976 add_anchor_token(T_CHARACTER_CONSTANT);
10977 add_anchor_token(T_COLONCOLON);
10978 add_anchor_token(T_FLOATINGPOINT);
10979 add_anchor_token(T_IDENTIFIER);
10980 add_anchor_token(T_INTEGER);
10981 add_anchor_token(T_MINUSMINUS);
10982 add_anchor_token(T_PLUSPLUS);
10983 add_anchor_token(T_STRING_LITERAL);
10984 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10985 add_anchor_token(T_WIDE_STRING_LITERAL);
10986 add_anchor_token(T__Bool);
10987 add_anchor_token(T__Complex);
10988 add_anchor_token(T__Imaginary);
10989 add_anchor_token(T___FUNCTION__);
10990 add_anchor_token(T___PRETTY_FUNCTION__);
10991 add_anchor_token(T___alignof__);
10992 add_anchor_token(T___attribute__);
10993 add_anchor_token(T___builtin_va_start);
10994 add_anchor_token(T___extension__);
10995 add_anchor_token(T___func__);
10996 add_anchor_token(T___imag__);
10997 add_anchor_token(T___label__);
10998 add_anchor_token(T___real__);
10999 add_anchor_token(T___thread);
11000 add_anchor_token(T_asm);
11001 add_anchor_token(T_auto);
11002 add_anchor_token(T_bool);
11003 add_anchor_token(T_break);
11004 add_anchor_token(T_case);
11005 add_anchor_token(T_char);
11006 add_anchor_token(T_class);
11007 add_anchor_token(T_const);
11008 add_anchor_token(T_const_cast);
11009 add_anchor_token(T_continue);
11010 add_anchor_token(T_default);
11011 add_anchor_token(T_delete);
11012 add_anchor_token(T_double);
11013 add_anchor_token(T_do);
11014 add_anchor_token(T_dynamic_cast);
11015 add_anchor_token(T_enum);
11016 add_anchor_token(T_extern);
11017 add_anchor_token(T_false);
11018 add_anchor_token(T_float);
11019 add_anchor_token(T_for);
11020 add_anchor_token(T_goto);
11021 add_anchor_token(T_if);
11022 add_anchor_token(T_inline);
11023 add_anchor_token(T_int);
11024 add_anchor_token(T_long);
11025 add_anchor_token(T_new);
11026 add_anchor_token(T_operator);
11027 add_anchor_token(T_register);
11028 add_anchor_token(T_reinterpret_cast);
11029 add_anchor_token(T_restrict);
11030 add_anchor_token(T_return);
11031 add_anchor_token(T_short);
11032 add_anchor_token(T_signed);
11033 add_anchor_token(T_sizeof);
11034 add_anchor_token(T_static);
11035 add_anchor_token(T_static_cast);
11036 add_anchor_token(T_struct);
11037 add_anchor_token(T_switch);
11038 add_anchor_token(T_template);
11039 add_anchor_token(T_this);
11040 add_anchor_token(T_throw);
11041 add_anchor_token(T_true);
11042 add_anchor_token(T_try);
11043 add_anchor_token(T_typedef);
11044 add_anchor_token(T_typeid);
11045 add_anchor_token(T_typename);
11046 add_anchor_token(T_typeof);
11047 add_anchor_token(T_union);
11048 add_anchor_token(T_unsigned);
11049 add_anchor_token(T_using);
11050 add_anchor_token(T_void);
11051 add_anchor_token(T_volatile);
11052 add_anchor_token(T_wchar_t);
11053 add_anchor_token(T_while);
11055 size_t const top = environment_top();
11056 scope_t *old_scope = scope_push(&statement->compound.scope);
11058 statement_t **anchor = &statement->compound.statements;
11059 bool only_decls_so_far = true;
11060 while (token.type != '}') {
11061 if (token.type == T_EOF) {
11062 errorf(&statement->base.source_position,
11063 "EOF while parsing compound statement");
11066 statement_t *sub_statement = intern_parse_statement();
11067 if (is_invalid_statement(sub_statement)) {
11068 /* an error occurred. if we are at an anchor, return */
11074 if (warning.declaration_after_statement) {
11075 if (sub_statement->kind != STATEMENT_DECLARATION) {
11076 only_decls_so_far = false;
11077 } else if (!only_decls_so_far) {
11078 warningf(&sub_statement->base.source_position,
11079 "ISO C90 forbids mixed declarations and code");
11083 *anchor = sub_statement;
11085 while (sub_statement->base.next != NULL)
11086 sub_statement = sub_statement->base.next;
11088 anchor = &sub_statement->base.next;
11092 /* look over all statements again to produce no effect warnings */
11093 if (warning.unused_value) {
11094 statement_t *sub_statement = statement->compound.statements;
11095 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11096 if (sub_statement->kind != STATEMENT_EXPRESSION)
11098 /* don't emit a warning for the last expression in an expression
11099 * statement as it has always an effect */
11100 if (inside_expression_statement && sub_statement->base.next == NULL)
11103 expression_t *expression = sub_statement->expression.expression;
11104 if (!expression_has_effect(expression)) {
11105 warningf(&expression->base.source_position,
11106 "statement has no effect");
11112 rem_anchor_token(T_while);
11113 rem_anchor_token(T_wchar_t);
11114 rem_anchor_token(T_volatile);
11115 rem_anchor_token(T_void);
11116 rem_anchor_token(T_using);
11117 rem_anchor_token(T_unsigned);
11118 rem_anchor_token(T_union);
11119 rem_anchor_token(T_typeof);
11120 rem_anchor_token(T_typename);
11121 rem_anchor_token(T_typeid);
11122 rem_anchor_token(T_typedef);
11123 rem_anchor_token(T_try);
11124 rem_anchor_token(T_true);
11125 rem_anchor_token(T_throw);
11126 rem_anchor_token(T_this);
11127 rem_anchor_token(T_template);
11128 rem_anchor_token(T_switch);
11129 rem_anchor_token(T_struct);
11130 rem_anchor_token(T_static_cast);
11131 rem_anchor_token(T_static);
11132 rem_anchor_token(T_sizeof);
11133 rem_anchor_token(T_signed);
11134 rem_anchor_token(T_short);
11135 rem_anchor_token(T_return);
11136 rem_anchor_token(T_restrict);
11137 rem_anchor_token(T_reinterpret_cast);
11138 rem_anchor_token(T_register);
11139 rem_anchor_token(T_operator);
11140 rem_anchor_token(T_new);
11141 rem_anchor_token(T_long);
11142 rem_anchor_token(T_int);
11143 rem_anchor_token(T_inline);
11144 rem_anchor_token(T_if);
11145 rem_anchor_token(T_goto);
11146 rem_anchor_token(T_for);
11147 rem_anchor_token(T_float);
11148 rem_anchor_token(T_false);
11149 rem_anchor_token(T_extern);
11150 rem_anchor_token(T_enum);
11151 rem_anchor_token(T_dynamic_cast);
11152 rem_anchor_token(T_do);
11153 rem_anchor_token(T_double);
11154 rem_anchor_token(T_delete);
11155 rem_anchor_token(T_default);
11156 rem_anchor_token(T_continue);
11157 rem_anchor_token(T_const_cast);
11158 rem_anchor_token(T_const);
11159 rem_anchor_token(T_class);
11160 rem_anchor_token(T_char);
11161 rem_anchor_token(T_case);
11162 rem_anchor_token(T_break);
11163 rem_anchor_token(T_bool);
11164 rem_anchor_token(T_auto);
11165 rem_anchor_token(T_asm);
11166 rem_anchor_token(T___thread);
11167 rem_anchor_token(T___real__);
11168 rem_anchor_token(T___label__);
11169 rem_anchor_token(T___imag__);
11170 rem_anchor_token(T___func__);
11171 rem_anchor_token(T___extension__);
11172 rem_anchor_token(T___builtin_va_start);
11173 rem_anchor_token(T___attribute__);
11174 rem_anchor_token(T___alignof__);
11175 rem_anchor_token(T___PRETTY_FUNCTION__);
11176 rem_anchor_token(T___FUNCTION__);
11177 rem_anchor_token(T__Imaginary);
11178 rem_anchor_token(T__Complex);
11179 rem_anchor_token(T__Bool);
11180 rem_anchor_token(T_WIDE_STRING_LITERAL);
11181 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11182 rem_anchor_token(T_STRING_LITERAL);
11183 rem_anchor_token(T_PLUSPLUS);
11184 rem_anchor_token(T_MINUSMINUS);
11185 rem_anchor_token(T_INTEGER);
11186 rem_anchor_token(T_IDENTIFIER);
11187 rem_anchor_token(T_FLOATINGPOINT);
11188 rem_anchor_token(T_COLONCOLON);
11189 rem_anchor_token(T_CHARACTER_CONSTANT);
11190 rem_anchor_token('~');
11191 rem_anchor_token('{');
11192 rem_anchor_token('-');
11193 rem_anchor_token('+');
11194 rem_anchor_token('*');
11195 rem_anchor_token('(');
11196 rem_anchor_token('&');
11197 rem_anchor_token('!');
11198 rem_anchor_token('}');
11199 assert(current_scope == &statement->compound.scope);
11200 scope_pop(old_scope);
11201 environment_pop_to(top);
11208 * Check for unused global static functions and variables
11210 static void check_unused_globals(void)
11212 if (!warning.unused_function && !warning.unused_variable)
11215 for (const entity_t *entity = file_scope->entities; entity != NULL;
11216 entity = entity->base.next) {
11217 if (!is_declaration(entity))
11220 const declaration_t *declaration = &entity->declaration;
11221 if (declaration->used ||
11222 declaration->modifiers & DM_UNUSED ||
11223 declaration->modifiers & DM_USED ||
11224 declaration->storage_class != STORAGE_CLASS_STATIC)
11227 type_t *const type = declaration->type;
11229 if (entity->kind == ENTITY_FUNCTION) {
11230 /* inhibit warning for static inline functions */
11231 if (entity->function.is_inline)
11234 s = entity->function.statement != NULL ? "defined" : "declared";
11239 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11240 type, declaration->base.symbol, s);
11244 static void parse_global_asm(void)
11246 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11249 expect('(', end_error);
11251 statement->asms.asm_text = parse_string_literals();
11252 statement->base.next = unit->global_asm;
11253 unit->global_asm = statement;
11255 expect(')', end_error);
11256 expect(';', end_error);
11261 static void parse_linkage_specification(void)
11264 assert(token.type == T_STRING_LITERAL);
11266 const char *linkage = parse_string_literals().begin;
11268 linkage_kind_t old_linkage = current_linkage;
11269 linkage_kind_t new_linkage;
11270 if (strcmp(linkage, "C") == 0) {
11271 new_linkage = LINKAGE_C;
11272 } else if (strcmp(linkage, "C++") == 0) {
11273 new_linkage = LINKAGE_CXX;
11275 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11276 new_linkage = LINKAGE_INVALID;
11278 current_linkage = new_linkage;
11280 if (token.type == '{') {
11283 expect('}', end_error);
11289 assert(current_linkage == new_linkage);
11290 current_linkage = old_linkage;
11293 static void parse_external(void)
11295 switch (token.type) {
11296 DECLARATION_START_NO_EXTERN
11298 case T___extension__:
11299 /* tokens below are for implicit int */
11300 case '&': /* & x; -> int& x; (and error later, because C++ has no
11302 case '*': /* * x; -> int* x; */
11303 case '(': /* (x); -> int (x); */
11304 parse_external_declaration();
11308 if (look_ahead(1)->type == T_STRING_LITERAL) {
11309 parse_linkage_specification();
11311 parse_external_declaration();
11316 parse_global_asm();
11320 parse_namespace_definition();
11324 if (!strict_mode) {
11326 warningf(HERE, "stray ';' outside of function");
11333 errorf(HERE, "stray %K outside of function", &token);
11334 if (token.type == '(' || token.type == '{' || token.type == '[')
11335 eat_until_matching_token(token.type);
11341 static void parse_externals(void)
11343 add_anchor_token('}');
11344 add_anchor_token(T_EOF);
11347 unsigned char token_anchor_copy[T_LAST_TOKEN];
11348 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11351 while (token.type != T_EOF && token.type != '}') {
11353 bool anchor_leak = false;
11354 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11355 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11357 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11358 anchor_leak = true;
11361 if (in_gcc_extension) {
11362 errorf(HERE, "Leaked __extension__");
11363 anchor_leak = true;
11373 rem_anchor_token(T_EOF);
11374 rem_anchor_token('}');
11378 * Parse a translation unit.
11380 static void parse_translation_unit(void)
11382 add_anchor_token(T_EOF);
11387 if (token.type == T_EOF)
11390 errorf(HERE, "stray %K outside of function", &token);
11391 if (token.type == '(' || token.type == '{' || token.type == '[')
11392 eat_until_matching_token(token.type);
11400 * @return the translation unit or NULL if errors occurred.
11402 void start_parsing(void)
11404 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11405 label_stack = NEW_ARR_F(stack_entry_t, 0);
11406 diagnostic_count = 0;
11410 type_set_output(stderr);
11411 ast_set_output(stderr);
11413 assert(unit == NULL);
11414 unit = allocate_ast_zero(sizeof(unit[0]));
11416 assert(file_scope == NULL);
11417 file_scope = &unit->scope;
11419 assert(current_scope == NULL);
11420 scope_push(&unit->scope);
11423 translation_unit_t *finish_parsing(void)
11425 assert(current_scope == &unit->scope);
11428 assert(file_scope == &unit->scope);
11429 check_unused_globals();
11432 DEL_ARR_F(environment_stack);
11433 DEL_ARR_F(label_stack);
11435 translation_unit_t *result = unit;
11440 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
11441 * are given length one. */
11442 static void complete_incomplete_arrays(void)
11444 size_t n = ARR_LEN(incomplete_arrays);
11445 for (size_t i = 0; i != n; ++i) {
11446 declaration_t *const decl = incomplete_arrays[i];
11447 type_t *const orig_type = decl->type;
11448 type_t *const type = skip_typeref(orig_type);
11450 if (!is_type_incomplete(type))
11453 if (warning.other) {
11454 warningf(&decl->base.source_position,
11455 "array '%#T' assumed to have one element",
11456 orig_type, decl->base.symbol);
11459 type_t *const new_type = duplicate_type(type);
11460 new_type->array.size_constant = true;
11461 new_type->array.has_implicit_size = true;
11462 new_type->array.size = 1;
11464 type_t *const result = identify_new_type(new_type);
11466 decl->type = result;
11472 lookahead_bufpos = 0;
11473 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11476 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11477 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11478 parse_translation_unit();
11479 complete_incomplete_arrays();
11480 DEL_ARR_F(incomplete_arrays);
11481 incomplete_arrays = NULL;
11485 * Initialize the parser.
11487 void init_parser(void)
11489 sym_anonymous = symbol_table_insert("<anonymous>");
11491 if (c_mode & _MS) {
11492 /* add predefined symbols for extended-decl-modifier */
11493 sym_align = symbol_table_insert("align");
11494 sym_allocate = symbol_table_insert("allocate");
11495 sym_dllimport = symbol_table_insert("dllimport");
11496 sym_dllexport = symbol_table_insert("dllexport");
11497 sym_naked = symbol_table_insert("naked");
11498 sym_noinline = symbol_table_insert("noinline");
11499 sym_returns_twice = symbol_table_insert("returns_twice");
11500 sym_noreturn = symbol_table_insert("noreturn");
11501 sym_nothrow = symbol_table_insert("nothrow");
11502 sym_novtable = symbol_table_insert("novtable");
11503 sym_property = symbol_table_insert("property");
11504 sym_get = symbol_table_insert("get");
11505 sym_put = symbol_table_insert("put");
11506 sym_selectany = symbol_table_insert("selectany");
11507 sym_thread = symbol_table_insert("thread");
11508 sym_uuid = symbol_table_insert("uuid");
11509 sym_deprecated = symbol_table_insert("deprecated");
11510 sym_restrict = symbol_table_insert("restrict");
11511 sym_noalias = symbol_table_insert("noalias");
11513 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11515 init_expression_parsers();
11516 obstack_init(&temp_obst);
11518 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11519 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11523 * Terminate the parser.
11525 void exit_parser(void)
11527 obstack_free(&temp_obst, NULL);