2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 2
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool have_arguments; /**< True, if this attribute has arguments. */
68 atomic_type_kind_t akind;
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
102 * Capture a MS __base extension.
104 typedef struct based_spec_t {
105 source_position_t source_position;
106 variable_t *base_variable;
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
111 /** The current token. */
112 static token_t token;
113 /** The lookahead ring-buffer. */
114 static token_t lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static int lookahead_bufpos;
117 static stack_entry_t *environment_stack = NULL;
118 static stack_entry_t *label_stack = NULL;
119 static scope_t *file_scope = NULL;
120 static scope_t *current_scope = NULL;
121 /** Point to the current function declaration if inside a function. */
122 static function_t *current_function = NULL;
123 static entity_t *current_init_decl = NULL;
124 static switch_statement_t *current_switch = NULL;
125 static statement_t *current_loop = NULL;
126 static statement_t *current_parent = NULL;
127 static ms_try_statement_t *current_try = NULL;
128 static linkage_kind_t current_linkage = LINKAGE_INVALID;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t **goto_anchor = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t **label_anchor = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
140 static entity_t *anonymous_entity;
141 static declaration_t **incomplete_arrays;
144 #define PUSH_PARENT(stmt) \
145 statement_t *const prev_parent = current_parent; \
146 ((void)(current_parent = (stmt)))
147 #define POP_PARENT ((void)(current_parent = prev_parent))
149 /** special symbol used for anonymous entities. */
150 static const symbol_t *sym_anonymous = NULL;
152 /* symbols for Microsoft extended-decl-modifier */
153 static const symbol_t *sym_align = NULL;
154 static const symbol_t *sym_allocate = NULL;
155 static const symbol_t *sym_dllimport = NULL;
156 static const symbol_t *sym_dllexport = NULL;
157 static const symbol_t *sym_naked = NULL;
158 static const symbol_t *sym_noinline = NULL;
159 static const symbol_t *sym_noreturn = NULL;
160 static const symbol_t *sym_nothrow = NULL;
161 static const symbol_t *sym_novtable = NULL;
162 static const symbol_t *sym_property = NULL;
163 static const symbol_t *sym_get = NULL;
164 static const symbol_t *sym_put = NULL;
165 static const symbol_t *sym_selectany = NULL;
166 static const symbol_t *sym_thread = NULL;
167 static const symbol_t *sym_uuid = NULL;
168 static const symbol_t *sym_deprecated = NULL;
169 static const symbol_t *sym_restrict = NULL;
170 static const symbol_t *sym_noalias = NULL;
172 /** The token anchor set */
173 static unsigned char token_anchor_set[T_LAST_TOKEN];
175 /** The current source position. */
176 #define HERE (&token.source_position)
178 /** true if we are in GCC mode. */
179 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
181 static type_t *type_valist;
183 static statement_t *parse_compound_statement(bool inside_expression_statement);
184 static statement_t *parse_statement(void);
186 static expression_t *parse_sub_expression(precedence_t);
187 static expression_t *parse_expression(void);
188 static type_t *parse_typename(void);
189 static void parse_externals(void);
190 static void parse_external(void);
192 static void parse_compound_type_entries(compound_t *compound_declaration);
194 typedef enum declarator_flags_t {
196 DECL_MAY_BE_ABSTRACT = 1U << 0,
197 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
198 DECL_IS_PARAMETER = 1U << 2
199 } declarator_flags_t;
201 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
202 declarator_flags_t flags);
204 static entity_t *record_entity(entity_t *entity, bool is_definition);
206 static void semantic_comparison(binary_expression_t *expression);
208 #define STORAGE_CLASSES \
209 STORAGE_CLASSES_NO_EXTERN \
212 #define STORAGE_CLASSES_NO_EXTERN \
219 #define TYPE_QUALIFIERS \
224 case T__forceinline: \
225 case T___attribute__:
227 #define COMPLEX_SPECIFIERS \
229 #define IMAGINARY_SPECIFIERS \
232 #define TYPE_SPECIFIERS \
234 case T___builtin_va_list: \
254 #define DECLARATION_START \
259 #define DECLARATION_START_NO_EXTERN \
260 STORAGE_CLASSES_NO_EXTERN \
264 #define TYPENAME_START \
268 #define EXPRESSION_START \
277 case T_CHARACTER_CONSTANT: \
278 case T_FLOATINGPOINT: \
282 case T_STRING_LITERAL: \
283 case T_WIDE_CHARACTER_CONSTANT: \
284 case T_WIDE_STRING_LITERAL: \
285 case T___FUNCDNAME__: \
286 case T___FUNCSIG__: \
287 case T___FUNCTION__: \
288 case T___PRETTY_FUNCTION__: \
289 case T___alignof__: \
290 case T___builtin_alloca: \
291 case T___builtin_classify_type: \
292 case T___builtin_constant_p: \
293 case T___builtin_expect: \
294 case T___builtin_huge_val: \
295 case T___builtin_inf: \
296 case T___builtin_inff: \
297 case T___builtin_infl: \
298 case T___builtin_isgreater: \
299 case T___builtin_isgreaterequal: \
300 case T___builtin_isless: \
301 case T___builtin_islessequal: \
302 case T___builtin_islessgreater: \
303 case T___builtin_isunordered: \
304 case T___builtin_nan: \
305 case T___builtin_nanf: \
306 case T___builtin_nanl: \
307 case T___builtin_offsetof: \
308 case T___builtin_prefetch: \
309 case T___builtin_va_arg: \
310 case T___builtin_va_end: \
311 case T___builtin_va_start: \
322 * Allocate an AST node with given size and
323 * initialize all fields with zero.
325 static void *allocate_ast_zero(size_t size)
327 void *res = allocate_ast(size);
328 memset(res, 0, size);
333 * Returns the size of an entity node.
335 * @param kind the entity kind
337 static size_t get_entity_struct_size(entity_kind_t kind)
339 static const size_t sizes[] = {
340 [ENTITY_VARIABLE] = sizeof(variable_t),
341 [ENTITY_PARAMETER] = sizeof(parameter_t),
342 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
343 [ENTITY_FUNCTION] = sizeof(function_t),
344 [ENTITY_TYPEDEF] = sizeof(typedef_t),
345 [ENTITY_STRUCT] = sizeof(compound_t),
346 [ENTITY_UNION] = sizeof(compound_t),
347 [ENTITY_ENUM] = sizeof(enum_t),
348 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
349 [ENTITY_LABEL] = sizeof(label_t),
350 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
351 [ENTITY_NAMESPACE] = sizeof(namespace_t)
353 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
354 assert(sizes[kind] != 0);
359 * Allocate an entity of given kind and initialize all
362 static entity_t *allocate_entity_zero(entity_kind_t kind)
364 size_t size = get_entity_struct_size(kind);
365 entity_t *entity = allocate_ast_zero(size);
371 * Returns the size of a statement node.
373 * @param kind the statement kind
375 static size_t get_statement_struct_size(statement_kind_t kind)
377 static const size_t sizes[] = {
378 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
379 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
380 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
381 [STATEMENT_RETURN] = sizeof(return_statement_t),
382 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
383 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
384 [STATEMENT_IF] = sizeof(if_statement_t),
385 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
386 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
387 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
388 [STATEMENT_BREAK] = sizeof(statement_base_t),
389 [STATEMENT_GOTO] = sizeof(goto_statement_t),
390 [STATEMENT_LABEL] = sizeof(label_statement_t),
391 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
392 [STATEMENT_WHILE] = sizeof(while_statement_t),
393 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
394 [STATEMENT_FOR] = sizeof(for_statement_t),
395 [STATEMENT_ASM] = sizeof(asm_statement_t),
396 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
397 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
399 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
400 assert(sizes[kind] != 0);
405 * Returns the size of an expression node.
407 * @param kind the expression kind
409 static size_t get_expression_struct_size(expression_kind_t kind)
411 static const size_t sizes[] = {
412 [EXPR_INVALID] = sizeof(expression_base_t),
413 [EXPR_REFERENCE] = sizeof(reference_expression_t),
414 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
415 [EXPR_CONST] = sizeof(const_expression_t),
416 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
417 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
418 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
419 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
420 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
421 [EXPR_CALL] = sizeof(call_expression_t),
422 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
423 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
424 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
425 [EXPR_SELECT] = sizeof(select_expression_t),
426 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
427 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
428 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
429 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
430 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
431 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
432 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
433 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
434 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
435 [EXPR_VA_START] = sizeof(va_start_expression_t),
436 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
437 [EXPR_STATEMENT] = sizeof(statement_expression_t),
438 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
440 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
441 return sizes[EXPR_UNARY_FIRST];
443 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
444 return sizes[EXPR_BINARY_FIRST];
446 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
447 assert(sizes[kind] != 0);
452 * Allocate a statement node of given kind and initialize all
453 * fields with zero. Sets its source position to the position
454 * of the current token.
456 static statement_t *allocate_statement_zero(statement_kind_t kind)
458 size_t size = get_statement_struct_size(kind);
459 statement_t *res = allocate_ast_zero(size);
461 res->base.kind = kind;
462 res->base.parent = current_parent;
463 res->base.source_position = token.source_position;
468 * Allocate an expression node of given kind and initialize all
471 static expression_t *allocate_expression_zero(expression_kind_t kind)
473 size_t size = get_expression_struct_size(kind);
474 expression_t *res = allocate_ast_zero(size);
476 res->base.kind = kind;
477 res->base.type = type_error_type;
478 res->base.source_position = token.source_position;
483 * Creates a new invalid expression at the source position
484 * of the current token.
486 static expression_t *create_invalid_expression(void)
488 return allocate_expression_zero(EXPR_INVALID);
492 * Creates a new invalid statement.
494 static statement_t *create_invalid_statement(void)
496 return allocate_statement_zero(STATEMENT_INVALID);
500 * Allocate a new empty statement.
502 static statement_t *create_empty_statement(void)
504 return allocate_statement_zero(STATEMENT_EMPTY);
508 * Returns the size of a type node.
510 * @param kind the type kind
512 static size_t get_type_struct_size(type_kind_t kind)
514 static const size_t sizes[] = {
515 [TYPE_ATOMIC] = sizeof(atomic_type_t),
516 [TYPE_COMPLEX] = sizeof(complex_type_t),
517 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
518 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
519 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
520 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
521 [TYPE_ENUM] = sizeof(enum_type_t),
522 [TYPE_FUNCTION] = sizeof(function_type_t),
523 [TYPE_POINTER] = sizeof(pointer_type_t),
524 [TYPE_ARRAY] = sizeof(array_type_t),
525 [TYPE_BUILTIN] = sizeof(builtin_type_t),
526 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
527 [TYPE_TYPEOF] = sizeof(typeof_type_t),
529 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
530 assert(kind <= TYPE_TYPEOF);
531 assert(sizes[kind] != 0);
536 * Allocate a type node of given kind and initialize all
539 * @param kind type kind to allocate
541 static type_t *allocate_type_zero(type_kind_t kind)
543 size_t size = get_type_struct_size(kind);
544 type_t *res = obstack_alloc(type_obst, size);
545 memset(res, 0, size);
546 res->base.kind = kind;
552 * Returns the size of an initializer node.
554 * @param kind the initializer kind
556 static size_t get_initializer_size(initializer_kind_t kind)
558 static const size_t sizes[] = {
559 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
560 [INITIALIZER_STRING] = sizeof(initializer_string_t),
561 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
562 [INITIALIZER_LIST] = sizeof(initializer_list_t),
563 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
565 assert(kind < sizeof(sizes) / sizeof(*sizes));
566 assert(sizes[kind] != 0);
571 * Allocate an initializer node of given kind and initialize all
574 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
576 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
583 * Free a type from the type obstack.
585 static void free_type(void *type)
587 obstack_free(type_obst, type);
591 * Returns the index of the top element of the environment stack.
593 static size_t environment_top(void)
595 return ARR_LEN(environment_stack);
599 * Returns the index of the top element of the global label stack.
601 static size_t label_top(void)
603 return ARR_LEN(label_stack);
607 * Return the next token.
609 static inline void next_token(void)
611 token = lookahead_buffer[lookahead_bufpos];
612 lookahead_buffer[lookahead_bufpos] = lexer_token;
615 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
618 print_token(stderr, &token);
619 fprintf(stderr, "\n");
624 * Return the next token with a given lookahead.
626 static inline const token_t *look_ahead(int num)
628 assert(num > 0 && num <= MAX_LOOKAHEAD);
629 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
630 return &lookahead_buffer[pos];
634 * Adds a token type to the token type anchor set (a multi-set).
636 static void add_anchor_token(int token_type)
638 assert(0 <= token_type && token_type < T_LAST_TOKEN);
639 ++token_anchor_set[token_type];
643 * Set the number of tokens types of the given type
644 * to zero and return the old count.
646 static int save_and_reset_anchor_state(int token_type)
648 assert(0 <= token_type && token_type < T_LAST_TOKEN);
649 int count = token_anchor_set[token_type];
650 token_anchor_set[token_type] = 0;
655 * Restore the number of token types to the given count.
657 static void restore_anchor_state(int token_type, int count)
659 assert(0 <= token_type && token_type < T_LAST_TOKEN);
660 token_anchor_set[token_type] = count;
664 * Remove a token type from the token type anchor set (a multi-set).
666 static void rem_anchor_token(int token_type)
668 assert(0 <= token_type && token_type < T_LAST_TOKEN);
669 assert(token_anchor_set[token_type] != 0);
670 --token_anchor_set[token_type];
674 * Return true if the token type of the current token is
677 static bool at_anchor(void)
681 return token_anchor_set[token.type];
685 * Eat tokens until a matching token type is found.
687 static void eat_until_matching_token(int type)
691 case '(': end_token = ')'; break;
692 case '{': end_token = '}'; break;
693 case '[': end_token = ']'; break;
694 default: end_token = type; break;
697 unsigned parenthesis_count = 0;
698 unsigned brace_count = 0;
699 unsigned bracket_count = 0;
700 while (token.type != end_token ||
701 parenthesis_count != 0 ||
703 bracket_count != 0) {
704 switch (token.type) {
706 case '(': ++parenthesis_count; break;
707 case '{': ++brace_count; break;
708 case '[': ++bracket_count; break;
711 if (parenthesis_count > 0)
721 if (bracket_count > 0)
724 if (token.type == end_token &&
725 parenthesis_count == 0 &&
739 * Eat input tokens until an anchor is found.
741 static void eat_until_anchor(void)
743 while (token_anchor_set[token.type] == 0) {
744 if (token.type == '(' || token.type == '{' || token.type == '[')
745 eat_until_matching_token(token.type);
751 * Eat a whole block from input tokens.
753 static void eat_block(void)
755 eat_until_matching_token('{');
756 if (token.type == '}')
760 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
763 * Report a parse error because an expected token was not found.
766 #if defined __GNUC__ && __GNUC__ >= 4
767 __attribute__((sentinel))
769 void parse_error_expected(const char *message, ...)
771 if (message != NULL) {
772 errorf(HERE, "%s", message);
775 va_start(ap, message);
776 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
781 * Report an incompatible type.
783 static void type_error_incompatible(const char *msg,
784 const source_position_t *source_position, type_t *type1, type_t *type2)
786 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
791 * Expect the current token is the expected token.
792 * If not, generate an error, eat the current statement,
793 * and goto the end_error label.
795 #define expect(expected, error_label) \
797 if (UNLIKELY(token.type != (expected))) { \
798 parse_error_expected(NULL, (expected), NULL); \
799 add_anchor_token(expected); \
800 eat_until_anchor(); \
801 if (token.type == expected) \
803 rem_anchor_token(expected); \
810 * Push a given scope on the scope stack and make it the
813 static scope_t *scope_push(scope_t *new_scope)
815 if (current_scope != NULL) {
816 new_scope->depth = current_scope->depth + 1;
819 scope_t *old_scope = current_scope;
820 current_scope = new_scope;
825 * Pop the current scope from the scope stack.
827 static void scope_pop(scope_t *old_scope)
829 current_scope = old_scope;
833 * Search an entity by its symbol in a given namespace.
835 static entity_t *get_entity(const symbol_t *const symbol,
836 namespace_tag_t namespc)
838 entity_t *entity = symbol->entity;
839 for (; entity != NULL; entity = entity->base.symbol_next) {
840 if (entity->base.namespc == namespc)
848 * pushs an entity on the environment stack and links the corresponding symbol
851 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
853 symbol_t *symbol = entity->base.symbol;
854 entity_namespace_t namespc = entity->base.namespc;
855 assert(namespc != NAMESPACE_INVALID);
857 /* replace/add entity into entity list of the symbol */
860 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
865 /* replace an entry? */
866 if (iter->base.namespc == namespc) {
867 entity->base.symbol_next = iter->base.symbol_next;
873 /* remember old declaration */
875 entry.symbol = symbol;
876 entry.old_entity = iter;
877 entry.namespc = namespc;
878 ARR_APP1(stack_entry_t, *stack_ptr, entry);
882 * Push an entity on the environment stack.
884 static void environment_push(entity_t *entity)
886 assert(entity->base.source_position.input_name != NULL);
887 assert(entity->base.parent_scope != NULL);
888 stack_push(&environment_stack, entity);
892 * Push a declaration on the global label stack.
894 * @param declaration the declaration
896 static void label_push(entity_t *label)
898 /* we abuse the parameters scope as parent for the labels */
899 label->base.parent_scope = ¤t_function->parameters;
900 stack_push(&label_stack, label);
904 * pops symbols from the environment stack until @p new_top is the top element
906 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
908 stack_entry_t *stack = *stack_ptr;
909 size_t top = ARR_LEN(stack);
912 assert(new_top <= top);
916 for (i = top; i > new_top; --i) {
917 stack_entry_t *entry = &stack[i - 1];
919 entity_t *old_entity = entry->old_entity;
920 symbol_t *symbol = entry->symbol;
921 entity_namespace_t namespc = entry->namespc;
923 /* replace with old_entity/remove */
926 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
928 assert(iter != NULL);
929 /* replace an entry? */
930 if (iter->base.namespc == namespc)
934 /* restore definition from outer scopes (if there was one) */
935 if (old_entity != NULL) {
936 old_entity->base.symbol_next = iter->base.symbol_next;
937 *anchor = old_entity;
939 /* remove entry from list */
940 *anchor = iter->base.symbol_next;
944 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
948 * Pop all entries from the environment stack until the new_top
951 * @param new_top the new stack top
953 static void environment_pop_to(size_t new_top)
955 stack_pop_to(&environment_stack, new_top);
959 * Pop all entries from the global label stack until the new_top
962 * @param new_top the new stack top
964 static void label_pop_to(size_t new_top)
966 stack_pop_to(&label_stack, new_top);
969 static int get_akind_rank(atomic_type_kind_t akind)
975 * Return the type rank for an atomic type.
977 static int get_rank(const type_t *type)
979 assert(!is_typeref(type));
980 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
981 * and esp. footnote 108). However we can't fold constants (yet), so we
982 * can't decide whether unsigned int is possible, while int always works.
983 * (unsigned int would be preferable when possible... for stuff like
984 * struct { enum { ... } bla : 4; } ) */
985 if (type->kind == TYPE_ENUM)
986 return get_akind_rank(ATOMIC_TYPE_INT);
988 assert(type->kind == TYPE_ATOMIC);
989 return get_akind_rank(type->atomic.akind);
993 * Do integer promotion for a given type.
995 * @param type the type to promote
996 * @return the promoted type
998 static type_t *promote_integer(type_t *type)
1000 if (type->kind == TYPE_BITFIELD)
1001 type = type->bitfield.base_type;
1003 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
1010 * Create a cast expression.
1012 * @param expression the expression to cast
1013 * @param dest_type the destination type
1015 static expression_t *create_cast_expression(expression_t *expression,
1018 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1020 cast->unary.value = expression;
1021 cast->base.type = dest_type;
1027 * Check if a given expression represents a null pointer constant.
1029 * @param expression the expression to check
1031 static bool is_null_pointer_constant(const expression_t *expression)
1033 /* skip void* cast */
1034 if (expression->kind == EXPR_UNARY_CAST
1035 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1036 expression = expression->unary.value;
1039 /* TODO: not correct yet, should be any constant integer expression
1040 * which evaluates to 0 */
1041 if (expression->kind != EXPR_CONST)
1044 type_t *const type = skip_typeref(expression->base.type);
1045 if (!is_type_integer(type))
1048 return expression->conste.v.int_value == 0;
1052 * Create an implicit cast expression.
1054 * @param expression the expression to cast
1055 * @param dest_type the destination type
1057 static expression_t *create_implicit_cast(expression_t *expression,
1060 type_t *const source_type = expression->base.type;
1062 if (source_type == dest_type)
1065 return create_cast_expression(expression, dest_type);
1068 typedef enum assign_error_t {
1070 ASSIGN_ERROR_INCOMPATIBLE,
1071 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1072 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1073 ASSIGN_WARNING_POINTER_FROM_INT,
1074 ASSIGN_WARNING_INT_FROM_POINTER
1077 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1078 const expression_t *const right,
1079 const char *context,
1080 const source_position_t *source_position)
1082 type_t *const orig_type_right = right->base.type;
1083 type_t *const type_left = skip_typeref(orig_type_left);
1084 type_t *const type_right = skip_typeref(orig_type_right);
1087 case ASSIGN_SUCCESS:
1089 case ASSIGN_ERROR_INCOMPATIBLE:
1090 errorf(source_position,
1091 "destination type '%T' in %s is incompatible with type '%T'",
1092 orig_type_left, context, orig_type_right);
1095 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1096 if (warning.other) {
1097 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1098 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1100 /* the left type has all qualifiers from the right type */
1101 unsigned missing_qualifiers
1102 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1103 warningf(source_position,
1104 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1105 orig_type_left, context, orig_type_right, missing_qualifiers);
1110 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1111 if (warning.other) {
1112 warningf(source_position,
1113 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1114 orig_type_left, context, right, orig_type_right);
1118 case ASSIGN_WARNING_POINTER_FROM_INT:
1119 if (warning.other) {
1120 warningf(source_position,
1121 "%s makes pointer '%T' from integer '%T' without a cast",
1122 context, orig_type_left, orig_type_right);
1126 case ASSIGN_WARNING_INT_FROM_POINTER:
1127 if (warning.other) {
1128 warningf(source_position,
1129 "%s makes integer '%T' from pointer '%T' without a cast",
1130 context, orig_type_left, orig_type_right);
1135 panic("invalid error value");
1139 /** Implements the rules from § 6.5.16.1 */
1140 static assign_error_t semantic_assign(type_t *orig_type_left,
1141 const expression_t *const right)
1143 type_t *const orig_type_right = right->base.type;
1144 type_t *const type_left = skip_typeref(orig_type_left);
1145 type_t *const type_right = skip_typeref(orig_type_right);
1147 if (is_type_pointer(type_left)) {
1148 if (is_null_pointer_constant(right)) {
1149 return ASSIGN_SUCCESS;
1150 } else if (is_type_pointer(type_right)) {
1151 type_t *points_to_left
1152 = skip_typeref(type_left->pointer.points_to);
1153 type_t *points_to_right
1154 = skip_typeref(type_right->pointer.points_to);
1155 assign_error_t res = ASSIGN_SUCCESS;
1157 /* the left type has all qualifiers from the right type */
1158 unsigned missing_qualifiers
1159 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1160 if (missing_qualifiers != 0) {
1161 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1164 points_to_left = get_unqualified_type(points_to_left);
1165 points_to_right = get_unqualified_type(points_to_right);
1167 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1170 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1171 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1172 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1175 if (!types_compatible(points_to_left, points_to_right)) {
1176 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1180 } else if (is_type_integer(type_right)) {
1181 return ASSIGN_WARNING_POINTER_FROM_INT;
1183 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1184 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1185 && is_type_pointer(type_right))) {
1186 return ASSIGN_SUCCESS;
1187 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1188 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1189 type_t *const unqual_type_left = get_unqualified_type(type_left);
1190 type_t *const unqual_type_right = get_unqualified_type(type_right);
1191 if (types_compatible(unqual_type_left, unqual_type_right)) {
1192 return ASSIGN_SUCCESS;
1194 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1195 return ASSIGN_WARNING_INT_FROM_POINTER;
1198 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1199 return ASSIGN_SUCCESS;
1201 return ASSIGN_ERROR_INCOMPATIBLE;
1204 static expression_t *parse_constant_expression(void)
1206 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1208 if (!is_constant_expression(result)) {
1209 errorf(&result->base.source_position,
1210 "expression '%E' is not constant", result);
1216 static expression_t *parse_assignment_expression(void)
1218 return parse_sub_expression(PREC_ASSIGNMENT);
1221 static string_t parse_string_literals(void)
1223 assert(token.type == T_STRING_LITERAL);
1224 string_t result = token.v.string;
1228 while (token.type == T_STRING_LITERAL) {
1229 result = concat_strings(&result, &token.v.string);
1236 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1237 [GNU_AK_CONST] = "const",
1238 [GNU_AK_VOLATILE] = "volatile",
1239 [GNU_AK_CDECL] = "cdecl",
1240 [GNU_AK_STDCALL] = "stdcall",
1241 [GNU_AK_FASTCALL] = "fastcall",
1242 [GNU_AK_DEPRECATED] = "deprecated",
1243 [GNU_AK_NOINLINE] = "noinline",
1244 [GNU_AK_NORETURN] = "noreturn",
1245 [GNU_AK_NAKED] = "naked",
1246 [GNU_AK_PURE] = "pure",
1247 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1248 [GNU_AK_MALLOC] = "malloc",
1249 [GNU_AK_WEAK] = "weak",
1250 [GNU_AK_CONSTRUCTOR] = "constructor",
1251 [GNU_AK_DESTRUCTOR] = "destructor",
1252 [GNU_AK_NOTHROW] = "nothrow",
1253 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1254 [GNU_AK_COMMON] = "common",
1255 [GNU_AK_NOCOMMON] = "nocommon",
1256 [GNU_AK_PACKED] = "packed",
1257 [GNU_AK_SHARED] = "shared",
1258 [GNU_AK_NOTSHARED] = "notshared",
1259 [GNU_AK_USED] = "used",
1260 [GNU_AK_UNUSED] = "unused",
1261 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1262 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1263 [GNU_AK_LONGCALL] = "longcall",
1264 [GNU_AK_SHORTCALL] = "shortcall",
1265 [GNU_AK_LONG_CALL] = "long_call",
1266 [GNU_AK_SHORT_CALL] = "short_call",
1267 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1268 [GNU_AK_INTERRUPT] = "interrupt",
1269 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1270 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1271 [GNU_AK_NESTING] = "nesting",
1272 [GNU_AK_NEAR] = "near",
1273 [GNU_AK_FAR] = "far",
1274 [GNU_AK_SIGNAL] = "signal",
1275 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1276 [GNU_AK_TINY_DATA] = "tiny_data",
1277 [GNU_AK_SAVEALL] = "saveall",
1278 [GNU_AK_FLATTEN] = "flatten",
1279 [GNU_AK_SSEREGPARM] = "sseregparm",
1280 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1281 [GNU_AK_RETURN_TWICE] = "return_twice",
1282 [GNU_AK_MAY_ALIAS] = "may_alias",
1283 [GNU_AK_MS_STRUCT] = "ms_struct",
1284 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1285 [GNU_AK_DLLIMPORT] = "dllimport",
1286 [GNU_AK_DLLEXPORT] = "dllexport",
1287 [GNU_AK_ALIGNED] = "aligned",
1288 [GNU_AK_ALIAS] = "alias",
1289 [GNU_AK_SECTION] = "section",
1290 [GNU_AK_FORMAT] = "format",
1291 [GNU_AK_FORMAT_ARG] = "format_arg",
1292 [GNU_AK_WEAKREF] = "weakref",
1293 [GNU_AK_NONNULL] = "nonnull",
1294 [GNU_AK_TLS_MODEL] = "tls_model",
1295 [GNU_AK_VISIBILITY] = "visibility",
1296 [GNU_AK_REGPARM] = "regparm",
1297 [GNU_AK_MODE] = "mode",
1298 [GNU_AK_MODEL] = "model",
1299 [GNU_AK_TRAP_EXIT] = "trap_exit",
1300 [GNU_AK_SP_SWITCH] = "sp_switch",
1301 [GNU_AK_SENTINEL] = "sentinel"
1305 * compare two string, ignoring double underscores on the second.
1307 static int strcmp_underscore(const char *s1, const char *s2)
1309 if (s2[0] == '_' && s2[1] == '_') {
1310 size_t len2 = strlen(s2);
1311 size_t len1 = strlen(s1);
1312 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1313 return strncmp(s1, s2+2, len2-4);
1317 return strcmp(s1, s2);
1321 * Allocate a new gnu temporal attribute of given kind.
1323 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1325 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1326 attribute->kind = kind;
1327 attribute->next = NULL;
1328 attribute->invalid = false;
1329 attribute->have_arguments = false;
1335 * Parse one constant expression argument of the given attribute.
1337 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1339 expression_t *expression;
1340 add_anchor_token(')');
1341 expression = parse_constant_expression();
1342 rem_anchor_token(')');
1343 expect(')', end_error);
1344 attribute->u.argument = fold_constant(expression);
1347 attribute->invalid = true;
1351 * Parse a list of constant expressions arguments of the given attribute.
1353 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1355 argument_list_t **list = &attribute->u.arguments;
1356 argument_list_t *entry;
1357 expression_t *expression;
1358 add_anchor_token(')');
1359 add_anchor_token(',');
1361 expression = parse_constant_expression();
1362 entry = obstack_alloc(&temp_obst, sizeof(entry));
1363 entry->argument = fold_constant(expression);
1366 list = &entry->next;
1367 if (token.type != ',')
1371 rem_anchor_token(',');
1372 rem_anchor_token(')');
1373 expect(')', end_error);
1376 attribute->invalid = true;
1380 * Parse one string literal argument of the given attribute.
1382 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1385 add_anchor_token('(');
1386 if (token.type != T_STRING_LITERAL) {
1387 parse_error_expected("while parsing attribute directive",
1388 T_STRING_LITERAL, NULL);
1391 *string = parse_string_literals();
1392 rem_anchor_token('(');
1393 expect(')', end_error);
1396 attribute->invalid = true;
1400 * Parse one tls model of the given attribute.
1402 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1404 static const char *const tls_models[] = {
1410 string_t string = { NULL, 0 };
1411 parse_gnu_attribute_string_arg(attribute, &string);
1412 if (string.begin != NULL) {
1413 for (size_t i = 0; i < 4; ++i) {
1414 if (strcmp(tls_models[i], string.begin) == 0) {
1415 attribute->u.value = i;
1419 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1421 attribute->invalid = true;
1425 * Parse one tls model of the given attribute.
1427 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1429 static const char *const visibilities[] = {
1435 string_t string = { NULL, 0 };
1436 parse_gnu_attribute_string_arg(attribute, &string);
1437 if (string.begin != NULL) {
1438 for (size_t i = 0; i < 4; ++i) {
1439 if (strcmp(visibilities[i], string.begin) == 0) {
1440 attribute->u.value = i;
1444 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1446 attribute->invalid = true;
1450 * Parse one (code) model of the given attribute.
1452 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1454 static const char *const visibilities[] = {
1459 string_t string = { NULL, 0 };
1460 parse_gnu_attribute_string_arg(attribute, &string);
1461 if (string.begin != NULL) {
1462 for (int i = 0; i < 3; ++i) {
1463 if (strcmp(visibilities[i], string.begin) == 0) {
1464 attribute->u.value = i;
1468 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1470 attribute->invalid = true;
1474 * Parse one mode of the given attribute.
1476 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1478 /* TODO: find out what is allowed here... */
1480 /* at least: byte, word, pointer, list of machine modes
1481 * __XXX___ is interpreted as XXX */
1482 add_anchor_token(')');
1484 if (token.type != T_IDENTIFIER) {
1485 expect(T_IDENTIFIER, end_error);
1488 /* This isn't really correct, the backend should provide a list of machine
1489 * specific modes (according to gcc philosophy that is...) */
1490 const char *symbol_str = token.v.symbol->string;
1491 if (strcmp_underscore("QI", symbol_str) == 0 ||
1492 strcmp_underscore("byte", symbol_str) == 0) {
1493 attribute->u.akind = ATOMIC_TYPE_CHAR;
1494 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1495 attribute->u.akind = ATOMIC_TYPE_SHORT;
1496 } else if (strcmp_underscore("SI", symbol_str) == 0
1497 || strcmp_underscore("word", symbol_str) == 0
1498 || strcmp_underscore("pointer", symbol_str) == 0) {
1499 attribute->u.akind = ATOMIC_TYPE_INT;
1500 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1501 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1504 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1505 attribute->invalid = true;
1509 rem_anchor_token(')');
1510 expect(')', end_error);
1513 attribute->invalid = true;
1517 * Parse one interrupt argument of the given attribute.
1519 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1521 static const char *const interrupts[] = {
1528 string_t string = { NULL, 0 };
1529 parse_gnu_attribute_string_arg(attribute, &string);
1530 if (string.begin != NULL) {
1531 for (size_t i = 0; i < 5; ++i) {
1532 if (strcmp(interrupts[i], string.begin) == 0) {
1533 attribute->u.value = i;
1537 errorf(HERE, "'%s' is not an interrupt", string.begin);
1539 attribute->invalid = true;
1543 * Parse ( identifier, const expression, const expression )
1545 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1547 static const char *const format_names[] = {
1555 if (token.type != T_IDENTIFIER) {
1556 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1559 const char *name = token.v.symbol->string;
1560 for (i = 0; i < 4; ++i) {
1561 if (strcmp_underscore(format_names[i], name) == 0)
1565 if (warning.attribute)
1566 warningf(HERE, "'%s' is an unrecognized format function type", name);
1570 expect(',', end_error);
1571 add_anchor_token(')');
1572 add_anchor_token(',');
1573 parse_constant_expression();
1574 rem_anchor_token(',');
1575 rem_anchor_token(')');
1577 expect(',', end_error);
1578 add_anchor_token(')');
1579 parse_constant_expression();
1580 rem_anchor_token(')');
1581 expect(')', end_error);
1584 attribute->u.value = true;
1588 * Check that a given GNU attribute has no arguments.
1590 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1592 if (!attribute->have_arguments)
1595 /* should have no arguments */
1596 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1597 eat_until_matching_token('(');
1598 /* we have already consumed '(', so we stop before ')', eat it */
1600 attribute->invalid = true;
1604 * Parse one GNU attribute.
1606 * Note that attribute names can be specified WITH or WITHOUT
1607 * double underscores, ie const or __const__.
1609 * The following attributes are parsed without arguments
1634 * no_instrument_function
1635 * warn_unused_result
1652 * externally_visible
1660 * The following attributes are parsed with arguments
1661 * aligned( const expression )
1662 * alias( string literal )
1663 * section( string literal )
1664 * format( identifier, const expression, const expression )
1665 * format_arg( const expression )
1666 * tls_model( string literal )
1667 * visibility( string literal )
1668 * regparm( const expression )
1669 * model( string leteral )
1670 * trap_exit( const expression )
1671 * sp_switch( string literal )
1673 * The following attributes might have arguments
1674 * weak_ref( string literal )
1675 * non_null( const expression // ',' )
1676 * interrupt( string literal )
1677 * sentinel( constant expression )
1679 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1681 gnu_attribute_t *head = *attributes;
1682 gnu_attribute_t *last = *attributes;
1683 decl_modifiers_t modifiers = 0;
1684 gnu_attribute_t *attribute;
1686 eat(T___attribute__);
1687 expect('(', end_error);
1688 expect('(', end_error);
1690 if (token.type != ')') {
1691 /* find the end of the list */
1693 while (last->next != NULL)
1697 /* non-empty attribute list */
1700 if (token.type == T_const) {
1702 } else if (token.type == T_volatile) {
1704 } else if (token.type == T_cdecl) {
1705 /* __attribute__((cdecl)), WITH ms mode */
1707 } else if (token.type == T_IDENTIFIER) {
1708 const symbol_t *sym = token.v.symbol;
1711 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1718 for (i = 0; i < GNU_AK_LAST; ++i) {
1719 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1722 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1725 if (kind == GNU_AK_LAST) {
1726 if (warning.attribute)
1727 warningf(HERE, "'%s' attribute directive ignored", name);
1729 /* skip possible arguments */
1730 if (token.type == '(') {
1731 eat_until_matching_token(')');
1734 /* check for arguments */
1735 attribute = allocate_gnu_attribute(kind);
1736 if (token.type == '(') {
1738 if (token.type == ')') {
1739 /* empty args are allowed */
1742 attribute->have_arguments = true;
1746 case GNU_AK_VOLATILE:
1751 case GNU_AK_NOCOMMON:
1753 case GNU_AK_NOTSHARED:
1754 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1755 case GNU_AK_WARN_UNUSED_RESULT:
1756 case GNU_AK_LONGCALL:
1757 case GNU_AK_SHORTCALL:
1758 case GNU_AK_LONG_CALL:
1759 case GNU_AK_SHORT_CALL:
1760 case GNU_AK_FUNCTION_VECTOR:
1761 case GNU_AK_INTERRUPT_HANDLER:
1762 case GNU_AK_NMI_HANDLER:
1763 case GNU_AK_NESTING:
1767 case GNU_AK_EIGTHBIT_DATA:
1768 case GNU_AK_TINY_DATA:
1769 case GNU_AK_SAVEALL:
1770 case GNU_AK_FLATTEN:
1771 case GNU_AK_SSEREGPARM:
1772 case GNU_AK_EXTERNALLY_VISIBLE:
1773 case GNU_AK_RETURN_TWICE:
1774 case GNU_AK_MAY_ALIAS:
1775 case GNU_AK_MS_STRUCT:
1776 case GNU_AK_GCC_STRUCT:
1779 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1780 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1781 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1782 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1783 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1784 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1785 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1786 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1787 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1788 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1789 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1790 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1791 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1792 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1793 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1794 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1795 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1796 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1798 case GNU_AK_ALIGNED:
1799 /* __align__ may be used without an argument */
1800 if (attribute->have_arguments) {
1801 parse_gnu_attribute_const_arg(attribute);
1805 case GNU_AK_FORMAT_ARG:
1806 case GNU_AK_REGPARM:
1807 case GNU_AK_TRAP_EXIT:
1808 if (!attribute->have_arguments) {
1809 /* should have arguments */
1810 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1811 attribute->invalid = true;
1813 parse_gnu_attribute_const_arg(attribute);
1816 case GNU_AK_SECTION:
1817 case GNU_AK_SP_SWITCH:
1818 if (!attribute->have_arguments) {
1819 /* should have arguments */
1820 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1821 attribute->invalid = true;
1823 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1826 if (!attribute->have_arguments) {
1827 /* should have arguments */
1828 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1829 attribute->invalid = true;
1831 parse_gnu_attribute_format_args(attribute);
1833 case GNU_AK_WEAKREF:
1834 /* may have one string argument */
1835 if (attribute->have_arguments)
1836 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1838 case GNU_AK_NONNULL:
1839 if (attribute->have_arguments)
1840 parse_gnu_attribute_const_arg_list(attribute);
1842 case GNU_AK_TLS_MODEL:
1843 if (!attribute->have_arguments) {
1844 /* should have arguments */
1845 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1847 parse_gnu_attribute_tls_model_arg(attribute);
1849 case GNU_AK_VISIBILITY:
1850 if (!attribute->have_arguments) {
1851 /* should have arguments */
1852 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1854 parse_gnu_attribute_visibility_arg(attribute);
1857 if (!attribute->have_arguments) {
1858 /* should have arguments */
1859 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1861 parse_gnu_attribute_model_arg(attribute);
1865 if (!attribute->have_arguments) {
1866 /* should have arguments */
1867 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1869 parse_gnu_attribute_mode_arg(attribute);
1872 case GNU_AK_INTERRUPT:
1873 /* may have one string argument */
1874 if (attribute->have_arguments)
1875 parse_gnu_attribute_interrupt_arg(attribute);
1877 case GNU_AK_SENTINEL:
1878 /* may have one string argument */
1879 if (attribute->have_arguments)
1880 parse_gnu_attribute_const_arg(attribute);
1883 /* already handled */
1887 check_no_argument(attribute, name);
1890 if (attribute != NULL) {
1892 last->next = attribute;
1895 head = last = attribute;
1899 if (token.type != ',')
1904 expect(')', end_error);
1905 expect(')', end_error);
1913 * Parse GNU attributes.
1915 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1917 decl_modifiers_t modifiers = 0;
1920 switch (token.type) {
1921 case T___attribute__:
1922 modifiers |= parse_gnu_attribute(attributes);
1927 expect('(', end_error);
1928 if (token.type != T_STRING_LITERAL) {
1929 parse_error_expected("while parsing assembler attribute",
1930 T_STRING_LITERAL, NULL);
1931 eat_until_matching_token('(');
1934 parse_string_literals();
1936 expect(')', end_error);
1939 case T_cdecl: modifiers |= DM_CDECL; break;
1940 case T__fastcall: modifiers |= DM_FASTCALL; break;
1941 case T__stdcall: modifiers |= DM_STDCALL; break;
1944 /* TODO record modifier */
1946 warningf(HERE, "Ignoring declaration modifier %K", &token);
1950 default: return modifiers;
1957 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1959 static entity_t *determine_lhs_ent(expression_t *const expr,
1962 switch (expr->kind) {
1963 case EXPR_REFERENCE: {
1964 entity_t *const entity = expr->reference.entity;
1965 /* we should only find variables as lvalues... */
1966 if (entity->base.kind != ENTITY_VARIABLE
1967 && entity->base.kind != ENTITY_PARAMETER)
1973 case EXPR_ARRAY_ACCESS: {
1974 expression_t *const ref = expr->array_access.array_ref;
1975 entity_t * ent = NULL;
1976 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1977 ent = determine_lhs_ent(ref, lhs_ent);
1980 mark_vars_read(expr->select.compound, lhs_ent);
1982 mark_vars_read(expr->array_access.index, lhs_ent);
1987 if (is_type_compound(skip_typeref(expr->base.type))) {
1988 return determine_lhs_ent(expr->select.compound, lhs_ent);
1990 mark_vars_read(expr->select.compound, lhs_ent);
1995 case EXPR_UNARY_DEREFERENCE: {
1996 expression_t *const val = expr->unary.value;
1997 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1999 return determine_lhs_ent(val->unary.value, lhs_ent);
2001 mark_vars_read(val, NULL);
2007 mark_vars_read(expr, NULL);
2012 #define ENT_ANY ((entity_t*)-1)
2015 * Mark declarations, which are read. This is used to detect variables, which
2019 * x is not marked as "read", because it is only read to calculate its own new
2023 * x and y are not detected as "not read", because multiple variables are
2026 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2028 switch (expr->kind) {
2029 case EXPR_REFERENCE: {
2030 entity_t *const entity = expr->reference.entity;
2031 if (entity->kind != ENTITY_VARIABLE
2032 && entity->kind != ENTITY_PARAMETER)
2035 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2036 if (entity->kind == ENTITY_VARIABLE) {
2037 entity->variable.read = true;
2039 entity->parameter.read = true;
2046 // TODO respect pure/const
2047 mark_vars_read(expr->call.function, NULL);
2048 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2049 mark_vars_read(arg->expression, NULL);
2053 case EXPR_CONDITIONAL:
2054 // TODO lhs_decl should depend on whether true/false have an effect
2055 mark_vars_read(expr->conditional.condition, NULL);
2056 if (expr->conditional.true_expression != NULL)
2057 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2058 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2062 if (lhs_ent == ENT_ANY
2063 && !is_type_compound(skip_typeref(expr->base.type)))
2065 mark_vars_read(expr->select.compound, lhs_ent);
2068 case EXPR_ARRAY_ACCESS: {
2069 expression_t *const ref = expr->array_access.array_ref;
2070 mark_vars_read(ref, lhs_ent);
2071 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2072 mark_vars_read(expr->array_access.index, lhs_ent);
2077 mark_vars_read(expr->va_arge.ap, lhs_ent);
2080 case EXPR_UNARY_CAST:
2081 /* Special case: Use void cast to mark a variable as "read" */
2082 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2087 case EXPR_UNARY_THROW:
2088 if (expr->unary.value == NULL)
2091 case EXPR_UNARY_DEREFERENCE:
2092 case EXPR_UNARY_DELETE:
2093 case EXPR_UNARY_DELETE_ARRAY:
2094 if (lhs_ent == ENT_ANY)
2098 case EXPR_UNARY_NEGATE:
2099 case EXPR_UNARY_PLUS:
2100 case EXPR_UNARY_BITWISE_NEGATE:
2101 case EXPR_UNARY_NOT:
2102 case EXPR_UNARY_TAKE_ADDRESS:
2103 case EXPR_UNARY_POSTFIX_INCREMENT:
2104 case EXPR_UNARY_POSTFIX_DECREMENT:
2105 case EXPR_UNARY_PREFIX_INCREMENT:
2106 case EXPR_UNARY_PREFIX_DECREMENT:
2107 case EXPR_UNARY_CAST_IMPLICIT:
2108 case EXPR_UNARY_ASSUME:
2110 mark_vars_read(expr->unary.value, lhs_ent);
2113 case EXPR_BINARY_ADD:
2114 case EXPR_BINARY_SUB:
2115 case EXPR_BINARY_MUL:
2116 case EXPR_BINARY_DIV:
2117 case EXPR_BINARY_MOD:
2118 case EXPR_BINARY_EQUAL:
2119 case EXPR_BINARY_NOTEQUAL:
2120 case EXPR_BINARY_LESS:
2121 case EXPR_BINARY_LESSEQUAL:
2122 case EXPR_BINARY_GREATER:
2123 case EXPR_BINARY_GREATEREQUAL:
2124 case EXPR_BINARY_BITWISE_AND:
2125 case EXPR_BINARY_BITWISE_OR:
2126 case EXPR_BINARY_BITWISE_XOR:
2127 case EXPR_BINARY_LOGICAL_AND:
2128 case EXPR_BINARY_LOGICAL_OR:
2129 case EXPR_BINARY_SHIFTLEFT:
2130 case EXPR_BINARY_SHIFTRIGHT:
2131 case EXPR_BINARY_COMMA:
2132 case EXPR_BINARY_ISGREATER:
2133 case EXPR_BINARY_ISGREATEREQUAL:
2134 case EXPR_BINARY_ISLESS:
2135 case EXPR_BINARY_ISLESSEQUAL:
2136 case EXPR_BINARY_ISLESSGREATER:
2137 case EXPR_BINARY_ISUNORDERED:
2138 mark_vars_read(expr->binary.left, lhs_ent);
2139 mark_vars_read(expr->binary.right, lhs_ent);
2142 case EXPR_BINARY_ASSIGN:
2143 case EXPR_BINARY_MUL_ASSIGN:
2144 case EXPR_BINARY_DIV_ASSIGN:
2145 case EXPR_BINARY_MOD_ASSIGN:
2146 case EXPR_BINARY_ADD_ASSIGN:
2147 case EXPR_BINARY_SUB_ASSIGN:
2148 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2149 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2150 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2151 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2152 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2153 if (lhs_ent == ENT_ANY)
2155 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2156 mark_vars_read(expr->binary.right, lhs_ent);
2161 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2167 case EXPR_CHARACTER_CONSTANT:
2168 case EXPR_WIDE_CHARACTER_CONSTANT:
2169 case EXPR_STRING_LITERAL:
2170 case EXPR_WIDE_STRING_LITERAL:
2171 case EXPR_COMPOUND_LITERAL: // TODO init?
2173 case EXPR_CLASSIFY_TYPE:
2176 case EXPR_BUILTIN_SYMBOL:
2177 case EXPR_BUILTIN_CONSTANT_P:
2178 case EXPR_BUILTIN_PREFETCH:
2180 case EXPR_STATEMENT: // TODO
2181 case EXPR_LABEL_ADDRESS:
2182 case EXPR_REFERENCE_ENUM_VALUE:
2186 panic("unhandled expression");
2189 static designator_t *parse_designation(void)
2191 designator_t *result = NULL;
2192 designator_t *last = NULL;
2195 designator_t *designator;
2196 switch (token.type) {
2198 designator = allocate_ast_zero(sizeof(designator[0]));
2199 designator->source_position = token.source_position;
2201 add_anchor_token(']');
2202 designator->array_index = parse_constant_expression();
2203 rem_anchor_token(']');
2204 expect(']', end_error);
2207 designator = allocate_ast_zero(sizeof(designator[0]));
2208 designator->source_position = token.source_position;
2210 if (token.type != T_IDENTIFIER) {
2211 parse_error_expected("while parsing designator",
2212 T_IDENTIFIER, NULL);
2215 designator->symbol = token.v.symbol;
2219 expect('=', end_error);
2223 assert(designator != NULL);
2225 last->next = designator;
2227 result = designator;
2235 static initializer_t *initializer_from_string(array_type_t *type,
2236 const string_t *const string)
2238 /* TODO: check len vs. size of array type */
2241 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2242 initializer->string.string = *string;
2247 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2248 wide_string_t *const string)
2250 /* TODO: check len vs. size of array type */
2253 initializer_t *const initializer =
2254 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2255 initializer->wide_string.string = *string;
2261 * Build an initializer from a given expression.
2263 static initializer_t *initializer_from_expression(type_t *orig_type,
2264 expression_t *expression)
2266 /* TODO check that expression is a constant expression */
2268 /* § 6.7.8.14/15 char array may be initialized by string literals */
2269 type_t *type = skip_typeref(orig_type);
2270 type_t *expr_type_orig = expression->base.type;
2271 type_t *expr_type = skip_typeref(expr_type_orig);
2272 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2273 array_type_t *const array_type = &type->array;
2274 type_t *const element_type = skip_typeref(array_type->element_type);
2276 if (element_type->kind == TYPE_ATOMIC) {
2277 atomic_type_kind_t akind = element_type->atomic.akind;
2278 switch (expression->kind) {
2279 case EXPR_STRING_LITERAL:
2280 if (akind == ATOMIC_TYPE_CHAR
2281 || akind == ATOMIC_TYPE_SCHAR
2282 || akind == ATOMIC_TYPE_UCHAR) {
2283 return initializer_from_string(array_type,
2284 &expression->string.value);
2287 case EXPR_WIDE_STRING_LITERAL: {
2288 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2289 if (get_unqualified_type(element_type) == bare_wchar_type) {
2290 return initializer_from_wide_string(array_type,
2291 &expression->wide_string.value);
2301 assign_error_t error = semantic_assign(type, expression);
2302 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2304 report_assign_error(error, type, expression, "initializer",
2305 &expression->base.source_position);
2307 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2309 if (type->kind == TYPE_BITFIELD) {
2310 type = type->bitfield.base_type;
2313 result->value.value = create_implicit_cast(expression, type);
2319 * Checks if a given expression can be used as an constant initializer.
2321 static bool is_initializer_constant(const expression_t *expression)
2323 return is_constant_expression(expression)
2324 || is_address_constant(expression);
2328 * Parses an scalar initializer.
2330 * § 6.7.8.11; eat {} without warning
2332 static initializer_t *parse_scalar_initializer(type_t *type,
2333 bool must_be_constant)
2335 /* there might be extra {} hierarchies */
2337 if (token.type == '{') {
2339 warningf(HERE, "extra curly braces around scalar initializer");
2343 } while (token.type == '{');
2346 expression_t *expression = parse_assignment_expression();
2347 mark_vars_read(expression, NULL);
2348 if (must_be_constant && !is_initializer_constant(expression)) {
2349 errorf(&expression->base.source_position,
2350 "Initialisation expression '%E' is not constant",
2354 initializer_t *initializer = initializer_from_expression(type, expression);
2356 if (initializer == NULL) {
2357 errorf(&expression->base.source_position,
2358 "expression '%E' (type '%T') doesn't match expected type '%T'",
2359 expression, expression->base.type, type);
2364 bool additional_warning_displayed = false;
2365 while (braces > 0) {
2366 if (token.type == ',') {
2369 if (token.type != '}') {
2370 if (!additional_warning_displayed && warning.other) {
2371 warningf(HERE, "additional elements in scalar initializer");
2372 additional_warning_displayed = true;
2383 * An entry in the type path.
2385 typedef struct type_path_entry_t type_path_entry_t;
2386 struct type_path_entry_t {
2387 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2389 size_t index; /**< For array types: the current index. */
2390 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2395 * A type path expression a position inside compound or array types.
2397 typedef struct type_path_t type_path_t;
2398 struct type_path_t {
2399 type_path_entry_t *path; /**< An flexible array containing the current path. */
2400 type_t *top_type; /**< type of the element the path points */
2401 size_t max_index; /**< largest index in outermost array */
2405 * Prints a type path for debugging.
2407 static __attribute__((unused)) void debug_print_type_path(
2408 const type_path_t *path)
2410 size_t len = ARR_LEN(path->path);
2412 for (size_t i = 0; i < len; ++i) {
2413 const type_path_entry_t *entry = & path->path[i];
2415 type_t *type = skip_typeref(entry->type);
2416 if (is_type_compound(type)) {
2417 /* in gcc mode structs can have no members */
2418 if (entry->v.compound_entry == NULL) {
2422 fprintf(stderr, ".%s",
2423 entry->v.compound_entry->base.symbol->string);
2424 } else if (is_type_array(type)) {
2425 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2427 fprintf(stderr, "-INVALID-");
2430 if (path->top_type != NULL) {
2431 fprintf(stderr, " (");
2432 print_type(path->top_type);
2433 fprintf(stderr, ")");
2438 * Return the top type path entry, ie. in a path
2439 * (type).a.b returns the b.
2441 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2443 size_t len = ARR_LEN(path->path);
2445 return &path->path[len-1];
2449 * Enlarge the type path by an (empty) element.
2451 static type_path_entry_t *append_to_type_path(type_path_t *path)
2453 size_t len = ARR_LEN(path->path);
2454 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2456 type_path_entry_t *result = & path->path[len];
2457 memset(result, 0, sizeof(result[0]));
2462 * Descending into a sub-type. Enter the scope of the current top_type.
2464 static void descend_into_subtype(type_path_t *path)
2466 type_t *orig_top_type = path->top_type;
2467 type_t *top_type = skip_typeref(orig_top_type);
2469 type_path_entry_t *top = append_to_type_path(path);
2470 top->type = top_type;
2472 if (is_type_compound(top_type)) {
2473 compound_t *compound = top_type->compound.compound;
2474 entity_t *entry = compound->members.entities;
2476 if (entry != NULL) {
2477 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2478 top->v.compound_entry = &entry->declaration;
2479 path->top_type = entry->declaration.type;
2481 path->top_type = NULL;
2483 } else if (is_type_array(top_type)) {
2485 path->top_type = top_type->array.element_type;
2487 assert(!is_type_valid(top_type));
2492 * Pop an entry from the given type path, ie. returning from
2493 * (type).a.b to (type).a
2495 static void ascend_from_subtype(type_path_t *path)
2497 type_path_entry_t *top = get_type_path_top(path);
2499 path->top_type = top->type;
2501 size_t len = ARR_LEN(path->path);
2502 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2506 * Pop entries from the given type path until the given
2507 * path level is reached.
2509 static void ascend_to(type_path_t *path, size_t top_path_level)
2511 size_t len = ARR_LEN(path->path);
2513 while (len > top_path_level) {
2514 ascend_from_subtype(path);
2515 len = ARR_LEN(path->path);
2519 static bool walk_designator(type_path_t *path, const designator_t *designator,
2520 bool used_in_offsetof)
2522 for (; designator != NULL; designator = designator->next) {
2523 type_path_entry_t *top = get_type_path_top(path);
2524 type_t *orig_type = top->type;
2526 type_t *type = skip_typeref(orig_type);
2528 if (designator->symbol != NULL) {
2529 symbol_t *symbol = designator->symbol;
2530 if (!is_type_compound(type)) {
2531 if (is_type_valid(type)) {
2532 errorf(&designator->source_position,
2533 "'.%Y' designator used for non-compound type '%T'",
2537 top->type = type_error_type;
2538 top->v.compound_entry = NULL;
2539 orig_type = type_error_type;
2541 compound_t *compound = type->compound.compound;
2542 entity_t *iter = compound->members.entities;
2543 for (; iter != NULL; iter = iter->base.next) {
2544 if (iter->base.symbol == symbol) {
2549 errorf(&designator->source_position,
2550 "'%T' has no member named '%Y'", orig_type, symbol);
2553 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2554 if (used_in_offsetof) {
2555 type_t *real_type = skip_typeref(iter->declaration.type);
2556 if (real_type->kind == TYPE_BITFIELD) {
2557 errorf(&designator->source_position,
2558 "offsetof designator '%Y' may not specify bitfield",
2564 top->type = orig_type;
2565 top->v.compound_entry = &iter->declaration;
2566 orig_type = iter->declaration.type;
2569 expression_t *array_index = designator->array_index;
2570 assert(designator->array_index != NULL);
2572 if (!is_type_array(type)) {
2573 if (is_type_valid(type)) {
2574 errorf(&designator->source_position,
2575 "[%E] designator used for non-array type '%T'",
2576 array_index, orig_type);
2581 long index = fold_constant(array_index);
2582 if (!used_in_offsetof) {
2584 errorf(&designator->source_position,
2585 "array index [%E] must be positive", array_index);
2586 } else if (type->array.size_constant) {
2587 long array_size = type->array.size;
2588 if (index >= array_size) {
2589 errorf(&designator->source_position,
2590 "designator [%E] (%d) exceeds array size %d",
2591 array_index, index, array_size);
2596 top->type = orig_type;
2597 top->v.index = (size_t) index;
2598 orig_type = type->array.element_type;
2600 path->top_type = orig_type;
2602 if (designator->next != NULL) {
2603 descend_into_subtype(path);
2612 static void advance_current_object(type_path_t *path, size_t top_path_level)
2614 type_path_entry_t *top = get_type_path_top(path);
2616 type_t *type = skip_typeref(top->type);
2617 if (is_type_union(type)) {
2618 /* in unions only the first element is initialized */
2619 top->v.compound_entry = NULL;
2620 } else if (is_type_struct(type)) {
2621 declaration_t *entry = top->v.compound_entry;
2623 entity_t *next_entity = entry->base.next;
2624 if (next_entity != NULL) {
2625 assert(is_declaration(next_entity));
2626 entry = &next_entity->declaration;
2631 top->v.compound_entry = entry;
2632 if (entry != NULL) {
2633 path->top_type = entry->type;
2636 } else if (is_type_array(type)) {
2637 assert(is_type_array(type));
2641 if (!type->array.size_constant || top->v.index < type->array.size) {
2645 assert(!is_type_valid(type));
2649 /* we're past the last member of the current sub-aggregate, try if we
2650 * can ascend in the type hierarchy and continue with another subobject */
2651 size_t len = ARR_LEN(path->path);
2653 if (len > top_path_level) {
2654 ascend_from_subtype(path);
2655 advance_current_object(path, top_path_level);
2657 path->top_type = NULL;
2662 * skip until token is found.
2664 static void skip_until(int type)
2666 while (token.type != type) {
2667 if (token.type == T_EOF)
2674 * skip any {...} blocks until a closing bracket is reached.
2676 static void skip_initializers(void)
2678 if (token.type == '{')
2681 while (token.type != '}') {
2682 if (token.type == T_EOF)
2684 if (token.type == '{') {
2692 static initializer_t *create_empty_initializer(void)
2694 static initializer_t empty_initializer
2695 = { .list = { { INITIALIZER_LIST }, 0 } };
2696 return &empty_initializer;
2700 * Parse a part of an initialiser for a struct or union,
2702 static initializer_t *parse_sub_initializer(type_path_t *path,
2703 type_t *outer_type, size_t top_path_level,
2704 parse_initializer_env_t *env)
2706 if (token.type == '}') {
2707 /* empty initializer */
2708 return create_empty_initializer();
2711 type_t *orig_type = path->top_type;
2712 type_t *type = NULL;
2714 if (orig_type == NULL) {
2715 /* We are initializing an empty compound. */
2717 type = skip_typeref(orig_type);
2720 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2723 designator_t *designator = NULL;
2724 if (token.type == '.' || token.type == '[') {
2725 designator = parse_designation();
2726 goto finish_designator;
2727 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2728 /* GNU-style designator ("identifier: value") */
2729 designator = allocate_ast_zero(sizeof(designator[0]));
2730 designator->source_position = token.source_position;
2731 designator->symbol = token.v.symbol;
2736 /* reset path to toplevel, evaluate designator from there */
2737 ascend_to(path, top_path_level);
2738 if (!walk_designator(path, designator, false)) {
2739 /* can't continue after designation error */
2743 initializer_t *designator_initializer
2744 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2745 designator_initializer->designator.designator = designator;
2746 ARR_APP1(initializer_t*, initializers, designator_initializer);
2748 orig_type = path->top_type;
2749 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2754 if (token.type == '{') {
2755 if (type != NULL && is_type_scalar(type)) {
2756 sub = parse_scalar_initializer(type, env->must_be_constant);
2760 if (env->entity != NULL) {
2762 "extra brace group at end of initializer for '%Y'",
2763 env->entity->base.symbol);
2765 errorf(HERE, "extra brace group at end of initializer");
2768 descend_into_subtype(path);
2770 add_anchor_token('}');
2771 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2773 rem_anchor_token('}');
2776 ascend_from_subtype(path);
2777 expect('}', end_error);
2779 expect('}', end_error);
2780 goto error_parse_next;
2784 /* must be an expression */
2785 expression_t *expression = parse_assignment_expression();
2787 if (env->must_be_constant && !is_initializer_constant(expression)) {
2788 errorf(&expression->base.source_position,
2789 "Initialisation expression '%E' is not constant",
2794 /* we are already outside, ... */
2795 type_t *const outer_type_skip = skip_typeref(outer_type);
2796 if (is_type_compound(outer_type_skip) &&
2797 !outer_type_skip->compound.compound->complete) {
2798 goto error_parse_next;
2803 /* handle { "string" } special case */
2804 if ((expression->kind == EXPR_STRING_LITERAL
2805 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2806 && outer_type != NULL) {
2807 sub = initializer_from_expression(outer_type, expression);
2809 if (token.type == ',') {
2812 if (token.type != '}' && warning.other) {
2813 warningf(HERE, "excessive elements in initializer for type '%T'",
2816 /* TODO: eat , ... */
2821 /* descend into subtypes until expression matches type */
2823 orig_type = path->top_type;
2824 type = skip_typeref(orig_type);
2826 sub = initializer_from_expression(orig_type, expression);
2830 if (!is_type_valid(type)) {
2833 if (is_type_scalar(type)) {
2834 errorf(&expression->base.source_position,
2835 "expression '%E' doesn't match expected type '%T'",
2836 expression, orig_type);
2840 descend_into_subtype(path);
2844 /* update largest index of top array */
2845 const type_path_entry_t *first = &path->path[0];
2846 type_t *first_type = first->type;
2847 first_type = skip_typeref(first_type);
2848 if (is_type_array(first_type)) {
2849 size_t index = first->v.index;
2850 if (index > path->max_index)
2851 path->max_index = index;
2855 /* append to initializers list */
2856 ARR_APP1(initializer_t*, initializers, sub);
2859 if (warning.other) {
2860 if (env->entity != NULL) {
2861 warningf(HERE, "excess elements in struct initializer for '%Y'",
2862 env->entity->base.symbol);
2864 warningf(HERE, "excess elements in struct initializer");
2870 if (token.type == '}') {
2873 expect(',', end_error);
2874 if (token.type == '}') {
2879 /* advance to the next declaration if we are not at the end */
2880 advance_current_object(path, top_path_level);
2881 orig_type = path->top_type;
2882 if (orig_type != NULL)
2883 type = skip_typeref(orig_type);
2889 size_t len = ARR_LEN(initializers);
2890 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2891 initializer_t *result = allocate_ast_zero(size);
2892 result->kind = INITIALIZER_LIST;
2893 result->list.len = len;
2894 memcpy(&result->list.initializers, initializers,
2895 len * sizeof(initializers[0]));
2897 DEL_ARR_F(initializers);
2898 ascend_to(path, top_path_level+1);
2903 skip_initializers();
2904 DEL_ARR_F(initializers);
2905 ascend_to(path, top_path_level+1);
2910 * Parses an initializer. Parsers either a compound literal
2911 * (env->declaration == NULL) or an initializer of a declaration.
2913 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2915 type_t *type = skip_typeref(env->type);
2916 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2917 initializer_t *result;
2919 if (is_type_scalar(type)) {
2920 result = parse_scalar_initializer(type, env->must_be_constant);
2921 } else if (token.type == '{') {
2925 memset(&path, 0, sizeof(path));
2926 path.top_type = env->type;
2927 path.path = NEW_ARR_F(type_path_entry_t, 0);
2929 descend_into_subtype(&path);
2931 add_anchor_token('}');
2932 result = parse_sub_initializer(&path, env->type, 1, env);
2933 rem_anchor_token('}');
2935 max_index = path.max_index;
2936 DEL_ARR_F(path.path);
2938 expect('}', end_error);
2940 /* parse_scalar_initializer() also works in this case: we simply
2941 * have an expression without {} around it */
2942 result = parse_scalar_initializer(type, env->must_be_constant);
2945 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2946 * the array type size */
2947 if (is_type_array(type) && type->array.size_expression == NULL
2948 && result != NULL) {
2950 switch (result->kind) {
2951 case INITIALIZER_LIST:
2952 assert(max_index != 0xdeadbeaf);
2953 size = max_index + 1;
2956 case INITIALIZER_STRING:
2957 size = result->string.string.size;
2960 case INITIALIZER_WIDE_STRING:
2961 size = result->wide_string.string.size;
2964 case INITIALIZER_DESIGNATOR:
2965 case INITIALIZER_VALUE:
2966 /* can happen for parse errors */
2971 internal_errorf(HERE, "invalid initializer type");
2974 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2975 cnst->base.type = type_size_t;
2976 cnst->conste.v.int_value = size;
2978 type_t *new_type = duplicate_type(type);
2980 new_type->array.size_expression = cnst;
2981 new_type->array.size_constant = true;
2982 new_type->array.has_implicit_size = true;
2983 new_type->array.size = size;
2984 env->type = new_type;
2992 static void append_entity(scope_t *scope, entity_t *entity)
2994 if (scope->last_entity != NULL) {
2995 scope->last_entity->base.next = entity;
2997 scope->entities = entity;
2999 scope->last_entity = entity;
3003 static compound_t *parse_compound_type_specifier(bool is_struct)
3005 gnu_attribute_t *attributes = NULL;
3006 decl_modifiers_t modifiers = 0;
3013 symbol_t *symbol = NULL;
3014 compound_t *compound = NULL;
3016 if (token.type == T___attribute__) {
3017 modifiers |= parse_attributes(&attributes);
3020 if (token.type == T_IDENTIFIER) {
3021 symbol = token.v.symbol;
3024 namespace_tag_t const namespc =
3025 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3026 entity_t *entity = get_entity(symbol, namespc);
3027 if (entity != NULL) {
3028 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3029 compound = &entity->compound;
3030 if (compound->base.parent_scope != current_scope &&
3031 (token.type == '{' || token.type == ';')) {
3032 /* we're in an inner scope and have a definition. Override
3033 existing definition in outer scope */
3035 } else if (compound->complete && token.type == '{') {
3036 assert(symbol != NULL);
3037 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3038 is_struct ? "struct" : "union", symbol,
3039 &compound->base.source_position);
3040 /* clear members in the hope to avoid further errors */
3041 compound->members.entities = NULL;
3044 } else if (token.type != '{') {
3046 parse_error_expected("while parsing struct type specifier",
3047 T_IDENTIFIER, '{', NULL);
3049 parse_error_expected("while parsing union type specifier",
3050 T_IDENTIFIER, '{', NULL);
3056 if (compound == NULL) {
3057 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3058 entity_t *entity = allocate_entity_zero(kind);
3059 compound = &entity->compound;
3061 compound->base.namespc =
3062 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3063 compound->base.source_position = token.source_position;
3064 compound->base.symbol = symbol;
3065 compound->base.parent_scope = current_scope;
3066 if (symbol != NULL) {
3067 environment_push(entity);
3069 append_entity(current_scope, entity);
3072 if (token.type == '{') {
3073 parse_compound_type_entries(compound);
3074 modifiers |= parse_attributes(&attributes);
3076 if (symbol == NULL) {
3077 assert(anonymous_entity == NULL);
3078 anonymous_entity = (entity_t*)compound;
3082 compound->modifiers |= modifiers;
3086 static void parse_enum_entries(type_t *const enum_type)
3090 if (token.type == '}') {
3091 errorf(HERE, "empty enum not allowed");
3096 add_anchor_token('}');
3098 if (token.type != T_IDENTIFIER) {
3099 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3101 rem_anchor_token('}');
3105 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3106 entity->enum_value.enum_type = enum_type;
3107 entity->base.symbol = token.v.symbol;
3108 entity->base.source_position = token.source_position;
3111 if (token.type == '=') {
3113 expression_t *value = parse_constant_expression();
3115 value = create_implicit_cast(value, enum_type);
3116 entity->enum_value.value = value;
3121 record_entity(entity, false);
3123 if (token.type != ',')
3126 } while (token.type != '}');
3127 rem_anchor_token('}');
3129 expect('}', end_error);
3135 static type_t *parse_enum_specifier(void)
3137 gnu_attribute_t *attributes = NULL;
3142 if (token.type == T_IDENTIFIER) {
3143 symbol = token.v.symbol;
3146 entity = get_entity(symbol, NAMESPACE_ENUM);
3147 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3148 } else if (token.type != '{') {
3149 parse_error_expected("while parsing enum type specifier",
3150 T_IDENTIFIER, '{', NULL);
3157 if (entity == NULL) {
3158 entity = allocate_entity_zero(ENTITY_ENUM);
3159 entity->base.namespc = NAMESPACE_ENUM;
3160 entity->base.source_position = token.source_position;
3161 entity->base.symbol = symbol;
3162 entity->base.parent_scope = current_scope;
3165 type_t *const type = allocate_type_zero(TYPE_ENUM);
3166 type->enumt.enume = &entity->enume;
3168 if (token.type == '{') {
3169 if (entity->enume.complete) {
3170 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3171 symbol, &entity->base.source_position);
3173 if (symbol != NULL) {
3174 environment_push(entity);
3176 append_entity(current_scope, entity);
3177 entity->enume.complete = true;
3179 parse_enum_entries(type);
3180 parse_attributes(&attributes);
3182 if (symbol == NULL) {
3183 assert(anonymous_entity == NULL);
3184 anonymous_entity = entity;
3186 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3187 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3195 * if a symbol is a typedef to another type, return true
3197 static bool is_typedef_symbol(symbol_t *symbol)
3199 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3200 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3203 static type_t *parse_typeof(void)
3209 expect('(', end_error);
3210 add_anchor_token(')');
3212 expression_t *expression = NULL;
3214 bool old_type_prop = in_type_prop;
3215 bool old_gcc_extension = in_gcc_extension;
3216 in_type_prop = true;
3218 while (token.type == T___extension__) {
3219 /* This can be a prefix to a typename or an expression. */
3221 in_gcc_extension = true;
3223 switch (token.type) {
3225 if (is_typedef_symbol(token.v.symbol)) {
3226 type = parse_typename();
3228 expression = parse_expression();
3229 type = expression->base.type;
3234 type = parse_typename();
3238 expression = parse_expression();
3239 type = expression->base.type;
3242 in_type_prop = old_type_prop;
3243 in_gcc_extension = old_gcc_extension;
3245 rem_anchor_token(')');
3246 expect(')', end_error);
3248 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3249 typeof_type->typeoft.expression = expression;
3250 typeof_type->typeoft.typeof_type = type;
3257 typedef enum specifiers_t {
3258 SPECIFIER_SIGNED = 1 << 0,
3259 SPECIFIER_UNSIGNED = 1 << 1,
3260 SPECIFIER_LONG = 1 << 2,
3261 SPECIFIER_INT = 1 << 3,
3262 SPECIFIER_DOUBLE = 1 << 4,
3263 SPECIFIER_CHAR = 1 << 5,
3264 SPECIFIER_WCHAR_T = 1 << 6,
3265 SPECIFIER_SHORT = 1 << 7,
3266 SPECIFIER_LONG_LONG = 1 << 8,
3267 SPECIFIER_FLOAT = 1 << 9,
3268 SPECIFIER_BOOL = 1 << 10,
3269 SPECIFIER_VOID = 1 << 11,
3270 SPECIFIER_INT8 = 1 << 12,
3271 SPECIFIER_INT16 = 1 << 13,
3272 SPECIFIER_INT32 = 1 << 14,
3273 SPECIFIER_INT64 = 1 << 15,
3274 SPECIFIER_INT128 = 1 << 16,
3275 SPECIFIER_COMPLEX = 1 << 17,
3276 SPECIFIER_IMAGINARY = 1 << 18,
3279 static type_t *create_builtin_type(symbol_t *const symbol,
3280 type_t *const real_type)
3282 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3283 type->builtin.symbol = symbol;
3284 type->builtin.real_type = real_type;
3286 type_t *result = typehash_insert(type);
3287 if (type != result) {
3294 static type_t *get_typedef_type(symbol_t *symbol)
3296 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3297 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3300 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3301 type->typedeft.typedefe = &entity->typedefe;
3307 * check for the allowed MS alignment values.
3309 static bool check_alignment_value(long long intvalue)
3311 if (intvalue < 1 || intvalue > 8192) {
3312 errorf(HERE, "illegal alignment value");
3315 unsigned v = (unsigned)intvalue;
3316 for (unsigned i = 1; i <= 8192; i += i) {
3320 errorf(HERE, "alignment must be power of two");
3324 #define DET_MOD(name, tag) do { \
3325 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3326 *modifiers |= tag; \
3329 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3331 decl_modifiers_t *modifiers = &specifiers->modifiers;
3334 if (token.type == T_restrict) {
3336 DET_MOD(restrict, DM_RESTRICT);
3338 } else if (token.type != T_IDENTIFIER)
3340 symbol_t *symbol = token.v.symbol;
3341 if (symbol == sym_align) {
3343 expect('(', end_error);
3344 if (token.type != T_INTEGER)
3346 if (check_alignment_value(token.v.intvalue)) {
3347 if (specifiers->alignment != 0 && warning.other)
3348 warningf(HERE, "align used more than once");
3349 specifiers->alignment = (unsigned char)token.v.intvalue;
3352 expect(')', end_error);
3353 } else if (symbol == sym_allocate) {
3355 expect('(', end_error);
3356 if (token.type != T_IDENTIFIER)
3358 (void)token.v.symbol;
3359 expect(')', end_error);
3360 } else if (symbol == sym_dllimport) {
3362 DET_MOD(dllimport, DM_DLLIMPORT);
3363 } else if (symbol == sym_dllexport) {
3365 DET_MOD(dllexport, DM_DLLEXPORT);
3366 } else if (symbol == sym_thread) {
3368 DET_MOD(thread, DM_THREAD);
3369 } else if (symbol == sym_naked) {
3371 DET_MOD(naked, DM_NAKED);
3372 } else if (symbol == sym_noinline) {
3374 DET_MOD(noinline, DM_NOINLINE);
3375 } else if (symbol == sym_noreturn) {
3377 DET_MOD(noreturn, DM_NORETURN);
3378 } else if (symbol == sym_nothrow) {
3380 DET_MOD(nothrow, DM_NOTHROW);
3381 } else if (symbol == sym_novtable) {
3383 DET_MOD(novtable, DM_NOVTABLE);
3384 } else if (symbol == sym_property) {
3386 expect('(', end_error);
3388 bool is_get = false;
3389 if (token.type != T_IDENTIFIER)
3391 if (token.v.symbol == sym_get) {
3393 } else if (token.v.symbol == sym_put) {
3395 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3399 expect('=', end_error);
3400 if (token.type != T_IDENTIFIER)
3403 if (specifiers->get_property_sym != NULL) {
3404 errorf(HERE, "get property name already specified");
3406 specifiers->get_property_sym = token.v.symbol;
3409 if (specifiers->put_property_sym != NULL) {
3410 errorf(HERE, "put property name already specified");
3412 specifiers->put_property_sym = token.v.symbol;
3416 if (token.type == ',') {
3422 expect(')', end_error);
3423 } else if (symbol == sym_selectany) {
3425 DET_MOD(selectany, DM_SELECTANY);
3426 } else if (symbol == sym_uuid) {
3428 expect('(', end_error);
3429 if (token.type != T_STRING_LITERAL)
3432 expect(')', end_error);
3433 } else if (symbol == sym_deprecated) {
3435 if (specifiers->deprecated != 0 && warning.other)
3436 warningf(HERE, "deprecated used more than once");
3437 specifiers->deprecated = true;
3438 if (token.type == '(') {
3440 if (token.type == T_STRING_LITERAL) {
3441 specifiers->deprecated_string = token.v.string.begin;
3444 errorf(HERE, "string literal expected");
3446 expect(')', end_error);
3448 } else if (symbol == sym_noalias) {
3450 DET_MOD(noalias, DM_NOALIAS);
3453 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3455 if (token.type == '(')
3459 if (token.type == ',')
3466 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3468 entity_t *entity = allocate_entity_zero(kind);
3469 entity->base.source_position = *HERE;
3470 entity->base.symbol = symbol;
3471 if (is_declaration(entity)) {
3472 entity->declaration.type = type_error_type;
3473 entity->declaration.implicit = true;
3474 } else if (kind == ENTITY_TYPEDEF) {
3475 entity->typedefe.type = type_error_type;
3476 entity->typedefe.builtin = true;
3478 record_entity(entity, false);
3482 static void parse_microsoft_based(based_spec_t *based_spec)
3484 if (token.type != T_IDENTIFIER) {
3485 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3488 symbol_t *symbol = token.v.symbol;
3489 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3491 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3492 errorf(HERE, "'%Y' is not a variable name.", symbol);
3493 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3495 variable_t *variable = &entity->variable;
3497 if (based_spec->base_variable != NULL) {
3498 errorf(HERE, "__based type qualifier specified more than once");
3500 based_spec->source_position = token.source_position;
3501 based_spec->base_variable = variable;
3503 type_t *const type = variable->base.type;
3505 if (is_type_valid(type)) {
3506 if (! is_type_pointer(skip_typeref(type))) {
3507 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3509 if (variable->base.base.parent_scope != file_scope) {
3510 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3518 * Finish the construction of a struct type by calculating
3519 * its size, offsets, alignment.
3521 static void finish_struct_type(compound_type_t *type)
3523 assert(type->compound != NULL);
3525 compound_t *compound = type->compound;
3526 if (!compound->complete)
3531 il_alignment_t alignment = 1;
3532 bool need_pad = false;
3534 entity_t *entry = compound->members.entities;
3535 for (; entry != NULL; entry = entry->base.next) {
3536 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3539 type_t *m_type = skip_typeref(entry->declaration.type);
3540 if (! is_type_valid(m_type)) {
3541 /* simply ignore errors here */
3544 il_alignment_t m_alignment = m_type->base.alignment;
3545 if (m_alignment > alignment)
3546 alignment = m_alignment;
3548 offset = (size + m_alignment - 1) & -m_alignment;
3552 entry->compound_member.offset = offset;
3553 size = offset + m_type->base.size;
3555 if (type->base.alignment != 0) {
3556 alignment = type->base.alignment;
3559 offset = (size + alignment - 1) & -alignment;
3564 if (warning.padded) {
3565 warningf(&compound->base.source_position, "'%T' needs padding", type);
3568 if (compound->modifiers & DM_PACKED && warning.packed) {
3569 warningf(&compound->base.source_position,
3570 "superfluous packed attribute on '%T'", type);
3574 type->base.size = offset;
3575 type->base.alignment = alignment;
3579 * Finish the construction of an union type by calculating
3580 * its size and alignment.
3582 static void finish_union_type(compound_type_t *type)
3584 assert(type->compound != NULL);
3586 compound_t *compound = type->compound;
3587 if (! compound->complete)
3591 il_alignment_t alignment = 1;
3593 entity_t *entry = compound->members.entities;
3594 for (; entry != NULL; entry = entry->base.next) {
3595 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3598 type_t *m_type = skip_typeref(entry->declaration.type);
3599 if (! is_type_valid(m_type))
3602 entry->compound_member.offset = 0;
3603 if (m_type->base.size > size)
3604 size = m_type->base.size;
3605 if (m_type->base.alignment > alignment)
3606 alignment = m_type->base.alignment;
3608 if (type->base.alignment != 0) {
3609 alignment = type->base.alignment;
3611 size = (size + alignment - 1) & -alignment;
3612 type->base.size = size;
3613 type->base.alignment = alignment;
3616 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3618 type_t *type = NULL;
3619 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3620 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3621 unsigned type_specifiers = 0;
3622 bool newtype = false;
3623 bool saw_error = false;
3624 bool old_gcc_extension = in_gcc_extension;
3626 specifiers->source_position = token.source_position;
3629 specifiers->modifiers
3630 |= parse_attributes(&specifiers->gnu_attributes);
3631 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3632 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3634 switch (token.type) {
3636 #define MATCH_STORAGE_CLASS(token, class) \
3638 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3639 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3641 specifiers->storage_class = class; \
3642 if (specifiers->thread_local) \
3643 goto check_thread_storage_class; \
3647 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3648 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3649 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3650 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3651 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3655 expect('(', end_error);
3656 add_anchor_token(')');
3657 parse_microsoft_extended_decl_modifier(specifiers);
3658 rem_anchor_token(')');
3659 expect(')', end_error);
3663 if (specifiers->thread_local) {
3664 errorf(HERE, "duplicate '__thread'");
3666 specifiers->thread_local = true;
3667 check_thread_storage_class:
3668 switch (specifiers->storage_class) {
3669 case STORAGE_CLASS_EXTERN:
3670 case STORAGE_CLASS_NONE:
3671 case STORAGE_CLASS_STATIC:
3675 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3676 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3677 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3678 wrong_thread_stoarge_class:
3679 errorf(HERE, "'__thread' used with '%s'", wrong);
3686 /* type qualifiers */
3687 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3689 qualifiers |= qualifier; \
3693 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3694 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3695 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3696 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3697 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3698 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3699 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3700 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3702 case T___extension__:
3704 in_gcc_extension = true;
3707 /* type specifiers */
3708 #define MATCH_SPECIFIER(token, specifier, name) \
3710 if (type_specifiers & specifier) { \
3711 errorf(HERE, "multiple " name " type specifiers given"); \
3713 type_specifiers |= specifier; \
3718 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3719 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3720 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3721 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3722 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3723 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3724 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3725 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3726 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3727 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3728 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3729 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3730 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3731 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3732 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3733 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3734 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3735 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3737 case T__forceinline:
3738 /* only in microsoft mode */
3739 specifiers->modifiers |= DM_FORCEINLINE;
3744 specifiers->is_inline = true;
3748 if (type_specifiers & SPECIFIER_LONG_LONG) {
3749 errorf(HERE, "multiple type specifiers given");
3750 } else if (type_specifiers & SPECIFIER_LONG) {
3751 type_specifiers |= SPECIFIER_LONG_LONG;
3753 type_specifiers |= SPECIFIER_LONG;
3759 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3761 type->compound.compound = parse_compound_type_specifier(true);
3762 finish_struct_type(&type->compound);
3766 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3767 type->compound.compound = parse_compound_type_specifier(false);
3768 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3769 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3770 finish_union_type(&type->compound);
3774 type = parse_enum_specifier();
3777 type = parse_typeof();
3779 case T___builtin_va_list:
3780 type = duplicate_type(type_valist);
3784 case T_IDENTIFIER: {
3785 /* only parse identifier if we haven't found a type yet */
3786 if (type != NULL || type_specifiers != 0) {
3787 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3788 * declaration, so it doesn't generate errors about expecting '(' or
3790 switch (look_ahead(1)->type) {
3797 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3801 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3806 goto finish_specifiers;
3810 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3811 if (typedef_type == NULL) {
3812 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3813 * declaration, so it doesn't generate 'implicit int' followed by more
3814 * errors later on. */
3815 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3821 errorf(HERE, "%K does not name a type", &token);
3824 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3826 type = allocate_type_zero(TYPE_TYPEDEF);
3827 type->typedeft.typedefe = &entity->typedefe;
3831 if (la1_type == '&' || la1_type == '*')
3832 goto finish_specifiers;
3837 goto finish_specifiers;
3842 type = typedef_type;
3846 /* function specifier */
3848 goto finish_specifiers;
3853 in_gcc_extension = old_gcc_extension;
3855 if (type == NULL || (saw_error && type_specifiers != 0)) {
3856 atomic_type_kind_t atomic_type;
3858 /* match valid basic types */
3859 switch (type_specifiers) {
3860 case SPECIFIER_VOID:
3861 atomic_type = ATOMIC_TYPE_VOID;
3863 case SPECIFIER_WCHAR_T:
3864 atomic_type = ATOMIC_TYPE_WCHAR_T;
3866 case SPECIFIER_CHAR:
3867 atomic_type = ATOMIC_TYPE_CHAR;
3869 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3870 atomic_type = ATOMIC_TYPE_SCHAR;
3872 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3873 atomic_type = ATOMIC_TYPE_UCHAR;
3875 case SPECIFIER_SHORT:
3876 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3877 case SPECIFIER_SHORT | SPECIFIER_INT:
3878 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3879 atomic_type = ATOMIC_TYPE_SHORT;
3881 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3882 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3883 atomic_type = ATOMIC_TYPE_USHORT;
3886 case SPECIFIER_SIGNED:
3887 case SPECIFIER_SIGNED | SPECIFIER_INT:
3888 atomic_type = ATOMIC_TYPE_INT;
3890 case SPECIFIER_UNSIGNED:
3891 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3892 atomic_type = ATOMIC_TYPE_UINT;
3894 case SPECIFIER_LONG:
3895 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3896 case SPECIFIER_LONG | SPECIFIER_INT:
3897 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3898 atomic_type = ATOMIC_TYPE_LONG;
3900 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3901 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3902 atomic_type = ATOMIC_TYPE_ULONG;
3905 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3906 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3907 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3908 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3910 atomic_type = ATOMIC_TYPE_LONGLONG;
3911 goto warn_about_long_long;
3913 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3914 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3916 atomic_type = ATOMIC_TYPE_ULONGLONG;
3917 warn_about_long_long:
3918 if (warning.long_long) {
3919 warningf(&specifiers->source_position,
3920 "ISO C90 does not support 'long long'");
3924 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3925 atomic_type = unsigned_int8_type_kind;
3928 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3929 atomic_type = unsigned_int16_type_kind;
3932 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3933 atomic_type = unsigned_int32_type_kind;
3936 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3937 atomic_type = unsigned_int64_type_kind;
3940 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3941 atomic_type = unsigned_int128_type_kind;
3944 case SPECIFIER_INT8:
3945 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3946 atomic_type = int8_type_kind;
3949 case SPECIFIER_INT16:
3950 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3951 atomic_type = int16_type_kind;
3954 case SPECIFIER_INT32:
3955 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3956 atomic_type = int32_type_kind;
3959 case SPECIFIER_INT64:
3960 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3961 atomic_type = int64_type_kind;
3964 case SPECIFIER_INT128:
3965 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3966 atomic_type = int128_type_kind;
3969 case SPECIFIER_FLOAT:
3970 atomic_type = ATOMIC_TYPE_FLOAT;
3972 case SPECIFIER_DOUBLE:
3973 atomic_type = ATOMIC_TYPE_DOUBLE;
3975 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3976 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3978 case SPECIFIER_BOOL:
3979 atomic_type = ATOMIC_TYPE_BOOL;
3981 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3982 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3983 atomic_type = ATOMIC_TYPE_FLOAT;
3985 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3986 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3987 atomic_type = ATOMIC_TYPE_DOUBLE;
3989 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3990 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3991 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3994 /* invalid specifier combination, give an error message */
3995 if (type_specifiers == 0) {
3999 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4000 if (!(c_mode & _CXX) && !strict_mode) {
4001 if (warning.implicit_int) {
4002 warningf(HERE, "no type specifiers in declaration, using 'int'");
4004 atomic_type = ATOMIC_TYPE_INT;
4007 errorf(HERE, "no type specifiers given in declaration");
4009 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4010 (type_specifiers & SPECIFIER_UNSIGNED)) {
4011 errorf(HERE, "signed and unsigned specifiers given");
4012 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4013 errorf(HERE, "only integer types can be signed or unsigned");
4015 errorf(HERE, "multiple datatypes in declaration");
4020 if (type_specifiers & SPECIFIER_COMPLEX) {
4021 type = allocate_type_zero(TYPE_COMPLEX);
4022 type->complex.akind = atomic_type;
4023 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4024 type = allocate_type_zero(TYPE_IMAGINARY);
4025 type->imaginary.akind = atomic_type;
4027 type = allocate_type_zero(TYPE_ATOMIC);
4028 type->atomic.akind = atomic_type;
4031 } else if (type_specifiers != 0) {
4032 errorf(HERE, "multiple datatypes in declaration");
4035 /* FIXME: check type qualifiers here */
4037 type->base.qualifiers = qualifiers;
4038 type->base.modifiers = modifiers;
4040 type_t *result = typehash_insert(type);
4041 if (newtype && result != type) {
4045 specifiers->type = result;
4049 specifiers->type = type_error_type;
4053 static type_qualifiers_t parse_type_qualifiers(void)
4055 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4058 switch (token.type) {
4059 /* type qualifiers */
4060 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4061 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4062 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4063 /* microsoft extended type modifiers */
4064 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4065 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4066 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4067 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4068 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4077 * Parses an K&R identifier list
4079 static void parse_identifier_list(scope_t *scope)
4082 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4083 entity->base.source_position = token.source_position;
4084 entity->base.namespc = NAMESPACE_NORMAL;
4085 entity->base.symbol = token.v.symbol;
4086 /* a K&R parameter has no type, yet */
4090 append_entity(scope, entity);
4092 if (token.type != ',') {
4096 } while (token.type == T_IDENTIFIER);
4099 static entity_t *parse_parameter(void)
4101 declaration_specifiers_t specifiers;
4102 memset(&specifiers, 0, sizeof(specifiers));
4104 parse_declaration_specifiers(&specifiers);
4106 entity_t *entity = parse_declarator(&specifiers,
4107 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4108 anonymous_entity = NULL;
4112 static void semantic_parameter_incomplete(const entity_t *entity)
4114 assert(entity->kind == ENTITY_PARAMETER);
4116 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4117 * list in a function declarator that is part of a
4118 * definition of that function shall not have
4119 * incomplete type. */
4120 type_t *type = skip_typeref(entity->declaration.type);
4121 if (is_type_incomplete(type)) {
4122 errorf(&entity->base.source_position,
4123 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4124 entity->declaration.type);
4129 * Parses function type parameters (and optionally creates variable_t entities
4130 * for them in a scope)
4132 static void parse_parameters(function_type_t *type, scope_t *scope)
4135 add_anchor_token(')');
4136 int saved_comma_state = save_and_reset_anchor_state(',');
4138 if (token.type == T_IDENTIFIER &&
4139 !is_typedef_symbol(token.v.symbol)) {
4140 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4141 if (la1_type == ',' || la1_type == ')') {
4142 type->kr_style_parameters = true;
4143 type->unspecified_parameters = true;
4144 parse_identifier_list(scope);
4145 goto parameters_finished;
4149 if (token.type == ')') {
4150 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4151 if (!(c_mode & _CXX))
4152 type->unspecified_parameters = true;
4153 goto parameters_finished;
4156 function_parameter_t *parameter;
4157 function_parameter_t *last_parameter = NULL;
4160 switch (token.type) {
4163 type->variadic = true;
4164 goto parameters_finished;
4167 case T___extension__:
4170 entity_t *entity = parse_parameter();
4171 if (entity->kind == ENTITY_TYPEDEF) {
4172 errorf(&entity->base.source_position,
4173 "typedef not allowed as function parameter");
4176 assert(is_declaration(entity));
4178 /* func(void) is not a parameter */
4179 if (last_parameter == NULL
4180 && token.type == ')'
4181 && entity->base.symbol == NULL
4182 && skip_typeref(entity->declaration.type) == type_void) {
4183 goto parameters_finished;
4185 semantic_parameter_incomplete(entity);
4187 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4188 memset(parameter, 0, sizeof(parameter[0]));
4189 parameter->type = entity->declaration.type;
4191 if (scope != NULL) {
4192 append_entity(scope, entity);
4195 if (last_parameter != NULL) {
4196 last_parameter->next = parameter;
4198 type->parameters = parameter;
4200 last_parameter = parameter;
4205 goto parameters_finished;
4207 if (token.type != ',') {
4208 goto parameters_finished;
4214 parameters_finished:
4215 rem_anchor_token(')');
4216 expect(')', end_error);
4219 restore_anchor_state(',', saved_comma_state);
4222 typedef enum construct_type_kind_t {
4225 CONSTRUCT_REFERENCE,
4228 } construct_type_kind_t;
4230 typedef struct construct_type_t construct_type_t;
4231 struct construct_type_t {
4232 construct_type_kind_t kind;
4233 construct_type_t *next;
4236 typedef struct parsed_pointer_t parsed_pointer_t;
4237 struct parsed_pointer_t {
4238 construct_type_t construct_type;
4239 type_qualifiers_t type_qualifiers;
4240 variable_t *base_variable; /**< MS __based extension. */
4243 typedef struct parsed_reference_t parsed_reference_t;
4244 struct parsed_reference_t {
4245 construct_type_t construct_type;
4248 typedef struct construct_function_type_t construct_function_type_t;
4249 struct construct_function_type_t {
4250 construct_type_t construct_type;
4251 type_t *function_type;
4254 typedef struct parsed_array_t parsed_array_t;
4255 struct parsed_array_t {
4256 construct_type_t construct_type;
4257 type_qualifiers_t type_qualifiers;
4263 typedef struct construct_base_type_t construct_base_type_t;
4264 struct construct_base_type_t {
4265 construct_type_t construct_type;
4269 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4273 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4274 memset(pointer, 0, sizeof(pointer[0]));
4275 pointer->construct_type.kind = CONSTRUCT_POINTER;
4276 pointer->type_qualifiers = parse_type_qualifiers();
4277 pointer->base_variable = base_variable;
4279 return &pointer->construct_type;
4282 static construct_type_t *parse_reference_declarator(void)
4286 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4287 memset(reference, 0, sizeof(reference[0]));
4288 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4290 return (construct_type_t*)reference;
4293 static construct_type_t *parse_array_declarator(void)
4296 add_anchor_token(']');
4298 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4299 memset(array, 0, sizeof(array[0]));
4300 array->construct_type.kind = CONSTRUCT_ARRAY;
4302 if (token.type == T_static) {
4303 array->is_static = true;
4307 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4308 if (type_qualifiers != 0) {
4309 if (token.type == T_static) {
4310 array->is_static = true;
4314 array->type_qualifiers = type_qualifiers;
4316 if (token.type == '*' && look_ahead(1)->type == ']') {
4317 array->is_variable = true;
4319 } else if (token.type != ']') {
4320 array->size = parse_assignment_expression();
4323 rem_anchor_token(']');
4324 expect(']', end_error);
4327 return &array->construct_type;
4330 static construct_type_t *parse_function_declarator(scope_t *scope,
4331 decl_modifiers_t modifiers)
4333 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4334 function_type_t *ftype = &type->function;
4336 ftype->linkage = current_linkage;
4338 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4339 case DM_NONE: break;
4340 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4341 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4342 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4343 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4346 errorf(HERE, "multiple calling conventions in declaration");
4350 parse_parameters(ftype, scope);
4352 construct_function_type_t *construct_function_type =
4353 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4354 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4355 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4356 construct_function_type->function_type = type;
4358 return &construct_function_type->construct_type;
4361 typedef struct parse_declarator_env_t {
4362 decl_modifiers_t modifiers;
4364 source_position_t source_position;
4366 } parse_declarator_env_t;
4368 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4369 bool may_be_abstract)
4371 /* construct a single linked list of construct_type_t's which describe
4372 * how to construct the final declarator type */
4373 construct_type_t *first = NULL;
4374 construct_type_t *last = NULL;
4375 gnu_attribute_t *attributes = NULL;
4377 decl_modifiers_t modifiers = parse_attributes(&attributes);
4379 /* MS __based extension */
4380 based_spec_t base_spec;
4381 base_spec.base_variable = NULL;
4384 construct_type_t *type;
4385 switch (token.type) {
4387 if (!(c_mode & _CXX))
4388 errorf(HERE, "references are only available for C++");
4389 if (base_spec.base_variable != NULL && warning.other) {
4390 warningf(&base_spec.source_position,
4391 "__based does not precede a pointer operator, ignored");
4393 type = parse_reference_declarator();
4395 base_spec.base_variable = NULL;
4399 type = parse_pointer_declarator(base_spec.base_variable);
4401 base_spec.base_variable = NULL;
4406 expect('(', end_error);
4407 add_anchor_token(')');
4408 parse_microsoft_based(&base_spec);
4409 rem_anchor_token(')');
4410 expect(')', end_error);
4414 goto ptr_operator_end;
4425 /* TODO: find out if this is correct */
4426 modifiers |= parse_attributes(&attributes);
4429 if (base_spec.base_variable != NULL && warning.other) {
4430 warningf(&base_spec.source_position,
4431 "__based does not precede a pointer operator, ignored");
4435 modifiers |= env->modifiers;
4436 env->modifiers = modifiers;
4439 construct_type_t *inner_types = NULL;
4441 switch (token.type) {
4444 errorf(HERE, "no identifier expected in typename");
4446 env->symbol = token.v.symbol;
4447 env->source_position = token.source_position;
4452 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4453 * interpreted as ``function with no parameter specification'', rather
4454 * than redundant parentheses around the omitted identifier. */
4455 if (look_ahead(1)->type != ')') {
4457 add_anchor_token(')');
4458 inner_types = parse_inner_declarator(env, may_be_abstract);
4459 if (inner_types != NULL) {
4460 /* All later declarators only modify the return type */
4463 rem_anchor_token(')');
4464 expect(')', end_error);
4468 if (may_be_abstract)
4470 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4475 construct_type_t *p = last;
4478 construct_type_t *type;
4479 switch (token.type) {
4481 scope_t *scope = NULL;
4483 scope = &env->parameters;
4485 type = parse_function_declarator(scope, modifiers);
4489 type = parse_array_declarator();
4492 goto declarator_finished;
4495 /* insert in the middle of the list (behind p) */
4497 type->next = p->next;
4508 declarator_finished:
4509 /* append inner_types at the end of the list, we don't to set last anymore
4510 * as it's not needed anymore */
4512 assert(first == NULL);
4513 first = inner_types;
4515 last->next = inner_types;
4523 static void parse_declaration_attributes(entity_t *entity)
4525 gnu_attribute_t *attributes = NULL;
4526 decl_modifiers_t modifiers = parse_attributes(&attributes);
4532 if (entity->kind == ENTITY_TYPEDEF) {
4533 modifiers |= entity->typedefe.modifiers;
4534 type = entity->typedefe.type;
4536 assert(is_declaration(entity));
4537 modifiers |= entity->declaration.modifiers;
4538 type = entity->declaration.type;
4543 /* handle these strange/stupid mode attributes */
4544 gnu_attribute_t *attribute = attributes;
4545 for ( ; attribute != NULL; attribute = attribute->next) {
4546 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4549 atomic_type_kind_t akind = attribute->u.akind;
4550 if (!is_type_signed(type)) {
4552 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4553 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4554 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4555 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4557 panic("invalid akind in mode attribute");
4561 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4562 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4563 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4564 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4566 panic("invalid akind in mode attribute");
4570 type = make_atomic_type(akind, type->base.qualifiers);
4573 type_modifiers_t type_modifiers = type->base.modifiers;
4574 if (modifiers & DM_TRANSPARENT_UNION)
4575 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4577 if (type->base.modifiers != type_modifiers) {
4578 type_t *copy = duplicate_type(type);
4579 copy->base.modifiers = type_modifiers;
4581 type = typehash_insert(copy);
4583 obstack_free(type_obst, copy);
4587 if (entity->kind == ENTITY_TYPEDEF) {
4588 entity->typedefe.type = type;
4589 entity->typedefe.modifiers = modifiers;
4591 entity->declaration.type = type;
4592 entity->declaration.modifiers = modifiers;
4596 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4598 construct_type_t *iter = construct_list;
4599 for (; iter != NULL; iter = iter->next) {
4600 switch (iter->kind) {
4601 case CONSTRUCT_INVALID:
4602 internal_errorf(HERE, "invalid type construction found");
4603 case CONSTRUCT_FUNCTION: {
4604 construct_function_type_t *construct_function_type
4605 = (construct_function_type_t*) iter;
4607 type_t *function_type = construct_function_type->function_type;
4609 function_type->function.return_type = type;
4611 type_t *skipped_return_type = skip_typeref(type);
4613 if (is_type_function(skipped_return_type)) {
4614 errorf(HERE, "function returning function is not allowed");
4615 } else if (is_type_array(skipped_return_type)) {
4616 errorf(HERE, "function returning array is not allowed");
4618 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4620 "type qualifiers in return type of function type are meaningless");
4624 type = function_type;
4628 case CONSTRUCT_POINTER: {
4629 if (is_type_reference(skip_typeref(type)))
4630 errorf(HERE, "cannot declare a pointer to reference");
4632 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4633 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4637 case CONSTRUCT_REFERENCE:
4638 if (is_type_reference(skip_typeref(type)))
4639 errorf(HERE, "cannot declare a reference to reference");
4641 type = make_reference_type(type);
4644 case CONSTRUCT_ARRAY: {
4645 if (is_type_reference(skip_typeref(type)))
4646 errorf(HERE, "cannot declare an array of references");
4648 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4649 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4651 expression_t *size_expression = parsed_array->size;
4652 if (size_expression != NULL) {
4654 = create_implicit_cast(size_expression, type_size_t);
4657 array_type->base.qualifiers = parsed_array->type_qualifiers;
4658 array_type->array.element_type = type;
4659 array_type->array.is_static = parsed_array->is_static;
4660 array_type->array.is_variable = parsed_array->is_variable;
4661 array_type->array.size_expression = size_expression;
4663 if (size_expression != NULL) {
4664 if (is_constant_expression(size_expression)) {
4665 array_type->array.size_constant = true;
4666 array_type->array.size
4667 = fold_constant(size_expression);
4669 array_type->array.is_vla = true;
4673 type_t *skipped_type = skip_typeref(type);
4675 if (is_type_incomplete(skipped_type)) {
4676 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4677 } else if (is_type_function(skipped_type)) {
4678 errorf(HERE, "array of functions is not allowed");
4685 type_t *hashed_type = typehash_insert(type);
4686 if (hashed_type != type) {
4687 /* the function type was constructed earlier freeing it here will
4688 * destroy other types... */
4689 if (iter->kind != CONSTRUCT_FUNCTION) {
4699 static type_t *automatic_type_conversion(type_t *orig_type);
4701 static type_t *semantic_parameter(const source_position_t *pos,
4703 const declaration_specifiers_t *specifiers,
4706 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4707 * shall be adjusted to ``qualified pointer to type'',
4709 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4710 * type'' shall be adjusted to ``pointer to function
4711 * returning type'', as in 6.3.2.1. */
4712 type = automatic_type_conversion(type);
4714 if (specifiers->is_inline && is_type_valid(type)) {
4715 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4718 /* §6.9.1:6 The declarations in the declaration list shall contain
4719 * no storage-class specifier other than register and no
4720 * initializations. */
4721 if (specifiers->thread_local || (
4722 specifiers->storage_class != STORAGE_CLASS_NONE &&
4723 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4725 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4728 /* delay test for incomplete type, because we might have (void)
4729 * which is legal but incomplete... */
4734 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4735 declarator_flags_t flags)
4737 parse_declarator_env_t env;
4738 memset(&env, 0, sizeof(env));
4739 env.modifiers = specifiers->modifiers;
4741 construct_type_t *construct_type =
4742 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4744 construct_declarator_type(construct_type, specifiers->type);
4745 type_t *type = skip_typeref(orig_type);
4747 if (construct_type != NULL) {
4748 obstack_free(&temp_obst, construct_type);
4752 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4753 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4754 entity->base.symbol = env.symbol;
4755 entity->base.source_position = env.source_position;
4756 entity->typedefe.type = orig_type;
4758 if (anonymous_entity != NULL) {
4759 if (is_type_compound(type)) {
4760 assert(anonymous_entity->compound.alias == NULL);
4761 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4762 anonymous_entity->kind == ENTITY_UNION);
4763 anonymous_entity->compound.alias = entity;
4764 anonymous_entity = NULL;
4765 } else if (is_type_enum(type)) {
4766 assert(anonymous_entity->enume.alias == NULL);
4767 assert(anonymous_entity->kind == ENTITY_ENUM);
4768 anonymous_entity->enume.alias = entity;
4769 anonymous_entity = NULL;
4773 /* create a declaration type entity */
4774 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4775 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4777 if (specifiers->is_inline && is_type_valid(type)) {
4778 errorf(&env.source_position,
4779 "compound member '%Y' declared 'inline'", env.symbol);
4782 if (specifiers->thread_local ||
4783 specifiers->storage_class != STORAGE_CLASS_NONE) {
4784 errorf(&env.source_position,
4785 "compound member '%Y' must have no storage class",
4788 } else if (flags & DECL_IS_PARAMETER) {
4789 orig_type = semantic_parameter(&env.source_position, orig_type,
4790 specifiers, env.symbol);
4792 entity = allocate_entity_zero(ENTITY_PARAMETER);
4793 } else if (is_type_function(type)) {
4794 entity = allocate_entity_zero(ENTITY_FUNCTION);
4796 entity->function.is_inline = specifiers->is_inline;
4797 entity->function.parameters = env.parameters;
4799 if (specifiers->thread_local || (
4800 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4801 specifiers->storage_class != STORAGE_CLASS_NONE &&
4802 specifiers->storage_class != STORAGE_CLASS_STATIC)
4804 errorf(&env.source_position,
4805 "invalid storage class for function '%Y'", env.symbol);
4808 entity = allocate_entity_zero(ENTITY_VARIABLE);
4810 entity->variable.get_property_sym = specifiers->get_property_sym;
4811 entity->variable.put_property_sym = specifiers->put_property_sym;
4812 if (specifiers->alignment != 0) {
4813 /* TODO: add checks here */
4814 entity->variable.alignment = specifiers->alignment;
4817 if (specifiers->is_inline && is_type_valid(type)) {
4818 errorf(&env.source_position,
4819 "variable '%Y' declared 'inline'", env.symbol);
4822 entity->variable.thread_local = specifiers->thread_local;
4824 bool invalid_storage_class = false;
4825 if (current_scope == file_scope) {
4826 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4827 specifiers->storage_class != STORAGE_CLASS_NONE &&
4828 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4829 invalid_storage_class = true;
4832 if (specifiers->thread_local &&
4833 specifiers->storage_class == STORAGE_CLASS_NONE) {
4834 invalid_storage_class = true;
4837 if (invalid_storage_class) {
4838 errorf(&env.source_position,
4839 "invalid storage class for variable '%Y'", env.symbol);
4843 entity->base.source_position = env.source_position;
4844 entity->base.symbol = env.symbol;
4845 entity->base.namespc = NAMESPACE_NORMAL;
4846 entity->declaration.type = orig_type;
4847 entity->declaration.modifiers = env.modifiers;
4848 entity->declaration.deprecated_string = specifiers->deprecated_string;
4850 storage_class_t storage_class = specifiers->storage_class;
4851 entity->declaration.declared_storage_class = storage_class;
4853 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4854 storage_class = STORAGE_CLASS_AUTO;
4855 entity->declaration.storage_class = storage_class;
4858 parse_declaration_attributes(entity);
4863 static type_t *parse_abstract_declarator(type_t *base_type)
4865 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4867 type_t *result = construct_declarator_type(construct_type, base_type);
4868 if (construct_type != NULL) {
4869 obstack_free(&temp_obst, construct_type);
4876 * Check if the declaration of main is suspicious. main should be a
4877 * function with external linkage, returning int, taking either zero
4878 * arguments, two, or three arguments of appropriate types, ie.
4880 * int main([ int argc, char **argv [, char **env ] ]).
4882 * @param decl the declaration to check
4883 * @param type the function type of the declaration
4885 static void check_type_of_main(const entity_t *entity)
4887 const source_position_t *pos = &entity->base.source_position;
4888 if (entity->kind != ENTITY_FUNCTION) {
4889 warningf(pos, "'main' is not a function");
4893 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4894 warningf(pos, "'main' is normally a non-static function");
4897 type_t *type = skip_typeref(entity->declaration.type);
4898 assert(is_type_function(type));
4900 function_type_t *func_type = &type->function;
4901 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4902 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4903 func_type->return_type);
4905 const function_parameter_t *parm = func_type->parameters;
4907 type_t *const first_type = parm->type;
4908 if (!types_compatible(skip_typeref(first_type), type_int)) {
4910 "first argument of 'main' should be 'int', but is '%T'",
4915 type_t *const second_type = parm->type;
4916 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4917 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4921 type_t *const third_type = parm->type;
4922 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4923 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4927 goto warn_arg_count;
4931 warningf(pos, "'main' takes only zero, two or three arguments");
4937 * Check if a symbol is the equal to "main".
4939 static bool is_sym_main(const symbol_t *const sym)
4941 return strcmp(sym->string, "main") == 0;
4944 static void error_redefined_as_different_kind(const source_position_t *pos,
4945 const entity_t *old, entity_kind_t new_kind)
4947 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4948 get_entity_kind_name(old->kind), old->base.symbol,
4949 get_entity_kind_name(new_kind), &old->base.source_position);
4953 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4954 * for various problems that occur for multiple definitions
4956 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4958 const symbol_t *const symbol = entity->base.symbol;
4959 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4960 const source_position_t *pos = &entity->base.source_position;
4962 /* can happen in error cases */
4966 entity_t *previous_entity = get_entity(symbol, namespc);
4967 /* pushing the same entity twice will break the stack structure */
4968 assert(previous_entity != entity);
4970 if (entity->kind == ENTITY_FUNCTION) {
4971 type_t *const orig_type = entity->declaration.type;
4972 type_t *const type = skip_typeref(orig_type);
4974 assert(is_type_function(type));
4975 if (type->function.unspecified_parameters &&
4976 warning.strict_prototypes &&
4977 previous_entity == NULL) {
4978 warningf(pos, "function declaration '%#T' is not a prototype",
4982 if (warning.main && current_scope == file_scope
4983 && is_sym_main(symbol)) {
4984 check_type_of_main(entity);
4988 if (is_declaration(entity) &&
4989 warning.nested_externs &&
4990 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4991 current_scope != file_scope) {
4992 warningf(pos, "nested extern declaration of '%#T'",
4993 entity->declaration.type, symbol);
4996 if (previous_entity != NULL &&
4997 previous_entity->base.parent_scope == ¤t_function->parameters &&
4998 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4999 assert(previous_entity->kind == ENTITY_PARAMETER);
5001 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5002 entity->declaration.type, symbol,
5003 previous_entity->declaration.type, symbol,
5004 &previous_entity->base.source_position);
5008 if (previous_entity != NULL &&
5009 previous_entity->base.parent_scope == current_scope) {
5010 if (previous_entity->kind != entity->kind) {
5011 error_redefined_as_different_kind(pos, previous_entity,
5015 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5016 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5017 symbol, &previous_entity->base.source_position);
5020 if (previous_entity->kind == ENTITY_TYPEDEF) {
5021 /* TODO: C++ allows this for exactly the same type */
5022 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5023 symbol, &previous_entity->base.source_position);
5027 /* at this point we should have only VARIABLES or FUNCTIONS */
5028 assert(is_declaration(previous_entity) && is_declaration(entity));
5030 declaration_t *const prev_decl = &previous_entity->declaration;
5031 declaration_t *const decl = &entity->declaration;
5033 /* can happen for K&R style declarations */
5034 if (prev_decl->type == NULL &&
5035 previous_entity->kind == ENTITY_PARAMETER &&
5036 entity->kind == ENTITY_PARAMETER) {
5037 prev_decl->type = decl->type;
5038 prev_decl->storage_class = decl->storage_class;
5039 prev_decl->declared_storage_class = decl->declared_storage_class;
5040 prev_decl->modifiers = decl->modifiers;
5041 prev_decl->deprecated_string = decl->deprecated_string;
5042 return previous_entity;
5045 type_t *const orig_type = decl->type;
5046 assert(orig_type != NULL);
5047 type_t *const type = skip_typeref(orig_type);
5048 type_t * prev_type = skip_typeref(prev_decl->type);
5050 if (!types_compatible(type, prev_type)) {
5052 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5053 orig_type, symbol, prev_decl->type, symbol,
5054 &previous_entity->base.source_position);
5056 unsigned old_storage_class = prev_decl->storage_class;
5057 if (warning.redundant_decls &&
5060 !(prev_decl->modifiers & DM_USED) &&
5061 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5062 warningf(&previous_entity->base.source_position,
5063 "unnecessary static forward declaration for '%#T'",
5064 prev_decl->type, symbol);
5067 unsigned new_storage_class = decl->storage_class;
5068 if (is_type_incomplete(prev_type)) {
5069 prev_decl->type = type;
5073 /* pretend no storage class means extern for function
5074 * declarations (except if the previous declaration is neither
5075 * none nor extern) */
5076 if (entity->kind == ENTITY_FUNCTION) {
5077 if (prev_type->function.unspecified_parameters) {
5078 prev_decl->type = type;
5082 switch (old_storage_class) {
5083 case STORAGE_CLASS_NONE:
5084 old_storage_class = STORAGE_CLASS_EXTERN;
5087 case STORAGE_CLASS_EXTERN:
5088 if (is_definition) {
5089 if (warning.missing_prototypes &&
5090 prev_type->function.unspecified_parameters &&
5091 !is_sym_main(symbol)) {
5092 warningf(pos, "no previous prototype for '%#T'",
5095 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5096 new_storage_class = STORAGE_CLASS_EXTERN;
5105 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5106 new_storage_class == STORAGE_CLASS_EXTERN) {
5107 warn_redundant_declaration:
5108 if (!is_definition &&
5109 warning.redundant_decls &&
5110 is_type_valid(prev_type) &&
5111 strcmp(previous_entity->base.source_position.input_name,
5112 "<builtin>") != 0) {
5114 "redundant declaration for '%Y' (declared %P)",
5115 symbol, &previous_entity->base.source_position);
5117 } else if (current_function == NULL) {
5118 if (old_storage_class != STORAGE_CLASS_STATIC &&
5119 new_storage_class == STORAGE_CLASS_STATIC) {
5121 "static declaration of '%Y' follows non-static declaration (declared %P)",
5122 symbol, &previous_entity->base.source_position);
5123 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5124 prev_decl->storage_class = STORAGE_CLASS_NONE;
5125 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5127 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5129 goto error_redeclaration;
5130 goto warn_redundant_declaration;
5132 } else if (is_type_valid(prev_type)) {
5133 if (old_storage_class == new_storage_class) {
5134 error_redeclaration:
5135 errorf(pos, "redeclaration of '%Y' (declared %P)",
5136 symbol, &previous_entity->base.source_position);
5139 "redeclaration of '%Y' with different linkage (declared %P)",
5140 symbol, &previous_entity->base.source_position);
5145 prev_decl->modifiers |= decl->modifiers;
5146 if (entity->kind == ENTITY_FUNCTION) {
5147 previous_entity->function.is_inline |= entity->function.is_inline;
5149 return previous_entity;
5152 if (entity->kind == ENTITY_FUNCTION) {
5153 if (is_definition &&
5154 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5155 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5156 warningf(pos, "no previous prototype for '%#T'",
5157 entity->declaration.type, symbol);
5158 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5159 warningf(pos, "no previous declaration for '%#T'",
5160 entity->declaration.type, symbol);
5163 } else if (warning.missing_declarations &&
5164 entity->kind == ENTITY_VARIABLE &&
5165 current_scope == file_scope) {
5166 declaration_t *declaration = &entity->declaration;
5167 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5168 warningf(pos, "no previous declaration for '%#T'",
5169 declaration->type, symbol);
5174 assert(entity->base.parent_scope == NULL);
5175 assert(current_scope != NULL);
5177 entity->base.parent_scope = current_scope;
5178 entity->base.namespc = NAMESPACE_NORMAL;
5179 environment_push(entity);
5180 append_entity(current_scope, entity);
5185 static void parser_error_multiple_definition(entity_t *entity,
5186 const source_position_t *source_position)
5188 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5189 entity->base.symbol, &entity->base.source_position);
5192 static bool is_declaration_specifier(const token_t *token,
5193 bool only_specifiers_qualifiers)
5195 switch (token->type) {
5200 return is_typedef_symbol(token->v.symbol);
5202 case T___extension__:
5204 return !only_specifiers_qualifiers;
5211 static void parse_init_declarator_rest(entity_t *entity)
5213 assert(is_declaration(entity));
5214 declaration_t *const declaration = &entity->declaration;
5218 type_t *orig_type = declaration->type;
5219 type_t *type = skip_typeref(orig_type);
5221 if (entity->kind == ENTITY_VARIABLE
5222 && entity->variable.initializer != NULL) {
5223 parser_error_multiple_definition(entity, HERE);
5226 bool must_be_constant = false;
5227 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5228 entity->base.parent_scope == file_scope) {
5229 must_be_constant = true;
5232 if (is_type_function(type)) {
5233 errorf(&entity->base.source_position,
5234 "function '%#T' is initialized like a variable",
5235 orig_type, entity->base.symbol);
5236 orig_type = type_error_type;
5239 parse_initializer_env_t env;
5240 env.type = orig_type;
5241 env.must_be_constant = must_be_constant;
5242 env.entity = entity;
5243 current_init_decl = entity;
5245 initializer_t *initializer = parse_initializer(&env);
5246 current_init_decl = NULL;
5248 if (entity->kind == ENTITY_VARIABLE) {
5249 /* § 6.7.5 (22) array initializers for arrays with unknown size
5250 * determine the array type size */
5251 declaration->type = env.type;
5252 entity->variable.initializer = initializer;
5256 /* parse rest of a declaration without any declarator */
5257 static void parse_anonymous_declaration_rest(
5258 const declaration_specifiers_t *specifiers)
5261 anonymous_entity = NULL;
5263 if (warning.other) {
5264 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5265 specifiers->thread_local) {
5266 warningf(&specifiers->source_position,
5267 "useless storage class in empty declaration");
5270 type_t *type = specifiers->type;
5271 switch (type->kind) {
5272 case TYPE_COMPOUND_STRUCT:
5273 case TYPE_COMPOUND_UNION: {
5274 if (type->compound.compound->base.symbol == NULL) {
5275 warningf(&specifiers->source_position,
5276 "unnamed struct/union that defines no instances");
5285 warningf(&specifiers->source_position, "empty declaration");
5291 static void check_variable_type_complete(entity_t *ent)
5293 if (ent->kind != ENTITY_VARIABLE)
5296 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5297 * type for the object shall be complete [...] */
5298 declaration_t *decl = &ent->declaration;
5299 if (decl->storage_class != STORAGE_CLASS_NONE)
5302 type_t *const orig_type = decl->type;
5303 type_t *const type = skip_typeref(orig_type);
5304 if (!is_type_incomplete(type))
5307 /* GCC allows global arrays without size and assigns them a length of one,
5308 * if no different declaration follows */
5309 if (is_type_array(type) &&
5311 ent->base.parent_scope == file_scope) {
5312 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5316 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5317 orig_type, ent->base.symbol);
5321 static void parse_declaration_rest(entity_t *ndeclaration,
5322 const declaration_specifiers_t *specifiers,
5323 parsed_declaration_func finished_declaration,
5324 declarator_flags_t flags)
5326 add_anchor_token(';');
5327 add_anchor_token(',');
5329 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5331 if (token.type == '=') {
5332 parse_init_declarator_rest(entity);
5333 } else if (entity->kind == ENTITY_VARIABLE) {
5334 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5335 * [...] where the extern specifier is explicitly used. */
5336 declaration_t *decl = &entity->declaration;
5337 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5338 type_t *type = decl->type;
5339 if (is_type_reference(skip_typeref(type))) {
5340 errorf(&entity->base.source_position,
5341 "reference '%#T' must be initialized",
5342 type, entity->base.symbol);
5347 check_variable_type_complete(entity);
5349 if (token.type != ',')
5353 add_anchor_token('=');
5354 ndeclaration = parse_declarator(specifiers, flags);
5355 rem_anchor_token('=');
5357 expect(';', end_error);
5360 anonymous_entity = NULL;
5361 rem_anchor_token(';');
5362 rem_anchor_token(',');
5365 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5367 symbol_t *symbol = entity->base.symbol;
5368 if (symbol == NULL) {
5369 errorf(HERE, "anonymous declaration not valid as function parameter");
5373 assert(entity->base.namespc == NAMESPACE_NORMAL);
5374 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5375 if (previous_entity == NULL
5376 || previous_entity->base.parent_scope != current_scope) {
5377 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5382 if (is_definition) {
5383 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5386 return record_entity(entity, false);
5389 static void parse_declaration(parsed_declaration_func finished_declaration,
5390 declarator_flags_t flags)
5392 declaration_specifiers_t specifiers;
5393 memset(&specifiers, 0, sizeof(specifiers));
5395 add_anchor_token(';');
5396 parse_declaration_specifiers(&specifiers);
5397 rem_anchor_token(';');
5399 if (token.type == ';') {
5400 parse_anonymous_declaration_rest(&specifiers);
5402 entity_t *entity = parse_declarator(&specifiers, flags);
5403 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5407 static type_t *get_default_promoted_type(type_t *orig_type)
5409 type_t *result = orig_type;
5411 type_t *type = skip_typeref(orig_type);
5412 if (is_type_integer(type)) {
5413 result = promote_integer(type);
5414 } else if (type == type_float) {
5415 result = type_double;
5421 static void parse_kr_declaration_list(entity_t *entity)
5423 if (entity->kind != ENTITY_FUNCTION)
5426 type_t *type = skip_typeref(entity->declaration.type);
5427 assert(is_type_function(type));
5428 if (!type->function.kr_style_parameters)
5432 add_anchor_token('{');
5434 /* push function parameters */
5435 size_t const top = environment_top();
5436 scope_t *old_scope = scope_push(&entity->function.parameters);
5438 entity_t *parameter = entity->function.parameters.entities;
5439 for ( ; parameter != NULL; parameter = parameter->base.next) {
5440 assert(parameter->base.parent_scope == NULL);
5441 parameter->base.parent_scope = current_scope;
5442 environment_push(parameter);
5445 /* parse declaration list */
5447 switch (token.type) {
5449 case T___extension__:
5450 /* This covers symbols, which are no type, too, and results in
5451 * better error messages. The typical cases are misspelled type
5452 * names and missing includes. */
5454 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5462 /* pop function parameters */
5463 assert(current_scope == &entity->function.parameters);
5464 scope_pop(old_scope);
5465 environment_pop_to(top);
5467 /* update function type */
5468 type_t *new_type = duplicate_type(type);
5470 function_parameter_t *parameters = NULL;
5471 function_parameter_t *last_parameter = NULL;
5473 parameter = entity->function.parameters.entities;
5474 for (; parameter != NULL; parameter = parameter->base.next) {
5475 type_t *parameter_type = parameter->declaration.type;
5476 if (parameter_type == NULL) {
5478 errorf(HERE, "no type specified for function parameter '%Y'",
5479 parameter->base.symbol);
5481 if (warning.implicit_int) {
5482 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5483 parameter->base.symbol);
5485 parameter_type = type_int;
5486 parameter->declaration.type = parameter_type;
5490 semantic_parameter_incomplete(parameter);
5491 parameter_type = parameter->declaration.type;
5494 * we need the default promoted types for the function type
5496 parameter_type = get_default_promoted_type(parameter_type);
5498 function_parameter_t *function_parameter
5499 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5500 memset(function_parameter, 0, sizeof(function_parameter[0]));
5502 function_parameter->type = parameter_type;
5503 if (last_parameter != NULL) {
5504 last_parameter->next = function_parameter;
5506 parameters = function_parameter;
5508 last_parameter = function_parameter;
5511 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5513 new_type->function.parameters = parameters;
5514 new_type->function.unspecified_parameters = true;
5516 type = typehash_insert(new_type);
5517 if (type != new_type) {
5518 obstack_free(type_obst, new_type);
5521 entity->declaration.type = type;
5523 rem_anchor_token('{');
5526 static bool first_err = true;
5529 * When called with first_err set, prints the name of the current function,
5532 static void print_in_function(void)
5536 diagnosticf("%s: In function '%Y':\n",
5537 current_function->base.base.source_position.input_name,
5538 current_function->base.base.symbol);
5543 * Check if all labels are defined in the current function.
5544 * Check if all labels are used in the current function.
5546 static void check_labels(void)
5548 for (const goto_statement_t *goto_statement = goto_first;
5549 goto_statement != NULL;
5550 goto_statement = goto_statement->next) {
5551 /* skip computed gotos */
5552 if (goto_statement->expression != NULL)
5555 label_t *label = goto_statement->label;
5558 if (label->base.source_position.input_name == NULL) {
5559 print_in_function();
5560 errorf(&goto_statement->base.source_position,
5561 "label '%Y' used but not defined", label->base.symbol);
5565 if (warning.unused_label) {
5566 for (const label_statement_t *label_statement = label_first;
5567 label_statement != NULL;
5568 label_statement = label_statement->next) {
5569 label_t *label = label_statement->label;
5571 if (! label->used) {
5572 print_in_function();
5573 warningf(&label_statement->base.source_position,
5574 "label '%Y' defined but not used", label->base.symbol);
5580 static void warn_unused_entity(entity_t *entity, entity_t *end)
5582 for (; entity != NULL; entity = entity->base.next) {
5583 if (!is_declaration(entity))
5586 declaration_t *declaration = &entity->declaration;
5587 if (declaration->implicit)
5590 if (!declaration->used) {
5591 print_in_function();
5592 const char *what = get_entity_kind_name(entity->kind);
5593 warningf(&entity->base.source_position, "%s '%Y' is unused",
5594 what, entity->base.symbol);
5595 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5596 print_in_function();
5597 const char *what = get_entity_kind_name(entity->kind);
5598 warningf(&entity->base.source_position, "%s '%Y' is never read",
5599 what, entity->base.symbol);
5607 static void check_unused_variables(statement_t *const stmt, void *const env)
5611 switch (stmt->kind) {
5612 case STATEMENT_DECLARATION: {
5613 declaration_statement_t const *const decls = &stmt->declaration;
5614 warn_unused_entity(decls->declarations_begin,
5615 decls->declarations_end);
5620 warn_unused_entity(stmt->fors.scope.entities, NULL);
5629 * Check declarations of current_function for unused entities.
5631 static void check_declarations(void)
5633 if (warning.unused_parameter) {
5634 const scope_t *scope = ¤t_function->parameters;
5636 /* do not issue unused warnings for main */
5637 if (!is_sym_main(current_function->base.base.symbol)) {
5638 warn_unused_entity(scope->entities, NULL);
5641 if (warning.unused_variable) {
5642 walk_statements(current_function->statement, check_unused_variables,
5647 static int determine_truth(expression_t const* const cond)
5650 !is_constant_expression(cond) ? 0 :
5651 fold_constant(cond) != 0 ? 1 :
5655 static void check_reachable(statement_t *);
5657 static bool expression_returns(expression_t const *const expr)
5659 switch (expr->kind) {
5661 expression_t const *const func = expr->call.function;
5662 if (func->kind == EXPR_REFERENCE) {
5663 entity_t *entity = func->reference.entity;
5664 if (entity->kind == ENTITY_FUNCTION
5665 && entity->declaration.modifiers & DM_NORETURN)
5669 if (!expression_returns(func))
5672 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5673 if (!expression_returns(arg->expression))
5680 case EXPR_REFERENCE:
5681 case EXPR_REFERENCE_ENUM_VALUE:
5683 case EXPR_CHARACTER_CONSTANT:
5684 case EXPR_WIDE_CHARACTER_CONSTANT:
5685 case EXPR_STRING_LITERAL:
5686 case EXPR_WIDE_STRING_LITERAL:
5687 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5688 case EXPR_LABEL_ADDRESS:
5689 case EXPR_CLASSIFY_TYPE:
5690 case EXPR_SIZEOF: // TODO handle obscure VLA case
5693 case EXPR_BUILTIN_SYMBOL:
5694 case EXPR_BUILTIN_CONSTANT_P:
5695 case EXPR_BUILTIN_PREFETCH:
5700 case EXPR_STATEMENT:
5701 check_reachable(expr->statement.statement);
5702 // TODO check if statement can be left
5705 case EXPR_CONDITIONAL:
5706 // TODO handle constant expression
5708 if (!expression_returns(expr->conditional.condition))
5711 if (expr->conditional.true_expression != NULL
5712 && expression_returns(expr->conditional.true_expression))
5715 return expression_returns(expr->conditional.false_expression);
5718 return expression_returns(expr->select.compound);
5720 case EXPR_ARRAY_ACCESS:
5722 expression_returns(expr->array_access.array_ref) &&
5723 expression_returns(expr->array_access.index);
5726 return expression_returns(expr->va_starte.ap);
5729 return expression_returns(expr->va_arge.ap);
5731 EXPR_UNARY_CASES_MANDATORY
5732 return expression_returns(expr->unary.value);
5734 case EXPR_UNARY_THROW:
5738 // TODO handle constant lhs of && and ||
5740 expression_returns(expr->binary.left) &&
5741 expression_returns(expr->binary.right);
5747 panic("unhandled expression");
5750 static bool initializer_returns(initializer_t const *const init)
5752 switch (init->kind) {
5753 case INITIALIZER_VALUE:
5754 return expression_returns(init->value.value);
5756 case INITIALIZER_LIST: {
5757 initializer_t * const* i = init->list.initializers;
5758 initializer_t * const* const end = i + init->list.len;
5759 bool returns = true;
5760 for (; i != end; ++i) {
5761 if (!initializer_returns(*i))
5767 case INITIALIZER_STRING:
5768 case INITIALIZER_WIDE_STRING:
5769 case INITIALIZER_DESIGNATOR: // designators have no payload
5772 panic("unhandled initializer");
5775 static bool noreturn_candidate;
5777 static void check_reachable(statement_t *const stmt)
5779 if (stmt->base.reachable)
5781 if (stmt->kind != STATEMENT_DO_WHILE)
5782 stmt->base.reachable = true;
5784 statement_t *last = stmt;
5786 switch (stmt->kind) {
5787 case STATEMENT_INVALID:
5788 case STATEMENT_EMPTY:
5789 case STATEMENT_LOCAL_LABEL:
5791 next = stmt->base.next;
5794 case STATEMENT_DECLARATION: {
5795 declaration_statement_t const *const decl = &stmt->declaration;
5796 entity_t const * ent = decl->declarations_begin;
5797 entity_t const *const last = decl->declarations_end;
5799 for (;; ent = ent->base.next) {
5800 if (ent->kind == ENTITY_VARIABLE &&
5801 ent->variable.initializer != NULL &&
5802 !initializer_returns(ent->variable.initializer)) {
5809 next = stmt->base.next;
5813 case STATEMENT_COMPOUND:
5814 next = stmt->compound.statements;
5817 case STATEMENT_RETURN: {
5818 expression_t const *const val = stmt->returns.value;
5819 if (val == NULL || expression_returns(val))
5820 noreturn_candidate = false;
5824 case STATEMENT_IF: {
5825 if_statement_t const *const ifs = &stmt->ifs;
5826 expression_t const *const cond = ifs->condition;
5828 if (!expression_returns(cond))
5831 int const val = determine_truth(cond);
5834 check_reachable(ifs->true_statement);
5839 if (ifs->false_statement != NULL) {
5840 check_reachable(ifs->false_statement);
5844 next = stmt->base.next;
5848 case STATEMENT_SWITCH: {
5849 switch_statement_t const *const switchs = &stmt->switchs;
5850 expression_t const *const expr = switchs->expression;
5852 if (!expression_returns(expr))
5855 if (is_constant_expression(expr)) {
5856 long const val = fold_constant(expr);
5857 case_label_statement_t * defaults = NULL;
5858 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5859 if (i->expression == NULL) {
5864 if (i->first_case <= val && val <= i->last_case) {
5865 check_reachable((statement_t*)i);
5870 if (defaults != NULL) {
5871 check_reachable((statement_t*)defaults);
5875 bool has_default = false;
5876 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5877 if (i->expression == NULL)
5880 check_reachable((statement_t*)i);
5887 next = stmt->base.next;
5891 case STATEMENT_EXPRESSION: {
5892 /* Check for noreturn function call */
5893 expression_t const *const expr = stmt->expression.expression;
5894 if (!expression_returns(expr))
5897 next = stmt->base.next;
5901 case STATEMENT_CONTINUE: {
5902 statement_t *parent = stmt;
5904 parent = parent->base.parent;
5905 if (parent == NULL) /* continue not within loop */
5909 switch (parent->kind) {
5910 case STATEMENT_WHILE: goto continue_while;
5911 case STATEMENT_DO_WHILE: goto continue_do_while;
5912 case STATEMENT_FOR: goto continue_for;
5919 case STATEMENT_BREAK: {
5920 statement_t *parent = stmt;
5922 parent = parent->base.parent;
5923 if (parent == NULL) /* break not within loop/switch */
5926 switch (parent->kind) {
5927 case STATEMENT_SWITCH:
5928 case STATEMENT_WHILE:
5929 case STATEMENT_DO_WHILE:
5932 next = parent->base.next;
5933 goto found_break_parent;
5942 case STATEMENT_GOTO:
5943 if (stmt->gotos.expression) {
5944 if (!expression_returns(stmt->gotos.expression))
5947 statement_t *parent = stmt->base.parent;
5948 if (parent == NULL) /* top level goto */
5952 next = stmt->gotos.label->statement;
5953 if (next == NULL) /* missing label */
5958 case STATEMENT_LABEL:
5959 next = stmt->label.statement;
5962 case STATEMENT_CASE_LABEL:
5963 next = stmt->case_label.statement;
5966 case STATEMENT_WHILE: {
5967 while_statement_t const *const whiles = &stmt->whiles;
5968 expression_t const *const cond = whiles->condition;
5970 if (!expression_returns(cond))
5973 int const val = determine_truth(cond);
5976 check_reachable(whiles->body);
5981 next = stmt->base.next;
5985 case STATEMENT_DO_WHILE:
5986 next = stmt->do_while.body;
5989 case STATEMENT_FOR: {
5990 for_statement_t *const fors = &stmt->fors;
5992 if (fors->condition_reachable)
5994 fors->condition_reachable = true;
5996 expression_t const *const cond = fors->condition;
6001 } else if (expression_returns(cond)) {
6002 val = determine_truth(cond);
6008 check_reachable(fors->body);
6013 next = stmt->base.next;
6017 case STATEMENT_MS_TRY: {
6018 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6019 check_reachable(ms_try->try_statement);
6020 next = ms_try->final_statement;
6024 case STATEMENT_LEAVE: {
6025 statement_t *parent = stmt;
6027 parent = parent->base.parent;
6028 if (parent == NULL) /* __leave not within __try */
6031 if (parent->kind == STATEMENT_MS_TRY) {
6033 next = parent->ms_try.final_statement;
6041 panic("invalid statement kind");
6044 while (next == NULL) {
6045 next = last->base.parent;
6047 noreturn_candidate = false;
6049 type_t *const type = current_function->base.type;
6050 assert(is_type_function(type));
6051 type_t *const ret = skip_typeref(type->function.return_type);
6052 if (warning.return_type &&
6053 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6054 is_type_valid(ret) &&
6055 !is_sym_main(current_function->base.base.symbol)) {
6056 warningf(&stmt->base.source_position,
6057 "control reaches end of non-void function");
6062 switch (next->kind) {
6063 case STATEMENT_INVALID:
6064 case STATEMENT_EMPTY:
6065 case STATEMENT_DECLARATION:
6066 case STATEMENT_LOCAL_LABEL:
6067 case STATEMENT_EXPRESSION:
6069 case STATEMENT_RETURN:
6070 case STATEMENT_CONTINUE:
6071 case STATEMENT_BREAK:
6072 case STATEMENT_GOTO:
6073 case STATEMENT_LEAVE:
6074 panic("invalid control flow in function");
6076 case STATEMENT_COMPOUND:
6078 case STATEMENT_SWITCH:
6079 case STATEMENT_LABEL:
6080 case STATEMENT_CASE_LABEL:
6082 next = next->base.next;
6085 case STATEMENT_WHILE: {
6087 if (next->base.reachable)
6089 next->base.reachable = true;
6091 while_statement_t const *const whiles = &next->whiles;
6092 expression_t const *const cond = whiles->condition;
6094 if (!expression_returns(cond))
6097 int const val = determine_truth(cond);
6100 check_reachable(whiles->body);
6106 next = next->base.next;
6110 case STATEMENT_DO_WHILE: {
6112 if (next->base.reachable)
6114 next->base.reachable = true;
6116 do_while_statement_t const *const dw = &next->do_while;
6117 expression_t const *const cond = dw->condition;
6119 if (!expression_returns(cond))
6122 int const val = determine_truth(cond);
6125 check_reachable(dw->body);
6131 next = next->base.next;
6135 case STATEMENT_FOR: {
6137 for_statement_t *const fors = &next->fors;
6139 fors->step_reachable = true;
6141 if (fors->condition_reachable)
6143 fors->condition_reachable = true;
6145 expression_t const *const cond = fors->condition;
6150 } else if (expression_returns(cond)) {
6151 val = determine_truth(cond);
6157 check_reachable(fors->body);
6163 next = next->base.next;
6167 case STATEMENT_MS_TRY:
6169 next = next->ms_try.final_statement;
6174 check_reachable(next);
6177 static void check_unreachable(statement_t* const stmt, void *const env)
6181 switch (stmt->kind) {
6182 case STATEMENT_DO_WHILE:
6183 if (!stmt->base.reachable) {
6184 expression_t const *const cond = stmt->do_while.condition;
6185 if (determine_truth(cond) >= 0) {
6186 warningf(&cond->base.source_position,
6187 "condition of do-while-loop is unreachable");
6192 case STATEMENT_FOR: {
6193 for_statement_t const* const fors = &stmt->fors;
6195 // if init and step are unreachable, cond is unreachable, too
6196 if (!stmt->base.reachable && !fors->step_reachable) {
6197 warningf(&stmt->base.source_position, "statement is unreachable");
6199 if (!stmt->base.reachable && fors->initialisation != NULL) {
6200 warningf(&fors->initialisation->base.source_position,
6201 "initialisation of for-statement is unreachable");
6204 if (!fors->condition_reachable && fors->condition != NULL) {
6205 warningf(&fors->condition->base.source_position,
6206 "condition of for-statement is unreachable");
6209 if (!fors->step_reachable && fors->step != NULL) {
6210 warningf(&fors->step->base.source_position,
6211 "step of for-statement is unreachable");
6217 case STATEMENT_COMPOUND:
6218 if (stmt->compound.statements != NULL)
6220 goto warn_unreachable;
6222 case STATEMENT_DECLARATION: {
6223 /* Only warn if there is at least one declarator with an initializer.
6224 * This typically occurs in switch statements. */
6225 declaration_statement_t const *const decl = &stmt->declaration;
6226 entity_t const * ent = decl->declarations_begin;
6227 entity_t const *const last = decl->declarations_end;
6229 for (;; ent = ent->base.next) {
6230 if (ent->kind == ENTITY_VARIABLE &&
6231 ent->variable.initializer != NULL) {
6232 goto warn_unreachable;
6242 if (!stmt->base.reachable)
6243 warningf(&stmt->base.source_position, "statement is unreachable");
6248 static void parse_external_declaration(void)
6250 /* function-definitions and declarations both start with declaration
6252 declaration_specifiers_t specifiers;
6253 memset(&specifiers, 0, sizeof(specifiers));
6255 add_anchor_token(';');
6256 parse_declaration_specifiers(&specifiers);
6257 rem_anchor_token(';');
6259 /* must be a declaration */
6260 if (token.type == ';') {
6261 parse_anonymous_declaration_rest(&specifiers);
6265 add_anchor_token(',');
6266 add_anchor_token('=');
6267 add_anchor_token(';');
6268 add_anchor_token('{');
6270 /* declarator is common to both function-definitions and declarations */
6271 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6273 rem_anchor_token('{');
6274 rem_anchor_token(';');
6275 rem_anchor_token('=');
6276 rem_anchor_token(',');
6278 /* must be a declaration */
6279 switch (token.type) {
6283 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6288 /* must be a function definition */
6289 parse_kr_declaration_list(ndeclaration);
6291 if (token.type != '{') {
6292 parse_error_expected("while parsing function definition", '{', NULL);
6293 eat_until_matching_token(';');
6297 assert(is_declaration(ndeclaration));
6298 type_t *type = skip_typeref(ndeclaration->declaration.type);
6300 if (!is_type_function(type)) {
6301 if (is_type_valid(type)) {
6302 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6303 type, ndeclaration->base.symbol);
6309 if (warning.aggregate_return &&
6310 is_type_compound(skip_typeref(type->function.return_type))) {
6311 warningf(HERE, "function '%Y' returns an aggregate",
6312 ndeclaration->base.symbol);
6314 if (warning.traditional && !type->function.unspecified_parameters) {
6315 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6316 ndeclaration->base.symbol);
6318 if (warning.old_style_definition && type->function.unspecified_parameters) {
6319 warningf(HERE, "old-style function definition '%Y'",
6320 ndeclaration->base.symbol);
6323 /* § 6.7.5.3 (14) a function definition with () means no
6324 * parameters (and not unspecified parameters) */
6325 if (type->function.unspecified_parameters
6326 && type->function.parameters == NULL
6327 && !type->function.kr_style_parameters) {
6328 type_t *duplicate = duplicate_type(type);
6329 duplicate->function.unspecified_parameters = false;
6331 type = typehash_insert(duplicate);
6332 if (type != duplicate) {
6333 obstack_free(type_obst, duplicate);
6335 ndeclaration->declaration.type = type;
6338 entity_t *const entity = record_entity(ndeclaration, true);
6339 assert(entity->kind == ENTITY_FUNCTION);
6340 assert(ndeclaration->kind == ENTITY_FUNCTION);
6342 function_t *function = &entity->function;
6343 if (ndeclaration != entity) {
6344 function->parameters = ndeclaration->function.parameters;
6346 assert(is_declaration(entity));
6347 type = skip_typeref(entity->declaration.type);
6349 /* push function parameters and switch scope */
6350 size_t const top = environment_top();
6351 scope_t *old_scope = scope_push(&function->parameters);
6353 entity_t *parameter = function->parameters.entities;
6354 for (; parameter != NULL; parameter = parameter->base.next) {
6355 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6356 parameter->base.parent_scope = current_scope;
6358 assert(parameter->base.parent_scope == NULL
6359 || parameter->base.parent_scope == current_scope);
6360 parameter->base.parent_scope = current_scope;
6361 if (parameter->base.symbol == NULL) {
6362 errorf(¶meter->base.source_position, "parameter name omitted");
6365 environment_push(parameter);
6368 if (function->statement != NULL) {
6369 parser_error_multiple_definition(entity, HERE);
6372 /* parse function body */
6373 int label_stack_top = label_top();
6374 function_t *old_current_function = current_function;
6375 current_function = function;
6376 current_parent = NULL;
6379 goto_anchor = &goto_first;
6381 label_anchor = &label_first;
6383 statement_t *const body = parse_compound_statement(false);
6384 function->statement = body;
6387 check_declarations();
6388 if (warning.return_type ||
6389 warning.unreachable_code ||
6390 (warning.missing_noreturn
6391 && !(function->base.modifiers & DM_NORETURN))) {
6392 noreturn_candidate = true;
6393 check_reachable(body);
6394 if (warning.unreachable_code)
6395 walk_statements(body, check_unreachable, NULL);
6396 if (warning.missing_noreturn &&
6397 noreturn_candidate &&
6398 !(function->base.modifiers & DM_NORETURN)) {
6399 warningf(&body->base.source_position,
6400 "function '%#T' is candidate for attribute 'noreturn'",
6401 type, entity->base.symbol);
6405 assert(current_parent == NULL);
6406 assert(current_function == function);
6407 current_function = old_current_function;
6408 label_pop_to(label_stack_top);
6411 assert(current_scope == &function->parameters);
6412 scope_pop(old_scope);
6413 environment_pop_to(top);
6416 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6417 source_position_t *source_position,
6418 const symbol_t *symbol)
6420 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6422 type->bitfield.base_type = base_type;
6423 type->bitfield.size_expression = size;
6426 type_t *skipped_type = skip_typeref(base_type);
6427 if (!is_type_integer(skipped_type)) {
6428 errorf(HERE, "bitfield base type '%T' is not an integer type",
6432 bit_size = skipped_type->base.size * 8;
6435 if (is_constant_expression(size)) {
6436 long v = fold_constant(size);
6439 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6440 } else if (v == 0) {
6441 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6442 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6443 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6445 type->bitfield.bit_size = v;
6452 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6454 entity_t *iter = compound->members.entities;
6455 for (; iter != NULL; iter = iter->base.next) {
6456 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6459 if (iter->base.symbol == symbol) {
6461 } else if (iter->base.symbol == NULL) {
6462 type_t *type = skip_typeref(iter->declaration.type);
6463 if (is_type_compound(type)) {
6465 = find_compound_entry(type->compound.compound, symbol);
6476 static void parse_compound_declarators(compound_t *compound,
6477 const declaration_specifiers_t *specifiers)
6482 if (token.type == ':') {
6483 source_position_t source_position = *HERE;
6486 type_t *base_type = specifiers->type;
6487 expression_t *size = parse_constant_expression();
6489 type_t *type = make_bitfield_type(base_type, size,
6490 &source_position, sym_anonymous);
6492 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6493 entity->base.namespc = NAMESPACE_NORMAL;
6494 entity->base.source_position = source_position;
6495 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6496 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6497 entity->declaration.modifiers = specifiers->modifiers;
6498 entity->declaration.type = type;
6500 entity = parse_declarator(specifiers,
6501 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6502 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6504 if (token.type == ':') {
6505 source_position_t source_position = *HERE;
6507 expression_t *size = parse_constant_expression();
6509 type_t *type = entity->declaration.type;
6510 type_t *bitfield_type = make_bitfield_type(type, size,
6511 &source_position, entity->base.symbol);
6512 entity->declaration.type = bitfield_type;
6516 /* make sure we don't define a symbol multiple times */
6517 symbol_t *symbol = entity->base.symbol;
6518 if (symbol != NULL) {
6519 entity_t *prev = find_compound_entry(compound, symbol);
6522 errorf(&entity->base.source_position,
6523 "multiple declarations of symbol '%Y' (declared %P)",
6524 symbol, &prev->base.source_position);
6528 append_entity(&compound->members, entity);
6530 type_t *orig_type = entity->declaration.type;
6531 type_t *type = skip_typeref(orig_type);
6532 if (is_type_function(type)) {
6533 errorf(&entity->base.source_position,
6534 "compound member '%Y' must not have function type '%T'",
6535 entity->base.symbol, orig_type);
6536 } else if (is_type_incomplete(type)) {
6537 /* §6.7.2.1:16 flexible array member */
6538 if (is_type_array(type) &&
6539 token.type == ';' &&
6540 look_ahead(1)->type == '}') {
6541 compound->has_flexible_member = true;
6543 errorf(&entity->base.source_position,
6544 "compound member '%Y' has incomplete type '%T'",
6545 entity->base.symbol, orig_type);
6549 if (token.type != ',')
6553 expect(';', end_error);
6556 anonymous_entity = NULL;
6559 static void parse_compound_type_entries(compound_t *compound)
6562 add_anchor_token('}');
6564 while (token.type != '}') {
6565 if (token.type == T_EOF) {
6566 errorf(HERE, "EOF while parsing struct");
6569 declaration_specifiers_t specifiers;
6570 memset(&specifiers, 0, sizeof(specifiers));
6571 parse_declaration_specifiers(&specifiers);
6573 parse_compound_declarators(compound, &specifiers);
6575 rem_anchor_token('}');
6579 compound->complete = true;
6582 static type_t *parse_typename(void)
6584 declaration_specifiers_t specifiers;
6585 memset(&specifiers, 0, sizeof(specifiers));
6586 parse_declaration_specifiers(&specifiers);
6587 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6588 specifiers.thread_local) {
6589 /* TODO: improve error message, user does probably not know what a
6590 * storage class is...
6592 errorf(HERE, "typename may not have a storage class");
6595 type_t *result = parse_abstract_declarator(specifiers.type);
6603 typedef expression_t* (*parse_expression_function)(void);
6604 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6606 typedef struct expression_parser_function_t expression_parser_function_t;
6607 struct expression_parser_function_t {
6608 parse_expression_function parser;
6609 unsigned infix_precedence;
6610 parse_expression_infix_function infix_parser;
6613 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6616 * Prints an error message if an expression was expected but not read
6618 static expression_t *expected_expression_error(void)
6620 /* skip the error message if the error token was read */
6621 if (token.type != T_ERROR) {
6622 errorf(HERE, "expected expression, got token %K", &token);
6626 return create_invalid_expression();
6630 * Parse a string constant.
6632 static expression_t *parse_string_const(void)
6635 if (token.type == T_STRING_LITERAL) {
6636 string_t res = token.v.string;
6638 while (token.type == T_STRING_LITERAL) {
6639 res = concat_strings(&res, &token.v.string);
6642 if (token.type != T_WIDE_STRING_LITERAL) {
6643 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6644 /* note: that we use type_char_ptr here, which is already the
6645 * automatic converted type. revert_automatic_type_conversion
6646 * will construct the array type */
6647 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6648 cnst->string.value = res;
6652 wres = concat_string_wide_string(&res, &token.v.wide_string);
6654 wres = token.v.wide_string;
6659 switch (token.type) {
6660 case T_WIDE_STRING_LITERAL:
6661 wres = concat_wide_strings(&wres, &token.v.wide_string);
6664 case T_STRING_LITERAL:
6665 wres = concat_wide_string_string(&wres, &token.v.string);
6669 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6670 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6671 cnst->wide_string.value = wres;
6680 * Parse a boolean constant.
6682 static expression_t *parse_bool_const(bool value)
6684 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6685 cnst->base.type = type_bool;
6686 cnst->conste.v.int_value = value;
6694 * Parse an integer constant.
6696 static expression_t *parse_int_const(void)
6698 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6699 cnst->base.type = token.datatype;
6700 cnst->conste.v.int_value = token.v.intvalue;
6708 * Parse a character constant.
6710 static expression_t *parse_character_constant(void)
6712 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6713 cnst->base.type = token.datatype;
6714 cnst->conste.v.character = token.v.string;
6716 if (cnst->conste.v.character.size != 1) {
6718 errorf(HERE, "more than 1 character in character constant");
6719 } else if (warning.multichar) {
6720 warningf(HERE, "multi-character character constant");
6729 * Parse a wide character constant.
6731 static expression_t *parse_wide_character_constant(void)
6733 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6734 cnst->base.type = token.datatype;
6735 cnst->conste.v.wide_character = token.v.wide_string;
6737 if (cnst->conste.v.wide_character.size != 1) {
6739 errorf(HERE, "more than 1 character in character constant");
6740 } else if (warning.multichar) {
6741 warningf(HERE, "multi-character character constant");
6750 * Parse a float constant.
6752 static expression_t *parse_float_const(void)
6754 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6755 cnst->base.type = token.datatype;
6756 cnst->conste.v.float_value = token.v.floatvalue;
6763 static entity_t *create_implicit_function(symbol_t *symbol,
6764 const source_position_t *source_position)
6766 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6767 ntype->function.return_type = type_int;
6768 ntype->function.unspecified_parameters = true;
6769 ntype->function.linkage = LINKAGE_C;
6771 type_t *type = typehash_insert(ntype);
6772 if (type != ntype) {
6776 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6777 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6778 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6779 entity->declaration.type = type;
6780 entity->declaration.implicit = true;
6781 entity->base.symbol = symbol;
6782 entity->base.source_position = *source_position;
6784 bool strict_prototypes_old = warning.strict_prototypes;
6785 warning.strict_prototypes = false;
6786 record_entity(entity, false);
6787 warning.strict_prototypes = strict_prototypes_old;
6793 * Creates a return_type (func)(argument_type) function type if not
6796 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6797 type_t *argument_type2)
6799 function_parameter_t *parameter2
6800 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6801 memset(parameter2, 0, sizeof(parameter2[0]));
6802 parameter2->type = argument_type2;
6804 function_parameter_t *parameter1
6805 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6806 memset(parameter1, 0, sizeof(parameter1[0]));
6807 parameter1->type = argument_type1;
6808 parameter1->next = parameter2;
6810 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6811 type->function.return_type = return_type;
6812 type->function.parameters = parameter1;
6814 type_t *result = typehash_insert(type);
6815 if (result != type) {
6823 * Creates a return_type (func)(argument_type) function type if not
6826 * @param return_type the return type
6827 * @param argument_type the argument type
6829 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6831 function_parameter_t *parameter
6832 = obstack_alloc(type_obst, sizeof(parameter[0]));
6833 memset(parameter, 0, sizeof(parameter[0]));
6834 parameter->type = argument_type;
6836 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6837 type->function.return_type = return_type;
6838 type->function.parameters = parameter;
6840 type_t *result = typehash_insert(type);
6841 if (result != type) {
6848 static type_t *make_function_0_type(type_t *return_type)
6850 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6851 type->function.return_type = return_type;
6852 type->function.parameters = NULL;
6854 type_t *result = typehash_insert(type);
6855 if (result != type) {
6863 * Creates a function type for some function like builtins.
6865 * @param symbol the symbol describing the builtin
6867 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6869 switch (symbol->ID) {
6870 case T___builtin_alloca:
6871 return make_function_1_type(type_void_ptr, type_size_t);
6872 case T___builtin_huge_val:
6873 return make_function_0_type(type_double);
6874 case T___builtin_inf:
6875 return make_function_0_type(type_double);
6876 case T___builtin_inff:
6877 return make_function_0_type(type_float);
6878 case T___builtin_infl:
6879 return make_function_0_type(type_long_double);
6880 case T___builtin_nan:
6881 return make_function_1_type(type_double, type_char_ptr);
6882 case T___builtin_nanf:
6883 return make_function_1_type(type_float, type_char_ptr);
6884 case T___builtin_nanl:
6885 return make_function_1_type(type_long_double, type_char_ptr);
6886 case T___builtin_va_end:
6887 return make_function_1_type(type_void, type_valist);
6888 case T___builtin_expect:
6889 return make_function_2_type(type_long, type_long, type_long);
6891 internal_errorf(HERE, "not implemented builtin identifier found");
6896 * Performs automatic type cast as described in § 6.3.2.1.
6898 * @param orig_type the original type
6900 static type_t *automatic_type_conversion(type_t *orig_type)
6902 type_t *type = skip_typeref(orig_type);
6903 if (is_type_array(type)) {
6904 array_type_t *array_type = &type->array;
6905 type_t *element_type = array_type->element_type;
6906 unsigned qualifiers = array_type->base.qualifiers;
6908 return make_pointer_type(element_type, qualifiers);
6911 if (is_type_function(type)) {
6912 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6919 * reverts the automatic casts of array to pointer types and function
6920 * to function-pointer types as defined § 6.3.2.1
6922 type_t *revert_automatic_type_conversion(const expression_t *expression)
6924 switch (expression->kind) {
6925 case EXPR_REFERENCE: {
6926 entity_t *entity = expression->reference.entity;
6927 if (is_declaration(entity)) {
6928 return entity->declaration.type;
6929 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6930 return entity->enum_value.enum_type;
6932 panic("no declaration or enum in reference");
6937 entity_t *entity = expression->select.compound_entry;
6938 assert(is_declaration(entity));
6939 type_t *type = entity->declaration.type;
6940 return get_qualified_type(type,
6941 expression->base.type->base.qualifiers);
6944 case EXPR_UNARY_DEREFERENCE: {
6945 const expression_t *const value = expression->unary.value;
6946 type_t *const type = skip_typeref(value->base.type);
6947 assert(is_type_pointer(type));
6948 return type->pointer.points_to;
6951 case EXPR_BUILTIN_SYMBOL:
6952 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6954 case EXPR_ARRAY_ACCESS: {
6955 const expression_t *array_ref = expression->array_access.array_ref;
6956 type_t *type_left = skip_typeref(array_ref->base.type);
6957 if (!is_type_valid(type_left))
6959 assert(is_type_pointer(type_left));
6960 return type_left->pointer.points_to;
6963 case EXPR_STRING_LITERAL: {
6964 size_t size = expression->string.value.size;
6965 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6968 case EXPR_WIDE_STRING_LITERAL: {
6969 size_t size = expression->wide_string.value.size;
6970 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6973 case EXPR_COMPOUND_LITERAL:
6974 return expression->compound_literal.type;
6979 return expression->base.type;
6982 static expression_t *parse_reference(void)
6984 symbol_t *const symbol = token.v.symbol;
6986 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6988 if (entity == NULL) {
6989 if (!strict_mode && look_ahead(1)->type == '(') {
6990 /* an implicitly declared function */
6991 if (warning.error_implicit_function_declaration) {
6992 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6993 } else if (warning.implicit_function_declaration) {
6994 warningf(HERE, "implicit declaration of function '%Y'", symbol);
6997 entity = create_implicit_function(symbol, HERE);
6999 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7000 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7006 if (is_declaration(entity)) {
7007 orig_type = entity->declaration.type;
7008 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7009 orig_type = entity->enum_value.enum_type;
7010 } else if (entity->kind == ENTITY_TYPEDEF) {
7011 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7014 return create_invalid_expression();
7016 panic("expected declaration or enum value in reference");
7019 /* we always do the auto-type conversions; the & and sizeof parser contains
7020 * code to revert this! */
7021 type_t *type = automatic_type_conversion(orig_type);
7023 expression_kind_t kind = EXPR_REFERENCE;
7024 if (entity->kind == ENTITY_ENUM_VALUE)
7025 kind = EXPR_REFERENCE_ENUM_VALUE;
7027 expression_t *expression = allocate_expression_zero(kind);
7028 expression->reference.entity = entity;
7029 expression->base.type = type;
7031 /* this declaration is used */
7032 if (is_declaration(entity)) {
7033 entity->declaration.used = true;
7036 if (entity->base.parent_scope != file_scope
7037 && entity->base.parent_scope->depth < current_function->parameters.depth
7038 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7039 if (entity->kind == ENTITY_VARIABLE) {
7040 /* access of a variable from an outer function */
7041 entity->variable.address_taken = true;
7042 } else if (entity->kind == ENTITY_PARAMETER) {
7043 entity->parameter.address_taken = true;
7045 current_function->need_closure = true;
7048 /* check for deprecated functions */
7049 if (warning.deprecated_declarations
7050 && is_declaration(entity)
7051 && entity->declaration.modifiers & DM_DEPRECATED) {
7052 declaration_t *declaration = &entity->declaration;
7054 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7055 "function" : "variable";
7057 if (declaration->deprecated_string != NULL) {
7058 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7059 prefix, entity->base.symbol, &entity->base.source_position,
7060 declaration->deprecated_string);
7062 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7063 entity->base.symbol, &entity->base.source_position);
7067 if (warning.init_self && entity == current_init_decl && !in_type_prop
7068 && entity->kind == ENTITY_VARIABLE) {
7069 current_init_decl = NULL;
7070 warningf(HERE, "variable '%#T' is initialized by itself",
7071 entity->declaration.type, entity->base.symbol);
7078 static bool semantic_cast(expression_t *cast)
7080 expression_t *expression = cast->unary.value;
7081 type_t *orig_dest_type = cast->base.type;
7082 type_t *orig_type_right = expression->base.type;
7083 type_t const *dst_type = skip_typeref(orig_dest_type);
7084 type_t const *src_type = skip_typeref(orig_type_right);
7085 source_position_t const *pos = &cast->base.source_position;
7087 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7088 if (dst_type == type_void)
7091 /* only integer and pointer can be casted to pointer */
7092 if (is_type_pointer(dst_type) &&
7093 !is_type_pointer(src_type) &&
7094 !is_type_integer(src_type) &&
7095 is_type_valid(src_type)) {
7096 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7100 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7101 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7105 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7106 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7110 if (warning.cast_qual &&
7111 is_type_pointer(src_type) &&
7112 is_type_pointer(dst_type)) {
7113 type_t *src = skip_typeref(src_type->pointer.points_to);
7114 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7115 unsigned missing_qualifiers =
7116 src->base.qualifiers & ~dst->base.qualifiers;
7117 if (missing_qualifiers != 0) {
7119 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7120 missing_qualifiers, orig_type_right);
7126 static expression_t *parse_compound_literal(type_t *type)
7128 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7130 parse_initializer_env_t env;
7133 env.must_be_constant = false;
7134 initializer_t *initializer = parse_initializer(&env);
7137 expression->compound_literal.initializer = initializer;
7138 expression->compound_literal.type = type;
7139 expression->base.type = automatic_type_conversion(type);
7145 * Parse a cast expression.
7147 static expression_t *parse_cast(void)
7149 add_anchor_token(')');
7151 source_position_t source_position = token.source_position;
7153 type_t *type = parse_typename();
7155 rem_anchor_token(')');
7156 expect(')', end_error);
7158 if (token.type == '{') {
7159 return parse_compound_literal(type);
7162 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7163 cast->base.source_position = source_position;
7165 expression_t *value = parse_sub_expression(PREC_CAST);
7166 cast->base.type = type;
7167 cast->unary.value = value;
7169 if (! semantic_cast(cast)) {
7170 /* TODO: record the error in the AST. else it is impossible to detect it */
7175 return create_invalid_expression();
7179 * Parse a statement expression.
7181 static expression_t *parse_statement_expression(void)
7183 add_anchor_token(')');
7185 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7187 statement_t *statement = parse_compound_statement(true);
7188 expression->statement.statement = statement;
7190 /* find last statement and use its type */
7191 type_t *type = type_void;
7192 const statement_t *stmt = statement->compound.statements;
7194 while (stmt->base.next != NULL)
7195 stmt = stmt->base.next;
7197 if (stmt->kind == STATEMENT_EXPRESSION) {
7198 type = stmt->expression.expression->base.type;
7200 } else if (warning.other) {
7201 warningf(&expression->base.source_position, "empty statement expression ({})");
7203 expression->base.type = type;
7205 rem_anchor_token(')');
7206 expect(')', end_error);
7213 * Parse a parenthesized expression.
7215 static expression_t *parse_parenthesized_expression(void)
7219 switch (token.type) {
7221 /* gcc extension: a statement expression */
7222 return parse_statement_expression();
7226 return parse_cast();
7228 if (is_typedef_symbol(token.v.symbol)) {
7229 return parse_cast();
7233 add_anchor_token(')');
7234 expression_t *result = parse_expression();
7235 result->base.parenthesized = true;
7236 rem_anchor_token(')');
7237 expect(')', end_error);
7243 static expression_t *parse_function_keyword(void)
7247 if (current_function == NULL) {
7248 errorf(HERE, "'__func__' used outside of a function");
7251 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7252 expression->base.type = type_char_ptr;
7253 expression->funcname.kind = FUNCNAME_FUNCTION;
7260 static expression_t *parse_pretty_function_keyword(void)
7262 if (current_function == NULL) {
7263 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7266 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7267 expression->base.type = type_char_ptr;
7268 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7270 eat(T___PRETTY_FUNCTION__);
7275 static expression_t *parse_funcsig_keyword(void)
7277 if (current_function == NULL) {
7278 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7281 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7282 expression->base.type = type_char_ptr;
7283 expression->funcname.kind = FUNCNAME_FUNCSIG;
7290 static expression_t *parse_funcdname_keyword(void)
7292 if (current_function == NULL) {
7293 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7296 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7297 expression->base.type = type_char_ptr;
7298 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7300 eat(T___FUNCDNAME__);
7305 static designator_t *parse_designator(void)
7307 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7308 result->source_position = *HERE;
7310 if (token.type != T_IDENTIFIER) {
7311 parse_error_expected("while parsing member designator",
7312 T_IDENTIFIER, NULL);
7315 result->symbol = token.v.symbol;
7318 designator_t *last_designator = result;
7320 if (token.type == '.') {
7322 if (token.type != T_IDENTIFIER) {
7323 parse_error_expected("while parsing member designator",
7324 T_IDENTIFIER, NULL);
7327 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7328 designator->source_position = *HERE;
7329 designator->symbol = token.v.symbol;
7332 last_designator->next = designator;
7333 last_designator = designator;
7336 if (token.type == '[') {
7338 add_anchor_token(']');
7339 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7340 designator->source_position = *HERE;
7341 designator->array_index = parse_expression();
7342 rem_anchor_token(']');
7343 expect(']', end_error);
7344 if (designator->array_index == NULL) {
7348 last_designator->next = designator;
7349 last_designator = designator;
7361 * Parse the __builtin_offsetof() expression.
7363 static expression_t *parse_offsetof(void)
7365 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7366 expression->base.type = type_size_t;
7368 eat(T___builtin_offsetof);
7370 expect('(', end_error);
7371 add_anchor_token(',');
7372 type_t *type = parse_typename();
7373 rem_anchor_token(',');
7374 expect(',', end_error);
7375 add_anchor_token(')');
7376 designator_t *designator = parse_designator();
7377 rem_anchor_token(')');
7378 expect(')', end_error);
7380 expression->offsetofe.type = type;
7381 expression->offsetofe.designator = designator;
7384 memset(&path, 0, sizeof(path));
7385 path.top_type = type;
7386 path.path = NEW_ARR_F(type_path_entry_t, 0);
7388 descend_into_subtype(&path);
7390 if (!walk_designator(&path, designator, true)) {
7391 return create_invalid_expression();
7394 DEL_ARR_F(path.path);
7398 return create_invalid_expression();
7402 * Parses a _builtin_va_start() expression.
7404 static expression_t *parse_va_start(void)
7406 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7408 eat(T___builtin_va_start);
7410 expect('(', end_error);
7411 add_anchor_token(',');
7412 expression->va_starte.ap = parse_assignment_expression();
7413 rem_anchor_token(',');
7414 expect(',', end_error);
7415 expression_t *const expr = parse_assignment_expression();
7416 if (expr->kind == EXPR_REFERENCE) {
7417 entity_t *const entity = expr->reference.entity;
7418 if (entity->base.parent_scope != ¤t_function->parameters
7419 || entity->base.next != NULL
7420 || entity->kind != ENTITY_PARAMETER) {
7421 errorf(&expr->base.source_position,
7422 "second argument of 'va_start' must be last parameter of the current function");
7424 expression->va_starte.parameter = &entity->variable;
7426 expect(')', end_error);
7429 expect(')', end_error);
7431 return create_invalid_expression();
7435 * Parses a _builtin_va_arg() expression.
7437 static expression_t *parse_va_arg(void)
7439 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7441 eat(T___builtin_va_arg);
7443 expect('(', end_error);
7444 expression->va_arge.ap = parse_assignment_expression();
7445 expect(',', end_error);
7446 expression->base.type = parse_typename();
7447 expect(')', end_error);
7451 return create_invalid_expression();
7454 static expression_t *parse_builtin_symbol(void)
7456 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7458 symbol_t *symbol = token.v.symbol;
7460 expression->builtin_symbol.symbol = symbol;
7463 type_t *type = get_builtin_symbol_type(symbol);
7464 type = automatic_type_conversion(type);
7466 expression->base.type = type;
7471 * Parses a __builtin_constant() expression.
7473 static expression_t *parse_builtin_constant(void)
7475 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7477 eat(T___builtin_constant_p);
7479 expect('(', end_error);
7480 add_anchor_token(')');
7481 expression->builtin_constant.value = parse_assignment_expression();
7482 rem_anchor_token(')');
7483 expect(')', end_error);
7484 expression->base.type = type_int;
7488 return create_invalid_expression();
7492 * Parses a __builtin_prefetch() expression.
7494 static expression_t *parse_builtin_prefetch(void)
7496 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7498 eat(T___builtin_prefetch);
7500 expect('(', end_error);
7501 add_anchor_token(')');
7502 expression->builtin_prefetch.adr = parse_assignment_expression();
7503 if (token.type == ',') {
7505 expression->builtin_prefetch.rw = parse_assignment_expression();
7507 if (token.type == ',') {
7509 expression->builtin_prefetch.locality = parse_assignment_expression();
7511 rem_anchor_token(')');
7512 expect(')', end_error);
7513 expression->base.type = type_void;
7517 return create_invalid_expression();
7521 * Parses a __builtin_is_*() compare expression.
7523 static expression_t *parse_compare_builtin(void)
7525 expression_t *expression;
7527 switch (token.type) {
7528 case T___builtin_isgreater:
7529 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7531 case T___builtin_isgreaterequal:
7532 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7534 case T___builtin_isless:
7535 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7537 case T___builtin_islessequal:
7538 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7540 case T___builtin_islessgreater:
7541 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7543 case T___builtin_isunordered:
7544 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7547 internal_errorf(HERE, "invalid compare builtin found");
7549 expression->base.source_position = *HERE;
7552 expect('(', end_error);
7553 expression->binary.left = parse_assignment_expression();
7554 expect(',', end_error);
7555 expression->binary.right = parse_assignment_expression();
7556 expect(')', end_error);
7558 type_t *const orig_type_left = expression->binary.left->base.type;
7559 type_t *const orig_type_right = expression->binary.right->base.type;
7561 type_t *const type_left = skip_typeref(orig_type_left);
7562 type_t *const type_right = skip_typeref(orig_type_right);
7563 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7564 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7565 type_error_incompatible("invalid operands in comparison",
7566 &expression->base.source_position, orig_type_left, orig_type_right);
7569 semantic_comparison(&expression->binary);
7574 return create_invalid_expression();
7579 * Parses a __builtin_expect(, end_error) expression.
7581 static expression_t *parse_builtin_expect(void, end_error)
7583 expression_t *expression
7584 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7586 eat(T___builtin_expect);
7588 expect('(', end_error);
7589 expression->binary.left = parse_assignment_expression();
7590 expect(',', end_error);
7591 expression->binary.right = parse_constant_expression();
7592 expect(')', end_error);
7594 expression->base.type = expression->binary.left->base.type;
7598 return create_invalid_expression();
7603 * Parses a MS assume() expression.
7605 static expression_t *parse_assume(void)
7607 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7611 expect('(', end_error);
7612 add_anchor_token(')');
7613 expression->unary.value = parse_assignment_expression();
7614 rem_anchor_token(')');
7615 expect(')', end_error);
7617 expression->base.type = type_void;
7620 return create_invalid_expression();
7624 * Return the declaration for a given label symbol or create a new one.
7626 * @param symbol the symbol of the label
7628 static label_t *get_label(symbol_t *symbol)
7631 assert(current_function != NULL);
7633 label = get_entity(symbol, NAMESPACE_LABEL);
7634 /* if we found a local label, we already created the declaration */
7635 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7636 if (label->base.parent_scope != current_scope) {
7637 assert(label->base.parent_scope->depth < current_scope->depth);
7638 current_function->goto_to_outer = true;
7640 return &label->label;
7643 label = get_entity(symbol, NAMESPACE_LABEL);
7644 /* if we found a label in the same function, then we already created the
7647 && label->base.parent_scope == ¤t_function->parameters) {
7648 return &label->label;
7651 /* otherwise we need to create a new one */
7652 label = allocate_entity_zero(ENTITY_LABEL);
7653 label->base.namespc = NAMESPACE_LABEL;
7654 label->base.symbol = symbol;
7658 return &label->label;
7662 * Parses a GNU && label address expression.
7664 static expression_t *parse_label_address(void)
7666 source_position_t source_position = token.source_position;
7668 if (token.type != T_IDENTIFIER) {
7669 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7672 symbol_t *symbol = token.v.symbol;
7675 label_t *label = get_label(symbol);
7677 label->address_taken = true;
7679 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7680 expression->base.source_position = source_position;
7682 /* label address is threaten as a void pointer */
7683 expression->base.type = type_void_ptr;
7684 expression->label_address.label = label;
7687 return create_invalid_expression();
7691 * Parse a microsoft __noop expression.
7693 static expression_t *parse_noop_expression(void)
7695 /* the result is a (int)0 */
7696 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7697 cnst->base.type = type_int;
7698 cnst->conste.v.int_value = 0;
7699 cnst->conste.is_ms_noop = true;
7703 if (token.type == '(') {
7704 /* parse arguments */
7706 add_anchor_token(')');
7707 add_anchor_token(',');
7709 if (token.type != ')') {
7711 (void)parse_assignment_expression();
7712 if (token.type != ',')
7718 rem_anchor_token(',');
7719 rem_anchor_token(')');
7720 expect(')', end_error);
7727 * Parses a primary expression.
7729 static expression_t *parse_primary_expression(void)
7731 switch (token.type) {
7732 case T_false: return parse_bool_const(false);
7733 case T_true: return parse_bool_const(true);
7734 case T_INTEGER: return parse_int_const();
7735 case T_CHARACTER_CONSTANT: return parse_character_constant();
7736 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7737 case T_FLOATINGPOINT: return parse_float_const();
7738 case T_STRING_LITERAL:
7739 case T_WIDE_STRING_LITERAL: return parse_string_const();
7740 case T_IDENTIFIER: return parse_reference();
7741 case T___FUNCTION__:
7742 case T___func__: return parse_function_keyword();
7743 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7744 case T___FUNCSIG__: return parse_funcsig_keyword();
7745 case T___FUNCDNAME__: return parse_funcdname_keyword();
7746 case T___builtin_offsetof: return parse_offsetof();
7747 case T___builtin_va_start: return parse_va_start();
7748 case T___builtin_va_arg: return parse_va_arg();
7749 case T___builtin_expect:
7750 case T___builtin_alloca:
7751 case T___builtin_inf:
7752 case T___builtin_inff:
7753 case T___builtin_infl:
7754 case T___builtin_nan:
7755 case T___builtin_nanf:
7756 case T___builtin_nanl:
7757 case T___builtin_huge_val:
7758 case T___builtin_va_end: return parse_builtin_symbol();
7759 case T___builtin_isgreater:
7760 case T___builtin_isgreaterequal:
7761 case T___builtin_isless:
7762 case T___builtin_islessequal:
7763 case T___builtin_islessgreater:
7764 case T___builtin_isunordered: return parse_compare_builtin();
7765 case T___builtin_constant_p: return parse_builtin_constant();
7766 case T___builtin_prefetch: return parse_builtin_prefetch();
7767 case T__assume: return parse_assume();
7770 return parse_label_address();
7773 case '(': return parse_parenthesized_expression();
7774 case T___noop: return parse_noop_expression();
7777 errorf(HERE, "unexpected token %K, expected an expression", &token);
7778 return create_invalid_expression();
7782 * Check if the expression has the character type and issue a warning then.
7784 static void check_for_char_index_type(const expression_t *expression)
7786 type_t *const type = expression->base.type;
7787 const type_t *const base_type = skip_typeref(type);
7789 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7790 warning.char_subscripts) {
7791 warningf(&expression->base.source_position,
7792 "array subscript has type '%T'", type);
7796 static expression_t *parse_array_expression(expression_t *left)
7798 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7801 add_anchor_token(']');
7803 expression_t *inside = parse_expression();
7805 type_t *const orig_type_left = left->base.type;
7806 type_t *const orig_type_inside = inside->base.type;
7808 type_t *const type_left = skip_typeref(orig_type_left);
7809 type_t *const type_inside = skip_typeref(orig_type_inside);
7811 type_t *return_type;
7812 array_access_expression_t *array_access = &expression->array_access;
7813 if (is_type_pointer(type_left)) {
7814 return_type = type_left->pointer.points_to;
7815 array_access->array_ref = left;
7816 array_access->index = inside;
7817 check_for_char_index_type(inside);
7818 } else if (is_type_pointer(type_inside)) {
7819 return_type = type_inside->pointer.points_to;
7820 array_access->array_ref = inside;
7821 array_access->index = left;
7822 array_access->flipped = true;
7823 check_for_char_index_type(left);
7825 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7827 "array access on object with non-pointer types '%T', '%T'",
7828 orig_type_left, orig_type_inside);
7830 return_type = type_error_type;
7831 array_access->array_ref = left;
7832 array_access->index = inside;
7835 expression->base.type = automatic_type_conversion(return_type);
7837 rem_anchor_token(']');
7838 expect(']', end_error);
7843 static expression_t *parse_typeprop(expression_kind_t const kind)
7845 expression_t *tp_expression = allocate_expression_zero(kind);
7846 tp_expression->base.type = type_size_t;
7848 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7850 /* we only refer to a type property, mark this case */
7851 bool old = in_type_prop;
7852 in_type_prop = true;
7855 expression_t *expression;
7856 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7858 add_anchor_token(')');
7859 orig_type = parse_typename();
7860 rem_anchor_token(')');
7861 expect(')', end_error);
7863 if (token.type == '{') {
7864 /* It was not sizeof(type) after all. It is sizeof of an expression
7865 * starting with a compound literal */
7866 expression = parse_compound_literal(orig_type);
7867 goto typeprop_expression;
7870 expression = parse_sub_expression(PREC_UNARY);
7872 typeprop_expression:
7873 tp_expression->typeprop.tp_expression = expression;
7875 orig_type = revert_automatic_type_conversion(expression);
7876 expression->base.type = orig_type;
7879 tp_expression->typeprop.type = orig_type;
7880 type_t const* const type = skip_typeref(orig_type);
7881 char const* const wrong_type =
7882 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7883 is_type_incomplete(type) ? "incomplete" :
7884 type->kind == TYPE_FUNCTION ? "function designator" :
7885 type->kind == TYPE_BITFIELD ? "bitfield" :
7887 if (wrong_type != NULL) {
7888 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7889 errorf(&tp_expression->base.source_position,
7890 "operand of %s expression must not be of %s type '%T'",
7891 what, wrong_type, orig_type);
7896 return tp_expression;
7899 static expression_t *parse_sizeof(void)
7901 return parse_typeprop(EXPR_SIZEOF);
7904 static expression_t *parse_alignof(void)
7906 return parse_typeprop(EXPR_ALIGNOF);
7909 static expression_t *parse_select_expression(expression_t *compound)
7911 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7912 select->select.compound = compound;
7914 assert(token.type == '.' || token.type == T_MINUSGREATER);
7915 bool is_pointer = (token.type == T_MINUSGREATER);
7918 if (token.type != T_IDENTIFIER) {
7919 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7922 symbol_t *symbol = token.v.symbol;
7925 type_t *const orig_type = compound->base.type;
7926 type_t *const type = skip_typeref(orig_type);
7929 bool saw_error = false;
7930 if (is_type_pointer(type)) {
7933 "request for member '%Y' in something not a struct or union, but '%T'",
7937 type_left = skip_typeref(type->pointer.points_to);
7939 if (is_pointer && is_type_valid(type)) {
7940 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7947 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7948 type_left->kind == TYPE_COMPOUND_UNION) {
7949 compound_t *compound = type_left->compound.compound;
7951 if (!compound->complete) {
7952 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7954 goto create_error_entry;
7957 entry = find_compound_entry(compound, symbol);
7958 if (entry == NULL) {
7959 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7960 goto create_error_entry;
7963 if (is_type_valid(type_left) && !saw_error) {
7965 "request for member '%Y' in something not a struct or union, but '%T'",
7969 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7972 assert(is_declaration(entry));
7973 select->select.compound_entry = entry;
7975 type_t *entry_type = entry->declaration.type;
7977 = get_qualified_type(entry_type, type_left->base.qualifiers);
7979 /* we always do the auto-type conversions; the & and sizeof parser contains
7980 * code to revert this! */
7981 select->base.type = automatic_type_conversion(res_type);
7983 type_t *skipped = skip_typeref(res_type);
7984 if (skipped->kind == TYPE_BITFIELD) {
7985 select->base.type = skipped->bitfield.base_type;
7991 static void check_call_argument(const function_parameter_t *parameter,
7992 call_argument_t *argument, unsigned pos)
7994 type_t *expected_type = parameter->type;
7995 type_t *expected_type_skip = skip_typeref(expected_type);
7996 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7997 expression_t *arg_expr = argument->expression;
7998 type_t *arg_type = skip_typeref(arg_expr->base.type);
8000 /* handle transparent union gnu extension */
8001 if (is_type_union(expected_type_skip)
8002 && (expected_type_skip->base.modifiers
8003 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8004 compound_t *union_decl = expected_type_skip->compound.compound;
8005 type_t *best_type = NULL;
8006 entity_t *entry = union_decl->members.entities;
8007 for ( ; entry != NULL; entry = entry->base.next) {
8008 assert(is_declaration(entry));
8009 type_t *decl_type = entry->declaration.type;
8010 error = semantic_assign(decl_type, arg_expr);
8011 if (error == ASSIGN_ERROR_INCOMPATIBLE
8012 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8015 if (error == ASSIGN_SUCCESS) {
8016 best_type = decl_type;
8017 } else if (best_type == NULL) {
8018 best_type = decl_type;
8022 if (best_type != NULL) {
8023 expected_type = best_type;
8027 error = semantic_assign(expected_type, arg_expr);
8028 argument->expression = create_implicit_cast(argument->expression,
8031 if (error != ASSIGN_SUCCESS) {
8032 /* report exact scope in error messages (like "in argument 3") */
8034 snprintf(buf, sizeof(buf), "call argument %u", pos);
8035 report_assign_error(error, expected_type, arg_expr, buf,
8036 &arg_expr->base.source_position);
8037 } else if (warning.traditional || warning.conversion) {
8038 type_t *const promoted_type = get_default_promoted_type(arg_type);
8039 if (!types_compatible(expected_type_skip, promoted_type) &&
8040 !types_compatible(expected_type_skip, type_void_ptr) &&
8041 !types_compatible(type_void_ptr, promoted_type)) {
8042 /* Deliberately show the skipped types in this warning */
8043 warningf(&arg_expr->base.source_position,
8044 "passing call argument %u as '%T' rather than '%T' due to prototype",
8045 pos, expected_type_skip, promoted_type);
8051 * Parse a call expression, ie. expression '( ... )'.
8053 * @param expression the function address
8055 static expression_t *parse_call_expression(expression_t *expression)
8057 expression_t *result = allocate_expression_zero(EXPR_CALL);
8058 call_expression_t *call = &result->call;
8059 call->function = expression;
8061 type_t *const orig_type = expression->base.type;
8062 type_t *const type = skip_typeref(orig_type);
8064 function_type_t *function_type = NULL;
8065 if (is_type_pointer(type)) {
8066 type_t *const to_type = skip_typeref(type->pointer.points_to);
8068 if (is_type_function(to_type)) {
8069 function_type = &to_type->function;
8070 call->base.type = function_type->return_type;
8074 if (function_type == NULL && is_type_valid(type)) {
8075 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8078 /* parse arguments */
8080 add_anchor_token(')');
8081 add_anchor_token(',');
8083 if (token.type != ')') {
8084 call_argument_t *last_argument = NULL;
8087 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8089 argument->expression = parse_assignment_expression();
8090 if (last_argument == NULL) {
8091 call->arguments = argument;
8093 last_argument->next = argument;
8095 last_argument = argument;
8097 if (token.type != ',')
8102 rem_anchor_token(',');
8103 rem_anchor_token(')');
8104 expect(')', end_error);
8106 if (function_type == NULL)
8109 function_parameter_t *parameter = function_type->parameters;
8110 call_argument_t *argument = call->arguments;
8111 if (!function_type->unspecified_parameters) {
8112 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8113 parameter = parameter->next, argument = argument->next) {
8114 check_call_argument(parameter, argument, ++pos);
8117 if (parameter != NULL) {
8118 errorf(HERE, "too few arguments to function '%E'", expression);
8119 } else if (argument != NULL && !function_type->variadic) {
8120 errorf(HERE, "too many arguments to function '%E'", expression);
8124 /* do default promotion */
8125 for (; argument != NULL; argument = argument->next) {
8126 type_t *type = argument->expression->base.type;
8128 type = get_default_promoted_type(type);
8130 argument->expression
8131 = create_implicit_cast(argument->expression, type);
8134 check_format(&result->call);
8136 if (warning.aggregate_return &&
8137 is_type_compound(skip_typeref(function_type->return_type))) {
8138 warningf(&result->base.source_position,
8139 "function call has aggregate value");
8146 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8148 static bool same_compound_type(const type_t *type1, const type_t *type2)
8151 is_type_compound(type1) &&
8152 type1->kind == type2->kind &&
8153 type1->compound.compound == type2->compound.compound;
8156 static expression_t const *get_reference_address(expression_t const *expr)
8158 bool regular_take_address = true;
8160 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8161 expr = expr->unary.value;
8163 regular_take_address = false;
8166 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8169 expr = expr->unary.value;
8172 if (expr->kind != EXPR_REFERENCE)
8175 /* special case for functions which are automatically converted to a
8176 * pointer to function without an extra TAKE_ADDRESS operation */
8177 if (!regular_take_address &&
8178 expr->reference.entity->kind != ENTITY_FUNCTION) {
8185 static void warn_reference_address_as_bool(expression_t const* expr)
8187 if (!warning.address)
8190 expr = get_reference_address(expr);
8192 warningf(&expr->base.source_position,
8193 "the address of '%Y' will always evaluate as 'true'",
8194 expr->reference.entity->base.symbol);
8198 static void warn_assignment_in_condition(const expression_t *const expr)
8200 if (!warning.parentheses)
8202 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8204 if (expr->base.parenthesized)
8206 warningf(&expr->base.source_position,
8207 "suggest parentheses around assignment used as truth value");
8210 static void semantic_condition(expression_t const *const expr,
8211 char const *const context)
8213 type_t *const type = skip_typeref(expr->base.type);
8214 if (is_type_scalar(type)) {
8215 warn_reference_address_as_bool(expr);
8216 warn_assignment_in_condition(expr);
8217 } else if (is_type_valid(type)) {
8218 errorf(&expr->base.source_position,
8219 "%s must have scalar type", context);
8224 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8226 * @param expression the conditional expression
8228 static expression_t *parse_conditional_expression(expression_t *expression)
8230 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8232 conditional_expression_t *conditional = &result->conditional;
8233 conditional->condition = expression;
8236 add_anchor_token(':');
8238 /* §6.5.15:2 The first operand shall have scalar type. */
8239 semantic_condition(expression, "condition of conditional operator");
8241 expression_t *true_expression = expression;
8242 bool gnu_cond = false;
8243 if (GNU_MODE && token.type == ':') {
8246 true_expression = parse_expression();
8248 rem_anchor_token(':');
8249 expect(':', end_error);
8251 expression_t *false_expression =
8252 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8254 type_t *const orig_true_type = true_expression->base.type;
8255 type_t *const orig_false_type = false_expression->base.type;
8256 type_t *const true_type = skip_typeref(orig_true_type);
8257 type_t *const false_type = skip_typeref(orig_false_type);
8260 type_t *result_type;
8261 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8262 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8263 /* ISO/IEC 14882:1998(E) §5.16:2 */
8264 if (true_expression->kind == EXPR_UNARY_THROW) {
8265 result_type = false_type;
8266 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8267 result_type = true_type;
8269 if (warning.other && (
8270 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8271 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8273 warningf(&conditional->base.source_position,
8274 "ISO C forbids conditional expression with only one void side");
8276 result_type = type_void;
8278 } else if (is_type_arithmetic(true_type)
8279 && is_type_arithmetic(false_type)) {
8280 result_type = semantic_arithmetic(true_type, false_type);
8282 true_expression = create_implicit_cast(true_expression, result_type);
8283 false_expression = create_implicit_cast(false_expression, result_type);
8285 conditional->true_expression = true_expression;
8286 conditional->false_expression = false_expression;
8287 conditional->base.type = result_type;
8288 } else if (same_compound_type(true_type, false_type)) {
8289 /* just take 1 of the 2 types */
8290 result_type = true_type;
8291 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8292 type_t *pointer_type;
8294 expression_t *other_expression;
8295 if (is_type_pointer(true_type) &&
8296 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8297 pointer_type = true_type;
8298 other_type = false_type;
8299 other_expression = false_expression;
8301 pointer_type = false_type;
8302 other_type = true_type;
8303 other_expression = true_expression;
8306 if (is_null_pointer_constant(other_expression)) {
8307 result_type = pointer_type;
8308 } else if (is_type_pointer(other_type)) {
8309 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8310 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8313 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8314 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8316 } else if (types_compatible(get_unqualified_type(to1),
8317 get_unqualified_type(to2))) {
8320 if (warning.other) {
8321 warningf(&conditional->base.source_position,
8322 "pointer types '%T' and '%T' in conditional expression are incompatible",
8323 true_type, false_type);
8328 type_t *const type =
8329 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8330 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8331 } else if (is_type_integer(other_type)) {
8332 if (warning.other) {
8333 warningf(&conditional->base.source_position,
8334 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8336 result_type = pointer_type;
8338 if (is_type_valid(other_type)) {
8339 type_error_incompatible("while parsing conditional",
8340 &expression->base.source_position, true_type, false_type);
8342 result_type = type_error_type;
8345 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8346 type_error_incompatible("while parsing conditional",
8347 &conditional->base.source_position, true_type,
8350 result_type = type_error_type;
8353 conditional->true_expression
8354 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8355 conditional->false_expression
8356 = create_implicit_cast(false_expression, result_type);
8357 conditional->base.type = result_type;
8362 * Parse an extension expression.
8364 static expression_t *parse_extension(void)
8366 eat(T___extension__);
8368 bool old_gcc_extension = in_gcc_extension;
8369 in_gcc_extension = true;
8370 expression_t *expression = parse_sub_expression(PREC_UNARY);
8371 in_gcc_extension = old_gcc_extension;
8376 * Parse a __builtin_classify_type() expression.
8378 static expression_t *parse_builtin_classify_type(void)
8380 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8381 result->base.type = type_int;
8383 eat(T___builtin_classify_type);
8385 expect('(', end_error);
8386 add_anchor_token(')');
8387 expression_t *expression = parse_expression();
8388 rem_anchor_token(')');
8389 expect(')', end_error);
8390 result->classify_type.type_expression = expression;
8394 return create_invalid_expression();
8398 * Parse a delete expression
8399 * ISO/IEC 14882:1998(E) §5.3.5
8401 static expression_t *parse_delete(void)
8403 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8404 result->base.type = type_void;
8408 if (token.type == '[') {
8410 result->kind = EXPR_UNARY_DELETE_ARRAY;
8411 expect(']', end_error);
8415 expression_t *const value = parse_sub_expression(PREC_CAST);
8416 result->unary.value = value;
8418 type_t *const type = skip_typeref(value->base.type);
8419 if (!is_type_pointer(type)) {
8420 errorf(&value->base.source_position,
8421 "operand of delete must have pointer type");
8422 } else if (warning.other &&
8423 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8424 warningf(&value->base.source_position,
8425 "deleting 'void*' is undefined");
8432 * Parse a throw expression
8433 * ISO/IEC 14882:1998(E) §15:1
8435 static expression_t *parse_throw(void)
8437 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8438 result->base.type = type_void;
8442 expression_t *value = NULL;
8443 switch (token.type) {
8445 value = parse_assignment_expression();
8446 /* ISO/IEC 14882:1998(E) §15.1:3 */
8447 type_t *const orig_type = value->base.type;
8448 type_t *const type = skip_typeref(orig_type);
8449 if (is_type_incomplete(type)) {
8450 errorf(&value->base.source_position,
8451 "cannot throw object of incomplete type '%T'", orig_type);
8452 } else if (is_type_pointer(type)) {
8453 type_t *const points_to = skip_typeref(type->pointer.points_to);
8454 if (is_type_incomplete(points_to) &&
8455 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8456 errorf(&value->base.source_position,
8457 "cannot throw pointer to incomplete type '%T'", orig_type);
8465 result->unary.value = value;
8470 static bool check_pointer_arithmetic(const source_position_t *source_position,
8471 type_t *pointer_type,
8472 type_t *orig_pointer_type)
8474 type_t *points_to = pointer_type->pointer.points_to;
8475 points_to = skip_typeref(points_to);
8477 if (is_type_incomplete(points_to)) {
8478 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8479 errorf(source_position,
8480 "arithmetic with pointer to incomplete type '%T' not allowed",
8483 } else if (warning.pointer_arith) {
8484 warningf(source_position,
8485 "pointer of type '%T' used in arithmetic",
8488 } else if (is_type_function(points_to)) {
8490 errorf(source_position,
8491 "arithmetic with pointer to function type '%T' not allowed",
8494 } else if (warning.pointer_arith) {
8495 warningf(source_position,
8496 "pointer to a function '%T' used in arithmetic",
8503 static bool is_lvalue(const expression_t *expression)
8505 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8506 switch (expression->kind) {
8507 case EXPR_ARRAY_ACCESS:
8508 case EXPR_COMPOUND_LITERAL:
8509 case EXPR_REFERENCE:
8511 case EXPR_UNARY_DEREFERENCE:
8515 type_t *type = skip_typeref(expression->base.type);
8517 /* ISO/IEC 14882:1998(E) §3.10:3 */
8518 is_type_reference(type) ||
8519 /* Claim it is an lvalue, if the type is invalid. There was a parse
8520 * error before, which maybe prevented properly recognizing it as
8522 !is_type_valid(type);
8527 static void semantic_incdec(unary_expression_t *expression)
8529 type_t *const orig_type = expression->value->base.type;
8530 type_t *const type = skip_typeref(orig_type);
8531 if (is_type_pointer(type)) {
8532 if (!check_pointer_arithmetic(&expression->base.source_position,
8536 } else if (!is_type_real(type) && is_type_valid(type)) {
8537 /* TODO: improve error message */
8538 errorf(&expression->base.source_position,
8539 "operation needs an arithmetic or pointer type");
8542 if (!is_lvalue(expression->value)) {
8543 /* TODO: improve error message */
8544 errorf(&expression->base.source_position, "lvalue required as operand");
8546 expression->base.type = orig_type;
8549 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8551 type_t *const orig_type = expression->value->base.type;
8552 type_t *const type = skip_typeref(orig_type);
8553 if (!is_type_arithmetic(type)) {
8554 if (is_type_valid(type)) {
8555 /* TODO: improve error message */
8556 errorf(&expression->base.source_position,
8557 "operation needs an arithmetic type");
8562 expression->base.type = orig_type;
8565 static void semantic_unexpr_plus(unary_expression_t *expression)
8567 semantic_unexpr_arithmetic(expression);
8568 if (warning.traditional)
8569 warningf(&expression->base.source_position,
8570 "traditional C rejects the unary plus operator");
8573 static void semantic_not(unary_expression_t *expression)
8575 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8576 semantic_condition(expression->value, "operand of !");
8577 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8580 static void semantic_unexpr_integer(unary_expression_t *expression)
8582 type_t *const orig_type = expression->value->base.type;
8583 type_t *const type = skip_typeref(orig_type);
8584 if (!is_type_integer(type)) {
8585 if (is_type_valid(type)) {
8586 errorf(&expression->base.source_position,
8587 "operand of ~ must be of integer type");
8592 expression->base.type = orig_type;
8595 static void semantic_dereference(unary_expression_t *expression)
8597 type_t *const orig_type = expression->value->base.type;
8598 type_t *const type = skip_typeref(orig_type);
8599 if (!is_type_pointer(type)) {
8600 if (is_type_valid(type)) {
8601 errorf(&expression->base.source_position,
8602 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8607 type_t *result_type = type->pointer.points_to;
8608 result_type = automatic_type_conversion(result_type);
8609 expression->base.type = result_type;
8613 * Record that an address is taken (expression represents an lvalue).
8615 * @param expression the expression
8616 * @param may_be_register if true, the expression might be an register
8618 static void set_address_taken(expression_t *expression, bool may_be_register)
8620 if (expression->kind != EXPR_REFERENCE)
8623 entity_t *const entity = expression->reference.entity;
8625 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8628 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8629 && !may_be_register) {
8630 errorf(&expression->base.source_position,
8631 "address of register %s '%Y' requested",
8632 get_entity_kind_name(entity->kind), entity->base.symbol);
8635 if (entity->kind == ENTITY_VARIABLE) {
8636 entity->variable.address_taken = true;
8638 assert(entity->kind == ENTITY_PARAMETER);
8639 entity->parameter.address_taken = true;
8644 * Check the semantic of the address taken expression.
8646 static void semantic_take_addr(unary_expression_t *expression)
8648 expression_t *value = expression->value;
8649 value->base.type = revert_automatic_type_conversion(value);
8651 type_t *orig_type = value->base.type;
8652 type_t *type = skip_typeref(orig_type);
8653 if (!is_type_valid(type))
8657 if (!is_lvalue(value)) {
8658 errorf(&expression->base.source_position, "'&' requires an lvalue");
8660 if (type->kind == TYPE_BITFIELD) {
8661 errorf(&expression->base.source_position,
8662 "'&' not allowed on object with bitfield type '%T'",
8666 set_address_taken(value, false);
8668 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8671 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8672 static expression_t *parse_##unexpression_type(void) \
8674 expression_t *unary_expression \
8675 = allocate_expression_zero(unexpression_type); \
8677 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8679 sfunc(&unary_expression->unary); \
8681 return unary_expression; \
8684 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8685 semantic_unexpr_arithmetic)
8686 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8687 semantic_unexpr_plus)
8688 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8690 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8691 semantic_dereference)
8692 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8694 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8695 semantic_unexpr_integer)
8696 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8698 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8701 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8703 static expression_t *parse_##unexpression_type(expression_t *left) \
8705 expression_t *unary_expression \
8706 = allocate_expression_zero(unexpression_type); \
8708 unary_expression->unary.value = left; \
8710 sfunc(&unary_expression->unary); \
8712 return unary_expression; \
8715 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8716 EXPR_UNARY_POSTFIX_INCREMENT,
8718 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8719 EXPR_UNARY_POSTFIX_DECREMENT,
8722 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8724 /* TODO: handle complex + imaginary types */
8726 type_left = get_unqualified_type(type_left);
8727 type_right = get_unqualified_type(type_right);
8729 /* § 6.3.1.8 Usual arithmetic conversions */
8730 if (type_left == type_long_double || type_right == type_long_double) {
8731 return type_long_double;
8732 } else if (type_left == type_double || type_right == type_double) {
8734 } else if (type_left == type_float || type_right == type_float) {
8738 type_left = promote_integer(type_left);
8739 type_right = promote_integer(type_right);
8741 if (type_left == type_right)
8744 bool const signed_left = is_type_signed(type_left);
8745 bool const signed_right = is_type_signed(type_right);
8746 int const rank_left = get_rank(type_left);
8747 int const rank_right = get_rank(type_right);
8749 if (signed_left == signed_right)
8750 return rank_left >= rank_right ? type_left : type_right;
8759 u_rank = rank_right;
8760 u_type = type_right;
8762 s_rank = rank_right;
8763 s_type = type_right;
8768 if (u_rank >= s_rank)
8771 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8773 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8774 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8778 case ATOMIC_TYPE_INT: return type_unsigned_int;
8779 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8780 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8782 default: panic("invalid atomic type");
8787 * Check the semantic restrictions for a binary expression.
8789 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8791 expression_t *const left = expression->left;
8792 expression_t *const right = expression->right;
8793 type_t *const orig_type_left = left->base.type;
8794 type_t *const orig_type_right = right->base.type;
8795 type_t *const type_left = skip_typeref(orig_type_left);
8796 type_t *const type_right = skip_typeref(orig_type_right);
8798 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8799 /* TODO: improve error message */
8800 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8801 errorf(&expression->base.source_position,
8802 "operation needs arithmetic types");
8807 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8808 expression->left = create_implicit_cast(left, arithmetic_type);
8809 expression->right = create_implicit_cast(right, arithmetic_type);
8810 expression->base.type = arithmetic_type;
8813 static void warn_div_by_zero(binary_expression_t const *const expression)
8815 if (!warning.div_by_zero ||
8816 !is_type_integer(expression->base.type))
8819 expression_t const *const right = expression->right;
8820 /* The type of the right operand can be different for /= */
8821 if (is_type_integer(right->base.type) &&
8822 is_constant_expression(right) &&
8823 fold_constant(right) == 0) {
8824 warningf(&expression->base.source_position, "division by zero");
8829 * Check the semantic restrictions for a div/mod expression.
8831 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8832 semantic_binexpr_arithmetic(expression);
8833 warn_div_by_zero(expression);
8836 static void semantic_shift_op(binary_expression_t *expression)
8838 expression_t *const left = expression->left;
8839 expression_t *const right = expression->right;
8840 type_t *const orig_type_left = left->base.type;
8841 type_t *const orig_type_right = right->base.type;
8842 type_t * type_left = skip_typeref(orig_type_left);
8843 type_t * type_right = skip_typeref(orig_type_right);
8845 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8846 /* TODO: improve error message */
8847 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8848 errorf(&expression->base.source_position,
8849 "operands of shift operation must have integer types");
8854 type_left = promote_integer(type_left);
8855 type_right = promote_integer(type_right);
8857 expression->left = create_implicit_cast(left, type_left);
8858 expression->right = create_implicit_cast(right, type_right);
8859 expression->base.type = type_left;
8862 static void semantic_add(binary_expression_t *expression)
8864 expression_t *const left = expression->left;
8865 expression_t *const right = expression->right;
8866 type_t *const orig_type_left = left->base.type;
8867 type_t *const orig_type_right = right->base.type;
8868 type_t *const type_left = skip_typeref(orig_type_left);
8869 type_t *const type_right = skip_typeref(orig_type_right);
8872 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8873 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8874 expression->left = create_implicit_cast(left, arithmetic_type);
8875 expression->right = create_implicit_cast(right, arithmetic_type);
8876 expression->base.type = arithmetic_type;
8878 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8879 check_pointer_arithmetic(&expression->base.source_position,
8880 type_left, orig_type_left);
8881 expression->base.type = type_left;
8882 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8883 check_pointer_arithmetic(&expression->base.source_position,
8884 type_right, orig_type_right);
8885 expression->base.type = type_right;
8886 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8887 errorf(&expression->base.source_position,
8888 "invalid operands to binary + ('%T', '%T')",
8889 orig_type_left, orig_type_right);
8893 static void semantic_sub(binary_expression_t *expression)
8895 expression_t *const left = expression->left;
8896 expression_t *const right = expression->right;
8897 type_t *const orig_type_left = left->base.type;
8898 type_t *const orig_type_right = right->base.type;
8899 type_t *const type_left = skip_typeref(orig_type_left);
8900 type_t *const type_right = skip_typeref(orig_type_right);
8901 source_position_t const *const pos = &expression->base.source_position;
8904 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8905 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8906 expression->left = create_implicit_cast(left, arithmetic_type);
8907 expression->right = create_implicit_cast(right, arithmetic_type);
8908 expression->base.type = arithmetic_type;
8910 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8911 check_pointer_arithmetic(&expression->base.source_position,
8912 type_left, orig_type_left);
8913 expression->base.type = type_left;
8914 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8915 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8916 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8917 if (!types_compatible(unqual_left, unqual_right)) {
8919 "subtracting pointers to incompatible types '%T' and '%T'",
8920 orig_type_left, orig_type_right);
8921 } else if (!is_type_object(unqual_left)) {
8922 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8923 errorf(pos, "subtracting pointers to non-object types '%T'",
8925 } else if (warning.other) {
8926 warningf(pos, "subtracting pointers to void");
8929 expression->base.type = type_ptrdiff_t;
8930 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8931 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8932 orig_type_left, orig_type_right);
8936 static void warn_string_literal_address(expression_t const* expr)
8938 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8939 expr = expr->unary.value;
8940 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8942 expr = expr->unary.value;
8945 if (expr->kind == EXPR_STRING_LITERAL ||
8946 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8947 warningf(&expr->base.source_position,
8948 "comparison with string literal results in unspecified behaviour");
8952 static void warn_comparison_in_comparison(const expression_t *const expr)
8954 if (expr->base.parenthesized)
8956 switch (expr->base.kind) {
8957 case EXPR_BINARY_LESS:
8958 case EXPR_BINARY_GREATER:
8959 case EXPR_BINARY_LESSEQUAL:
8960 case EXPR_BINARY_GREATEREQUAL:
8961 case EXPR_BINARY_NOTEQUAL:
8962 case EXPR_BINARY_EQUAL:
8963 warningf(&expr->base.source_position,
8964 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8972 * Check the semantics of comparison expressions.
8974 * @param expression The expression to check.
8976 static void semantic_comparison(binary_expression_t *expression)
8978 expression_t *left = expression->left;
8979 expression_t *right = expression->right;
8981 if (warning.address) {
8982 warn_string_literal_address(left);
8983 warn_string_literal_address(right);
8985 expression_t const* const func_left = get_reference_address(left);
8986 if (func_left != NULL && is_null_pointer_constant(right)) {
8987 warningf(&expression->base.source_position,
8988 "the address of '%Y' will never be NULL",
8989 func_left->reference.entity->base.symbol);
8992 expression_t const* const func_right = get_reference_address(right);
8993 if (func_right != NULL && is_null_pointer_constant(right)) {
8994 warningf(&expression->base.source_position,
8995 "the address of '%Y' will never be NULL",
8996 func_right->reference.entity->base.symbol);
9000 if (warning.parentheses) {
9001 warn_comparison_in_comparison(left);
9002 warn_comparison_in_comparison(right);
9005 type_t *orig_type_left = left->base.type;
9006 type_t *orig_type_right = right->base.type;
9007 type_t *type_left = skip_typeref(orig_type_left);
9008 type_t *type_right = skip_typeref(orig_type_right);
9010 /* TODO non-arithmetic types */
9011 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9012 /* test for signed vs unsigned compares */
9013 if (warning.sign_compare &&
9014 (expression->base.kind != EXPR_BINARY_EQUAL &&
9015 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
9016 (is_type_signed(type_left) != is_type_signed(type_right))) {
9018 /* check if 1 of the operands is a constant, in this case we just
9019 * check wether we can safely represent the resulting constant in
9020 * the type of the other operand. */
9021 expression_t *const_expr = NULL;
9022 expression_t *other_expr = NULL;
9024 if (is_constant_expression(left)) {
9027 } else if (is_constant_expression(right)) {
9032 if (const_expr != NULL) {
9033 type_t *other_type = skip_typeref(other_expr->base.type);
9034 long val = fold_constant(const_expr);
9035 /* TODO: check if val can be represented by other_type */
9039 warningf(&expression->base.source_position,
9040 "comparison between signed and unsigned");
9042 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9043 expression->left = create_implicit_cast(left, arithmetic_type);
9044 expression->right = create_implicit_cast(right, arithmetic_type);
9045 expression->base.type = arithmetic_type;
9046 if (warning.float_equal &&
9047 (expression->base.kind == EXPR_BINARY_EQUAL ||
9048 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9049 is_type_float(arithmetic_type)) {
9050 warningf(&expression->base.source_position,
9051 "comparing floating point with == or != is unsafe");
9053 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9054 /* TODO check compatibility */
9055 } else if (is_type_pointer(type_left)) {
9056 expression->right = create_implicit_cast(right, type_left);
9057 } else if (is_type_pointer(type_right)) {
9058 expression->left = create_implicit_cast(left, type_right);
9059 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9060 type_error_incompatible("invalid operands in comparison",
9061 &expression->base.source_position,
9062 type_left, type_right);
9064 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9068 * Checks if a compound type has constant fields.
9070 static bool has_const_fields(const compound_type_t *type)
9072 compound_t *compound = type->compound;
9073 entity_t *entry = compound->members.entities;
9075 for (; entry != NULL; entry = entry->base.next) {
9076 if (!is_declaration(entry))
9079 const type_t *decl_type = skip_typeref(entry->declaration.type);
9080 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9087 static bool is_valid_assignment_lhs(expression_t const* const left)
9089 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9090 type_t *const type_left = skip_typeref(orig_type_left);
9092 if (!is_lvalue(left)) {
9093 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9098 if (left->kind == EXPR_REFERENCE
9099 && left->reference.entity->kind == ENTITY_FUNCTION) {
9100 errorf(HERE, "cannot assign to function '%E'", left);
9104 if (is_type_array(type_left)) {
9105 errorf(HERE, "cannot assign to array '%E'", left);
9108 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9109 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9113 if (is_type_incomplete(type_left)) {
9114 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9115 left, orig_type_left);
9118 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9119 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9120 left, orig_type_left);
9127 static void semantic_arithmetic_assign(binary_expression_t *expression)
9129 expression_t *left = expression->left;
9130 expression_t *right = expression->right;
9131 type_t *orig_type_left = left->base.type;
9132 type_t *orig_type_right = right->base.type;
9134 if (!is_valid_assignment_lhs(left))
9137 type_t *type_left = skip_typeref(orig_type_left);
9138 type_t *type_right = skip_typeref(orig_type_right);
9140 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9141 /* TODO: improve error message */
9142 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9143 errorf(&expression->base.source_position,
9144 "operation needs arithmetic types");
9149 /* combined instructions are tricky. We can't create an implicit cast on
9150 * the left side, because we need the uncasted form for the store.
9151 * The ast2firm pass has to know that left_type must be right_type
9152 * for the arithmetic operation and create a cast by itself */
9153 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9154 expression->right = create_implicit_cast(right, arithmetic_type);
9155 expression->base.type = type_left;
9158 static void semantic_divmod_assign(binary_expression_t *expression)
9160 semantic_arithmetic_assign(expression);
9161 warn_div_by_zero(expression);
9164 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9166 expression_t *const left = expression->left;
9167 expression_t *const right = expression->right;
9168 type_t *const orig_type_left = left->base.type;
9169 type_t *const orig_type_right = right->base.type;
9170 type_t *const type_left = skip_typeref(orig_type_left);
9171 type_t *const type_right = skip_typeref(orig_type_right);
9173 if (!is_valid_assignment_lhs(left))
9176 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9177 /* combined instructions are tricky. We can't create an implicit cast on
9178 * the left side, because we need the uncasted form for the store.
9179 * The ast2firm pass has to know that left_type must be right_type
9180 * for the arithmetic operation and create a cast by itself */
9181 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9182 expression->right = create_implicit_cast(right, arithmetic_type);
9183 expression->base.type = type_left;
9184 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9185 check_pointer_arithmetic(&expression->base.source_position,
9186 type_left, orig_type_left);
9187 expression->base.type = type_left;
9188 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9189 errorf(&expression->base.source_position,
9190 "incompatible types '%T' and '%T' in assignment",
9191 orig_type_left, orig_type_right);
9195 static void warn_logical_and_within_or(const expression_t *const expr)
9197 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9199 if (expr->base.parenthesized)
9201 warningf(&expr->base.source_position,
9202 "suggest parentheses around && within ||");
9206 * Check the semantic restrictions of a logical expression.
9208 static void semantic_logical_op(binary_expression_t *expression)
9210 /* §6.5.13:2 Each of the operands shall have scalar type.
9211 * §6.5.14:2 Each of the operands shall have scalar type. */
9212 semantic_condition(expression->left, "left operand of logical operator");
9213 semantic_condition(expression->right, "right operand of logical operator");
9214 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9215 warning.parentheses) {
9216 warn_logical_and_within_or(expression->left);
9217 warn_logical_and_within_or(expression->right);
9219 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9223 * Check the semantic restrictions of a binary assign expression.
9225 static void semantic_binexpr_assign(binary_expression_t *expression)
9227 expression_t *left = expression->left;
9228 type_t *orig_type_left = left->base.type;
9230 if (!is_valid_assignment_lhs(left))
9233 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9234 report_assign_error(error, orig_type_left, expression->right,
9235 "assignment", &left->base.source_position);
9236 expression->right = create_implicit_cast(expression->right, orig_type_left);
9237 expression->base.type = orig_type_left;
9241 * Determine if the outermost operation (or parts thereof) of the given
9242 * expression has no effect in order to generate a warning about this fact.
9243 * Therefore in some cases this only examines some of the operands of the
9244 * expression (see comments in the function and examples below).
9246 * f() + 23; // warning, because + has no effect
9247 * x || f(); // no warning, because x controls execution of f()
9248 * x ? y : f(); // warning, because y has no effect
9249 * (void)x; // no warning to be able to suppress the warning
9250 * This function can NOT be used for an "expression has definitely no effect"-
9252 static bool expression_has_effect(const expression_t *const expr)
9254 switch (expr->kind) {
9255 case EXPR_UNKNOWN: break;
9256 case EXPR_INVALID: return true; /* do NOT warn */
9257 case EXPR_REFERENCE: return false;
9258 case EXPR_REFERENCE_ENUM_VALUE: return false;
9259 /* suppress the warning for microsoft __noop operations */
9260 case EXPR_CONST: return expr->conste.is_ms_noop;
9261 case EXPR_CHARACTER_CONSTANT: return false;
9262 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9263 case EXPR_STRING_LITERAL: return false;
9264 case EXPR_WIDE_STRING_LITERAL: return false;
9265 case EXPR_LABEL_ADDRESS: return false;
9268 const call_expression_t *const call = &expr->call;
9269 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9272 switch (call->function->builtin_symbol.symbol->ID) {
9273 case T___builtin_va_end: return true;
9274 default: return false;
9278 /* Generate the warning if either the left or right hand side of a
9279 * conditional expression has no effect */
9280 case EXPR_CONDITIONAL: {
9281 const conditional_expression_t *const cond = &expr->conditional;
9283 expression_has_effect(cond->true_expression) &&
9284 expression_has_effect(cond->false_expression);
9287 case EXPR_SELECT: return false;
9288 case EXPR_ARRAY_ACCESS: return false;
9289 case EXPR_SIZEOF: return false;
9290 case EXPR_CLASSIFY_TYPE: return false;
9291 case EXPR_ALIGNOF: return false;
9293 case EXPR_FUNCNAME: return false;
9294 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9295 case EXPR_BUILTIN_CONSTANT_P: return false;
9296 case EXPR_BUILTIN_PREFETCH: return true;
9297 case EXPR_OFFSETOF: return false;
9298 case EXPR_VA_START: return true;
9299 case EXPR_VA_ARG: return true;
9300 case EXPR_STATEMENT: return true; // TODO
9301 case EXPR_COMPOUND_LITERAL: return false;
9303 case EXPR_UNARY_NEGATE: return false;
9304 case EXPR_UNARY_PLUS: return false;
9305 case EXPR_UNARY_BITWISE_NEGATE: return false;
9306 case EXPR_UNARY_NOT: return false;
9307 case EXPR_UNARY_DEREFERENCE: return false;
9308 case EXPR_UNARY_TAKE_ADDRESS: return false;
9309 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9310 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9311 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9312 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9314 /* Treat void casts as if they have an effect in order to being able to
9315 * suppress the warning */
9316 case EXPR_UNARY_CAST: {
9317 type_t *const type = skip_typeref(expr->base.type);
9318 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9321 case EXPR_UNARY_CAST_IMPLICIT: return true;
9322 case EXPR_UNARY_ASSUME: return true;
9323 case EXPR_UNARY_DELETE: return true;
9324 case EXPR_UNARY_DELETE_ARRAY: return true;
9325 case EXPR_UNARY_THROW: return true;
9327 case EXPR_BINARY_ADD: return false;
9328 case EXPR_BINARY_SUB: return false;
9329 case EXPR_BINARY_MUL: return false;
9330 case EXPR_BINARY_DIV: return false;
9331 case EXPR_BINARY_MOD: return false;
9332 case EXPR_BINARY_EQUAL: return false;
9333 case EXPR_BINARY_NOTEQUAL: return false;
9334 case EXPR_BINARY_LESS: return false;
9335 case EXPR_BINARY_LESSEQUAL: return false;
9336 case EXPR_BINARY_GREATER: return false;
9337 case EXPR_BINARY_GREATEREQUAL: return false;
9338 case EXPR_BINARY_BITWISE_AND: return false;
9339 case EXPR_BINARY_BITWISE_OR: return false;
9340 case EXPR_BINARY_BITWISE_XOR: return false;
9341 case EXPR_BINARY_SHIFTLEFT: return false;
9342 case EXPR_BINARY_SHIFTRIGHT: return false;
9343 case EXPR_BINARY_ASSIGN: return true;
9344 case EXPR_BINARY_MUL_ASSIGN: return true;
9345 case EXPR_BINARY_DIV_ASSIGN: return true;
9346 case EXPR_BINARY_MOD_ASSIGN: return true;
9347 case EXPR_BINARY_ADD_ASSIGN: return true;
9348 case EXPR_BINARY_SUB_ASSIGN: return true;
9349 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9350 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9351 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9352 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9353 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9355 /* Only examine the right hand side of && and ||, because the left hand
9356 * side already has the effect of controlling the execution of the right
9358 case EXPR_BINARY_LOGICAL_AND:
9359 case EXPR_BINARY_LOGICAL_OR:
9360 /* Only examine the right hand side of a comma expression, because the left
9361 * hand side has a separate warning */
9362 case EXPR_BINARY_COMMA:
9363 return expression_has_effect(expr->binary.right);
9365 case EXPR_BINARY_ISGREATER: return false;
9366 case EXPR_BINARY_ISGREATEREQUAL: return false;
9367 case EXPR_BINARY_ISLESS: return false;
9368 case EXPR_BINARY_ISLESSEQUAL: return false;
9369 case EXPR_BINARY_ISLESSGREATER: return false;
9370 case EXPR_BINARY_ISUNORDERED: return false;
9373 internal_errorf(HERE, "unexpected expression");
9376 static void semantic_comma(binary_expression_t *expression)
9378 if (warning.unused_value) {
9379 const expression_t *const left = expression->left;
9380 if (!expression_has_effect(left)) {
9381 warningf(&left->base.source_position,
9382 "left-hand operand of comma expression has no effect");
9385 expression->base.type = expression->right->base.type;
9389 * @param prec_r precedence of the right operand
9391 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9392 static expression_t *parse_##binexpression_type(expression_t *left) \
9394 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9395 binexpr->binary.left = left; \
9398 expression_t *right = parse_sub_expression(prec_r); \
9400 binexpr->binary.right = right; \
9401 sfunc(&binexpr->binary); \
9406 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9407 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9408 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9409 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9410 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9411 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9412 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9413 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9414 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9415 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9416 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9417 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9418 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9419 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9420 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9421 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9422 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9423 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9424 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9425 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9426 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9427 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9428 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9429 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9430 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9431 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9432 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9433 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9434 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9435 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9438 static expression_t *parse_sub_expression(precedence_t precedence)
9440 if (token.type < 0) {
9441 return expected_expression_error();
9444 expression_parser_function_t *parser
9445 = &expression_parsers[token.type];
9446 source_position_t source_position = token.source_position;
9449 if (parser->parser != NULL) {
9450 left = parser->parser();
9452 left = parse_primary_expression();
9454 assert(left != NULL);
9455 left->base.source_position = source_position;
9458 if (token.type < 0) {
9459 return expected_expression_error();
9462 parser = &expression_parsers[token.type];
9463 if (parser->infix_parser == NULL)
9465 if (parser->infix_precedence < precedence)
9468 left = parser->infix_parser(left);
9470 assert(left != NULL);
9471 assert(left->kind != EXPR_UNKNOWN);
9472 left->base.source_position = source_position;
9479 * Parse an expression.
9481 static expression_t *parse_expression(void)
9483 return parse_sub_expression(PREC_EXPRESSION);
9487 * Register a parser for a prefix-like operator.
9489 * @param parser the parser function
9490 * @param token_type the token type of the prefix token
9492 static void register_expression_parser(parse_expression_function parser,
9495 expression_parser_function_t *entry = &expression_parsers[token_type];
9497 if (entry->parser != NULL) {
9498 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9499 panic("trying to register multiple expression parsers for a token");
9501 entry->parser = parser;
9505 * Register a parser for an infix operator with given precedence.
9507 * @param parser the parser function
9508 * @param token_type the token type of the infix operator
9509 * @param precedence the precedence of the operator
9511 static void register_infix_parser(parse_expression_infix_function parser,
9512 int token_type, unsigned precedence)
9514 expression_parser_function_t *entry = &expression_parsers[token_type];
9516 if (entry->infix_parser != NULL) {
9517 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9518 panic("trying to register multiple infix expression parsers for a "
9521 entry->infix_parser = parser;
9522 entry->infix_precedence = precedence;
9526 * Initialize the expression parsers.
9528 static void init_expression_parsers(void)
9530 memset(&expression_parsers, 0, sizeof(expression_parsers));
9532 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9533 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9534 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9535 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9536 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9537 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9538 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9539 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9540 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9541 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9542 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9543 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9544 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9545 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9546 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9547 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9548 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9549 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9550 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9551 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9552 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9553 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9554 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9555 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9556 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9557 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9558 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9559 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9560 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9561 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9562 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9563 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9564 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9565 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9566 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9567 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9568 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9570 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9571 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9572 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9573 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9574 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9575 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9576 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9577 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9578 register_expression_parser(parse_sizeof, T_sizeof);
9579 register_expression_parser(parse_alignof, T___alignof__);
9580 register_expression_parser(parse_extension, T___extension__);
9581 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9582 register_expression_parser(parse_delete, T_delete);
9583 register_expression_parser(parse_throw, T_throw);
9587 * Parse a asm statement arguments specification.
9589 static asm_argument_t *parse_asm_arguments(bool is_out)
9591 asm_argument_t *result = NULL;
9592 asm_argument_t **anchor = &result;
9594 while (token.type == T_STRING_LITERAL || token.type == '[') {
9595 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9596 memset(argument, 0, sizeof(argument[0]));
9598 if (token.type == '[') {
9600 if (token.type != T_IDENTIFIER) {
9601 parse_error_expected("while parsing asm argument",
9602 T_IDENTIFIER, NULL);
9605 argument->symbol = token.v.symbol;
9607 expect(']', end_error);
9610 argument->constraints = parse_string_literals();
9611 expect('(', end_error);
9612 add_anchor_token(')');
9613 expression_t *expression = parse_expression();
9614 rem_anchor_token(')');
9616 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9617 * change size or type representation (e.g. int -> long is ok, but
9618 * int -> float is not) */
9619 if (expression->kind == EXPR_UNARY_CAST) {
9620 type_t *const type = expression->base.type;
9621 type_kind_t const kind = type->kind;
9622 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9625 if (kind == TYPE_ATOMIC) {
9626 atomic_type_kind_t const akind = type->atomic.akind;
9627 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9628 size = get_atomic_type_size(akind);
9630 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9631 size = get_atomic_type_size(get_intptr_kind());
9635 expression_t *const value = expression->unary.value;
9636 type_t *const value_type = value->base.type;
9637 type_kind_t const value_kind = value_type->kind;
9639 unsigned value_flags;
9640 unsigned value_size;
9641 if (value_kind == TYPE_ATOMIC) {
9642 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9643 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9644 value_size = get_atomic_type_size(value_akind);
9645 } else if (value_kind == TYPE_POINTER) {
9646 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9647 value_size = get_atomic_type_size(get_intptr_kind());
9652 if (value_flags != flags || value_size != size)
9656 } while (expression->kind == EXPR_UNARY_CAST);
9660 if (!is_lvalue(expression)) {
9661 errorf(&expression->base.source_position,
9662 "asm output argument is not an lvalue");
9665 if (argument->constraints.begin[0] == '+')
9666 mark_vars_read(expression, NULL);
9668 mark_vars_read(expression, NULL);
9670 argument->expression = expression;
9671 expect(')', end_error);
9673 set_address_taken(expression, true);
9676 anchor = &argument->next;
9678 if (token.type != ',')
9689 * Parse a asm statement clobber specification.
9691 static asm_clobber_t *parse_asm_clobbers(void)
9693 asm_clobber_t *result = NULL;
9694 asm_clobber_t *last = NULL;
9696 while (token.type == T_STRING_LITERAL) {
9697 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9698 clobber->clobber = parse_string_literals();
9701 last->next = clobber;
9707 if (token.type != ',')
9716 * Parse an asm statement.
9718 static statement_t *parse_asm_statement(void)
9720 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9721 asm_statement_t *asm_statement = &statement->asms;
9725 if (token.type == T_volatile) {
9727 asm_statement->is_volatile = true;
9730 expect('(', end_error);
9731 add_anchor_token(')');
9732 add_anchor_token(':');
9733 asm_statement->asm_text = parse_string_literals();
9735 if (token.type != ':') {
9736 rem_anchor_token(':');
9741 asm_statement->outputs = parse_asm_arguments(true);
9742 if (token.type != ':') {
9743 rem_anchor_token(':');
9748 asm_statement->inputs = parse_asm_arguments(false);
9749 if (token.type != ':') {
9750 rem_anchor_token(':');
9753 rem_anchor_token(':');
9756 asm_statement->clobbers = parse_asm_clobbers();
9759 rem_anchor_token(')');
9760 expect(')', end_error);
9761 expect(';', end_error);
9763 if (asm_statement->outputs == NULL) {
9764 /* GCC: An 'asm' instruction without any output operands will be treated
9765 * identically to a volatile 'asm' instruction. */
9766 asm_statement->is_volatile = true;
9771 return create_invalid_statement();
9775 * Parse a case statement.
9777 static statement_t *parse_case_statement(void)
9779 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9780 source_position_t *const pos = &statement->base.source_position;
9784 expression_t *const expression = parse_expression();
9785 statement->case_label.expression = expression;
9786 if (!is_constant_expression(expression)) {
9787 /* This check does not prevent the error message in all cases of an
9788 * prior error while parsing the expression. At least it catches the
9789 * common case of a mistyped enum entry. */
9790 if (is_type_valid(skip_typeref(expression->base.type))) {
9791 errorf(pos, "case label does not reduce to an integer constant");
9793 statement->case_label.is_bad = true;
9795 long const val = fold_constant(expression);
9796 statement->case_label.first_case = val;
9797 statement->case_label.last_case = val;
9801 if (token.type == T_DOTDOTDOT) {
9803 expression_t *const end_range = parse_expression();
9804 statement->case_label.end_range = end_range;
9805 if (!is_constant_expression(end_range)) {
9806 /* This check does not prevent the error message in all cases of an
9807 * prior error while parsing the expression. At least it catches the
9808 * common case of a mistyped enum entry. */
9809 if (is_type_valid(skip_typeref(end_range->base.type))) {
9810 errorf(pos, "case range does not reduce to an integer constant");
9812 statement->case_label.is_bad = true;
9814 long const val = fold_constant(end_range);
9815 statement->case_label.last_case = val;
9817 if (warning.other && val < statement->case_label.first_case) {
9818 statement->case_label.is_empty_range = true;
9819 warningf(pos, "empty range specified");
9825 PUSH_PARENT(statement);
9827 expect(':', end_error);
9830 if (current_switch != NULL) {
9831 if (! statement->case_label.is_bad) {
9832 /* Check for duplicate case values */
9833 case_label_statement_t *c = &statement->case_label;
9834 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9835 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9838 if (c->last_case < l->first_case || c->first_case > l->last_case)
9841 errorf(pos, "duplicate case value (previously used %P)",
9842 &l->base.source_position);
9846 /* link all cases into the switch statement */
9847 if (current_switch->last_case == NULL) {
9848 current_switch->first_case = &statement->case_label;
9850 current_switch->last_case->next = &statement->case_label;
9852 current_switch->last_case = &statement->case_label;
9854 errorf(pos, "case label not within a switch statement");
9857 statement_t *const inner_stmt = parse_statement();
9858 statement->case_label.statement = inner_stmt;
9859 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9860 errorf(&inner_stmt->base.source_position, "declaration after case label");
9868 * Parse a default statement.
9870 static statement_t *parse_default_statement(void)
9872 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9876 PUSH_PARENT(statement);
9878 expect(':', end_error);
9879 if (current_switch != NULL) {
9880 const case_label_statement_t *def_label = current_switch->default_label;
9881 if (def_label != NULL) {
9882 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9883 &def_label->base.source_position);
9885 current_switch->default_label = &statement->case_label;
9887 /* link all cases into the switch statement */
9888 if (current_switch->last_case == NULL) {
9889 current_switch->first_case = &statement->case_label;
9891 current_switch->last_case->next = &statement->case_label;
9893 current_switch->last_case = &statement->case_label;
9896 errorf(&statement->base.source_position,
9897 "'default' label not within a switch statement");
9900 statement_t *const inner_stmt = parse_statement();
9901 statement->case_label.statement = inner_stmt;
9902 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9903 errorf(&inner_stmt->base.source_position, "declaration after default label");
9910 return create_invalid_statement();
9914 * Parse a label statement.
9916 static statement_t *parse_label_statement(void)
9918 assert(token.type == T_IDENTIFIER);
9919 symbol_t *symbol = token.v.symbol;
9920 label_t *label = get_label(symbol);
9922 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9923 statement->label.label = label;
9927 PUSH_PARENT(statement);
9929 /* if statement is already set then the label is defined twice,
9930 * otherwise it was just mentioned in a goto/local label declaration so far
9932 if (label->statement != NULL) {
9933 errorf(HERE, "duplicate label '%Y' (declared %P)",
9934 symbol, &label->base.source_position);
9936 label->base.source_position = token.source_position;
9937 label->statement = statement;
9942 if (token.type == '}') {
9943 /* TODO only warn? */
9944 if (warning.other && false) {
9945 warningf(HERE, "label at end of compound statement");
9946 statement->label.statement = create_empty_statement();
9948 errorf(HERE, "label at end of compound statement");
9949 statement->label.statement = create_invalid_statement();
9951 } else if (token.type == ';') {
9952 /* Eat an empty statement here, to avoid the warning about an empty
9953 * statement after a label. label:; is commonly used to have a label
9954 * before a closing brace. */
9955 statement->label.statement = create_empty_statement();
9958 statement_t *const inner_stmt = parse_statement();
9959 statement->label.statement = inner_stmt;
9960 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9961 errorf(&inner_stmt->base.source_position, "declaration after label");
9965 /* remember the labels in a list for later checking */
9966 *label_anchor = &statement->label;
9967 label_anchor = &statement->label.next;
9974 * Parse an if statement.
9976 static statement_t *parse_if(void)
9978 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9982 PUSH_PARENT(statement);
9984 add_anchor_token('{');
9986 expect('(', end_error);
9987 add_anchor_token(')');
9988 expression_t *const expr = parse_expression();
9989 statement->ifs.condition = expr;
9990 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9992 semantic_condition(expr, "condition of 'if'-statment");
9993 mark_vars_read(expr, NULL);
9994 rem_anchor_token(')');
9995 expect(')', end_error);
9998 rem_anchor_token('{');
10000 add_anchor_token(T_else);
10001 statement_t *const true_stmt = parse_statement();
10002 statement->ifs.true_statement = true_stmt;
10003 rem_anchor_token(T_else);
10005 if (token.type == T_else) {
10007 statement->ifs.false_statement = parse_statement();
10008 } else if (warning.parentheses &&
10009 true_stmt->kind == STATEMENT_IF &&
10010 true_stmt->ifs.false_statement != NULL) {
10011 warningf(&true_stmt->base.source_position,
10012 "suggest explicit braces to avoid ambiguous 'else'");
10020 * Check that all enums are handled in a switch.
10022 * @param statement the switch statement to check
10024 static void check_enum_cases(const switch_statement_t *statement) {
10025 const type_t *type = skip_typeref(statement->expression->base.type);
10026 if (! is_type_enum(type))
10028 const enum_type_t *enumt = &type->enumt;
10030 /* if we have a default, no warnings */
10031 if (statement->default_label != NULL)
10034 /* FIXME: calculation of value should be done while parsing */
10035 /* TODO: quadratic algorithm here. Change to an n log n one */
10036 long last_value = -1;
10037 const entity_t *entry = enumt->enume->base.next;
10038 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10039 entry = entry->base.next) {
10040 const expression_t *expression = entry->enum_value.value;
10041 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10042 bool found = false;
10043 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10044 if (l->expression == NULL)
10046 if (l->first_case <= value && value <= l->last_case) {
10052 warningf(&statement->base.source_position,
10053 "enumeration value '%Y' not handled in switch",
10054 entry->base.symbol);
10056 last_value = value;
10061 * Parse a switch statement.
10063 static statement_t *parse_switch(void)
10065 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10069 PUSH_PARENT(statement);
10071 expect('(', end_error);
10072 add_anchor_token(')');
10073 expression_t *const expr = parse_expression();
10074 mark_vars_read(expr, NULL);
10075 type_t * type = skip_typeref(expr->base.type);
10076 if (is_type_integer(type)) {
10077 type = promote_integer(type);
10078 if (warning.traditional) {
10079 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10080 warningf(&expr->base.source_position,
10081 "'%T' switch expression not converted to '%T' in ISO C",
10085 } else if (is_type_valid(type)) {
10086 errorf(&expr->base.source_position,
10087 "switch quantity is not an integer, but '%T'", type);
10088 type = type_error_type;
10090 statement->switchs.expression = create_implicit_cast(expr, type);
10091 expect(')', end_error);
10092 rem_anchor_token(')');
10094 switch_statement_t *rem = current_switch;
10095 current_switch = &statement->switchs;
10096 statement->switchs.body = parse_statement();
10097 current_switch = rem;
10099 if (warning.switch_default &&
10100 statement->switchs.default_label == NULL) {
10101 warningf(&statement->base.source_position, "switch has no default case");
10103 if (warning.switch_enum)
10104 check_enum_cases(&statement->switchs);
10110 return create_invalid_statement();
10113 static statement_t *parse_loop_body(statement_t *const loop)
10115 statement_t *const rem = current_loop;
10116 current_loop = loop;
10118 statement_t *const body = parse_statement();
10120 current_loop = rem;
10125 * Parse a while statement.
10127 static statement_t *parse_while(void)
10129 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10133 PUSH_PARENT(statement);
10135 expect('(', end_error);
10136 add_anchor_token(')');
10137 expression_t *const cond = parse_expression();
10138 statement->whiles.condition = cond;
10139 /* §6.8.5:2 The controlling expression of an iteration statement shall
10140 * have scalar type. */
10141 semantic_condition(cond, "condition of 'while'-statement");
10142 mark_vars_read(cond, NULL);
10143 rem_anchor_token(')');
10144 expect(')', end_error);
10146 statement->whiles.body = parse_loop_body(statement);
10152 return create_invalid_statement();
10156 * Parse a do statement.
10158 static statement_t *parse_do(void)
10160 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10164 PUSH_PARENT(statement);
10166 add_anchor_token(T_while);
10167 statement->do_while.body = parse_loop_body(statement);
10168 rem_anchor_token(T_while);
10170 expect(T_while, end_error);
10171 expect('(', end_error);
10172 add_anchor_token(')');
10173 expression_t *const cond = parse_expression();
10174 statement->do_while.condition = cond;
10175 /* §6.8.5:2 The controlling expression of an iteration statement shall
10176 * have scalar type. */
10177 semantic_condition(cond, "condition of 'do-while'-statement");
10178 mark_vars_read(cond, NULL);
10179 rem_anchor_token(')');
10180 expect(')', end_error);
10181 expect(';', end_error);
10187 return create_invalid_statement();
10191 * Parse a for statement.
10193 static statement_t *parse_for(void)
10195 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10199 expect('(', end_error1);
10200 add_anchor_token(')');
10202 PUSH_PARENT(statement);
10204 size_t const top = environment_top();
10205 scope_t *old_scope = scope_push(&statement->fors.scope);
10207 if (token.type == ';') {
10209 } else if (is_declaration_specifier(&token, false)) {
10210 parse_declaration(record_entity, DECL_FLAGS_NONE);
10212 add_anchor_token(';');
10213 expression_t *const init = parse_expression();
10214 statement->fors.initialisation = init;
10215 mark_vars_read(init, ENT_ANY);
10216 if (warning.unused_value && !expression_has_effect(init)) {
10217 warningf(&init->base.source_position,
10218 "initialisation of 'for'-statement has no effect");
10220 rem_anchor_token(';');
10221 expect(';', end_error2);
10224 if (token.type != ';') {
10225 add_anchor_token(';');
10226 expression_t *const cond = parse_expression();
10227 statement->fors.condition = cond;
10228 /* §6.8.5:2 The controlling expression of an iteration statement
10229 * shall have scalar type. */
10230 semantic_condition(cond, "condition of 'for'-statement");
10231 mark_vars_read(cond, NULL);
10232 rem_anchor_token(';');
10234 expect(';', end_error2);
10235 if (token.type != ')') {
10236 expression_t *const step = parse_expression();
10237 statement->fors.step = step;
10238 mark_vars_read(step, ENT_ANY);
10239 if (warning.unused_value && !expression_has_effect(step)) {
10240 warningf(&step->base.source_position,
10241 "step of 'for'-statement has no effect");
10244 expect(')', end_error2);
10245 rem_anchor_token(')');
10246 statement->fors.body = parse_loop_body(statement);
10248 assert(current_scope == &statement->fors.scope);
10249 scope_pop(old_scope);
10250 environment_pop_to(top);
10257 rem_anchor_token(')');
10258 assert(current_scope == &statement->fors.scope);
10259 scope_pop(old_scope);
10260 environment_pop_to(top);
10264 return create_invalid_statement();
10268 * Parse a goto statement.
10270 static statement_t *parse_goto(void)
10272 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10275 if (GNU_MODE && token.type == '*') {
10277 expression_t *expression = parse_expression();
10278 mark_vars_read(expression, NULL);
10280 /* Argh: although documentation says the expression must be of type void*,
10281 * gcc accepts anything that can be casted into void* without error */
10282 type_t *type = expression->base.type;
10284 if (type != type_error_type) {
10285 if (!is_type_pointer(type) && !is_type_integer(type)) {
10286 errorf(&expression->base.source_position,
10287 "cannot convert to a pointer type");
10288 } else if (warning.other && type != type_void_ptr) {
10289 warningf(&expression->base.source_position,
10290 "type of computed goto expression should be 'void*' not '%T'", type);
10292 expression = create_implicit_cast(expression, type_void_ptr);
10295 statement->gotos.expression = expression;
10297 if (token.type != T_IDENTIFIER) {
10299 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10301 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10302 eat_until_anchor();
10305 symbol_t *symbol = token.v.symbol;
10308 statement->gotos.label = get_label(symbol);
10311 /* remember the goto's in a list for later checking */
10312 *goto_anchor = &statement->gotos;
10313 goto_anchor = &statement->gotos.next;
10315 expect(';', end_error);
10319 return create_invalid_statement();
10323 * Parse a continue statement.
10325 static statement_t *parse_continue(void)
10327 if (current_loop == NULL) {
10328 errorf(HERE, "continue statement not within loop");
10331 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10334 expect(';', end_error);
10341 * Parse a break statement.
10343 static statement_t *parse_break(void)
10345 if (current_switch == NULL && current_loop == NULL) {
10346 errorf(HERE, "break statement not within loop or switch");
10349 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10352 expect(';', end_error);
10359 * Parse a __leave statement.
10361 static statement_t *parse_leave_statement(void)
10363 if (current_try == NULL) {
10364 errorf(HERE, "__leave statement not within __try");
10367 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10370 expect(';', end_error);
10377 * Check if a given entity represents a local variable.
10379 static bool is_local_variable(const entity_t *entity)
10381 if (entity->kind != ENTITY_VARIABLE)
10384 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10385 case STORAGE_CLASS_AUTO:
10386 case STORAGE_CLASS_REGISTER: {
10387 const type_t *type = skip_typeref(entity->declaration.type);
10388 if (is_type_function(type)) {
10400 * Check if a given expression represents a local variable.
10402 static bool expression_is_local_variable(const expression_t *expression)
10404 if (expression->base.kind != EXPR_REFERENCE) {
10407 const entity_t *entity = expression->reference.entity;
10408 return is_local_variable(entity);
10412 * Check if a given expression represents a local variable and
10413 * return its declaration then, else return NULL.
10415 entity_t *expression_is_variable(const expression_t *expression)
10417 if (expression->base.kind != EXPR_REFERENCE) {
10420 entity_t *entity = expression->reference.entity;
10421 if (entity->kind != ENTITY_VARIABLE)
10428 * Parse a return statement.
10430 static statement_t *parse_return(void)
10434 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10436 expression_t *return_value = NULL;
10437 if (token.type != ';') {
10438 return_value = parse_expression();
10439 mark_vars_read(return_value, NULL);
10442 const type_t *const func_type = skip_typeref(current_function->base.type);
10443 assert(is_type_function(func_type));
10444 type_t *const return_type = skip_typeref(func_type->function.return_type);
10446 source_position_t const *const pos = &statement->base.source_position;
10447 if (return_value != NULL) {
10448 type_t *return_value_type = skip_typeref(return_value->base.type);
10450 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10451 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10452 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10453 /* Only warn in C mode, because GCC does the same */
10454 if (c_mode & _CXX || strict_mode) {
10456 "'return' with a value, in function returning 'void'");
10457 } else if (warning.other) {
10459 "'return' with a value, in function returning 'void'");
10461 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10462 /* Only warn in C mode, because GCC does the same */
10465 "'return' with expression in function return 'void'");
10466 } else if (warning.other) {
10468 "'return' with expression in function return 'void'");
10472 assign_error_t error = semantic_assign(return_type, return_value);
10473 report_assign_error(error, return_type, return_value, "'return'",
10476 return_value = create_implicit_cast(return_value, return_type);
10477 /* check for returning address of a local var */
10478 if (warning.other && return_value != NULL
10479 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10480 const expression_t *expression = return_value->unary.value;
10481 if (expression_is_local_variable(expression)) {
10482 warningf(pos, "function returns address of local variable");
10485 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10486 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10487 if (c_mode & _CXX || strict_mode) {
10489 "'return' without value, in function returning non-void");
10492 "'return' without value, in function returning non-void");
10495 statement->returns.value = return_value;
10497 expect(';', end_error);
10504 * Parse a declaration statement.
10506 static statement_t *parse_declaration_statement(void)
10508 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10510 entity_t *before = current_scope->last_entity;
10512 parse_external_declaration();
10514 parse_declaration(record_entity, DECL_FLAGS_NONE);
10517 if (before == NULL) {
10518 statement->declaration.declarations_begin = current_scope->entities;
10520 statement->declaration.declarations_begin = before->base.next;
10522 statement->declaration.declarations_end = current_scope->last_entity;
10528 * Parse an expression statement, ie. expr ';'.
10530 static statement_t *parse_expression_statement(void)
10532 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10534 expression_t *const expr = parse_expression();
10535 statement->expression.expression = expr;
10536 mark_vars_read(expr, ENT_ANY);
10538 expect(';', end_error);
10545 * Parse a microsoft __try { } __finally { } or
10546 * __try{ } __except() { }
10548 static statement_t *parse_ms_try_statment(void)
10550 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10553 PUSH_PARENT(statement);
10555 ms_try_statement_t *rem = current_try;
10556 current_try = &statement->ms_try;
10557 statement->ms_try.try_statement = parse_compound_statement(false);
10562 if (token.type == T___except) {
10564 expect('(', end_error);
10565 add_anchor_token(')');
10566 expression_t *const expr = parse_expression();
10567 mark_vars_read(expr, NULL);
10568 type_t * type = skip_typeref(expr->base.type);
10569 if (is_type_integer(type)) {
10570 type = promote_integer(type);
10571 } else if (is_type_valid(type)) {
10572 errorf(&expr->base.source_position,
10573 "__expect expression is not an integer, but '%T'", type);
10574 type = type_error_type;
10576 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10577 rem_anchor_token(')');
10578 expect(')', end_error);
10579 statement->ms_try.final_statement = parse_compound_statement(false);
10580 } else if (token.type == T__finally) {
10582 statement->ms_try.final_statement = parse_compound_statement(false);
10584 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10585 return create_invalid_statement();
10589 return create_invalid_statement();
10592 static statement_t *parse_empty_statement(void)
10594 if (warning.empty_statement) {
10595 warningf(HERE, "statement is empty");
10597 statement_t *const statement = create_empty_statement();
10602 static statement_t *parse_local_label_declaration(void)
10604 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10608 entity_t *begin = NULL, *end = NULL;
10611 if (token.type != T_IDENTIFIER) {
10612 parse_error_expected("while parsing local label declaration",
10613 T_IDENTIFIER, NULL);
10616 symbol_t *symbol = token.v.symbol;
10617 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10618 if (entity != NULL && entity->base.parent_scope == current_scope) {
10619 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10620 symbol, &entity->base.source_position);
10622 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10624 entity->base.parent_scope = current_scope;
10625 entity->base.namespc = NAMESPACE_LABEL;
10626 entity->base.source_position = token.source_position;
10627 entity->base.symbol = symbol;
10630 end->base.next = entity;
10635 environment_push(entity);
10639 if (token.type != ',')
10645 statement->declaration.declarations_begin = begin;
10646 statement->declaration.declarations_end = end;
10650 static void parse_namespace_definition(void)
10654 entity_t *entity = NULL;
10655 symbol_t *symbol = NULL;
10657 if (token.type == T_IDENTIFIER) {
10658 symbol = token.v.symbol;
10661 entity = get_entity(symbol, NAMESPACE_NORMAL);
10662 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10663 && entity->base.parent_scope == current_scope) {
10664 error_redefined_as_different_kind(&token.source_position,
10665 entity, ENTITY_NAMESPACE);
10670 if (entity == NULL) {
10671 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10672 entity->base.symbol = symbol;
10673 entity->base.source_position = token.source_position;
10674 entity->base.namespc = NAMESPACE_NORMAL;
10675 entity->base.parent_scope = current_scope;
10678 if (token.type == '=') {
10679 /* TODO: parse namespace alias */
10680 panic("namespace alias definition not supported yet");
10683 environment_push(entity);
10684 append_entity(current_scope, entity);
10686 size_t const top = environment_top();
10687 scope_t *old_scope = scope_push(&entity->namespacee.members);
10689 expect('{', end_error);
10691 expect('}', end_error);
10694 assert(current_scope == &entity->namespacee.members);
10695 scope_pop(old_scope);
10696 environment_pop_to(top);
10700 * Parse a statement.
10701 * There's also parse_statement() which additionally checks for
10702 * "statement has no effect" warnings
10704 static statement_t *intern_parse_statement(void)
10706 statement_t *statement = NULL;
10708 /* declaration or statement */
10709 add_anchor_token(';');
10710 switch (token.type) {
10711 case T_IDENTIFIER: {
10712 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10713 if (la1_type == ':') {
10714 statement = parse_label_statement();
10715 } else if (is_typedef_symbol(token.v.symbol)) {
10716 statement = parse_declaration_statement();
10718 /* it's an identifier, the grammar says this must be an
10719 * expression statement. However it is common that users mistype
10720 * declaration types, so we guess a bit here to improve robustness
10721 * for incorrect programs */
10722 switch (la1_type) {
10725 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10726 goto expression_statment;
10731 statement = parse_declaration_statement();
10735 expression_statment:
10736 statement = parse_expression_statement();
10743 case T___extension__:
10744 /* This can be a prefix to a declaration or an expression statement.
10745 * We simply eat it now and parse the rest with tail recursion. */
10748 } while (token.type == T___extension__);
10749 bool old_gcc_extension = in_gcc_extension;
10750 in_gcc_extension = true;
10751 statement = intern_parse_statement();
10752 in_gcc_extension = old_gcc_extension;
10756 statement = parse_declaration_statement();
10760 statement = parse_local_label_declaration();
10763 case ';': statement = parse_empty_statement(); break;
10764 case '{': statement = parse_compound_statement(false); break;
10765 case T___leave: statement = parse_leave_statement(); break;
10766 case T___try: statement = parse_ms_try_statment(); break;
10767 case T_asm: statement = parse_asm_statement(); break;
10768 case T_break: statement = parse_break(); break;
10769 case T_case: statement = parse_case_statement(); break;
10770 case T_continue: statement = parse_continue(); break;
10771 case T_default: statement = parse_default_statement(); break;
10772 case T_do: statement = parse_do(); break;
10773 case T_for: statement = parse_for(); break;
10774 case T_goto: statement = parse_goto(); break;
10775 case T_if: statement = parse_if(); break;
10776 case T_return: statement = parse_return(); break;
10777 case T_switch: statement = parse_switch(); break;
10778 case T_while: statement = parse_while(); break;
10781 statement = parse_expression_statement();
10785 errorf(HERE, "unexpected token %K while parsing statement", &token);
10786 statement = create_invalid_statement();
10791 rem_anchor_token(';');
10793 assert(statement != NULL
10794 && statement->base.source_position.input_name != NULL);
10800 * parse a statement and emits "statement has no effect" warning if needed
10801 * (This is really a wrapper around intern_parse_statement with check for 1
10802 * single warning. It is needed, because for statement expressions we have
10803 * to avoid the warning on the last statement)
10805 static statement_t *parse_statement(void)
10807 statement_t *statement = intern_parse_statement();
10809 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10810 expression_t *expression = statement->expression.expression;
10811 if (!expression_has_effect(expression)) {
10812 warningf(&expression->base.source_position,
10813 "statement has no effect");
10821 * Parse a compound statement.
10823 static statement_t *parse_compound_statement(bool inside_expression_statement)
10825 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10827 PUSH_PARENT(statement);
10830 add_anchor_token('}');
10831 /* tokens, which can start a statement */
10832 /* TODO MS, __builtin_FOO */
10833 add_anchor_token('!');
10834 add_anchor_token('&');
10835 add_anchor_token('(');
10836 add_anchor_token('*');
10837 add_anchor_token('+');
10838 add_anchor_token('-');
10839 add_anchor_token('{');
10840 add_anchor_token('~');
10841 add_anchor_token(T_CHARACTER_CONSTANT);
10842 add_anchor_token(T_COLONCOLON);
10843 add_anchor_token(T_FLOATINGPOINT);
10844 add_anchor_token(T_IDENTIFIER);
10845 add_anchor_token(T_INTEGER);
10846 add_anchor_token(T_MINUSMINUS);
10847 add_anchor_token(T_PLUSPLUS);
10848 add_anchor_token(T_STRING_LITERAL);
10849 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10850 add_anchor_token(T_WIDE_STRING_LITERAL);
10851 add_anchor_token(T__Bool);
10852 add_anchor_token(T__Complex);
10853 add_anchor_token(T__Imaginary);
10854 add_anchor_token(T___FUNCTION__);
10855 add_anchor_token(T___PRETTY_FUNCTION__);
10856 add_anchor_token(T___alignof__);
10857 add_anchor_token(T___attribute__);
10858 add_anchor_token(T___builtin_va_start);
10859 add_anchor_token(T___extension__);
10860 add_anchor_token(T___func__);
10861 add_anchor_token(T___imag__);
10862 add_anchor_token(T___label__);
10863 add_anchor_token(T___real__);
10864 add_anchor_token(T___thread);
10865 add_anchor_token(T_asm);
10866 add_anchor_token(T_auto);
10867 add_anchor_token(T_bool);
10868 add_anchor_token(T_break);
10869 add_anchor_token(T_case);
10870 add_anchor_token(T_char);
10871 add_anchor_token(T_class);
10872 add_anchor_token(T_const);
10873 add_anchor_token(T_const_cast);
10874 add_anchor_token(T_continue);
10875 add_anchor_token(T_default);
10876 add_anchor_token(T_delete);
10877 add_anchor_token(T_double);
10878 add_anchor_token(T_do);
10879 add_anchor_token(T_dynamic_cast);
10880 add_anchor_token(T_enum);
10881 add_anchor_token(T_extern);
10882 add_anchor_token(T_false);
10883 add_anchor_token(T_float);
10884 add_anchor_token(T_for);
10885 add_anchor_token(T_goto);
10886 add_anchor_token(T_if);
10887 add_anchor_token(T_inline);
10888 add_anchor_token(T_int);
10889 add_anchor_token(T_long);
10890 add_anchor_token(T_new);
10891 add_anchor_token(T_operator);
10892 add_anchor_token(T_register);
10893 add_anchor_token(T_reinterpret_cast);
10894 add_anchor_token(T_restrict);
10895 add_anchor_token(T_return);
10896 add_anchor_token(T_short);
10897 add_anchor_token(T_signed);
10898 add_anchor_token(T_sizeof);
10899 add_anchor_token(T_static);
10900 add_anchor_token(T_static_cast);
10901 add_anchor_token(T_struct);
10902 add_anchor_token(T_switch);
10903 add_anchor_token(T_template);
10904 add_anchor_token(T_this);
10905 add_anchor_token(T_throw);
10906 add_anchor_token(T_true);
10907 add_anchor_token(T_try);
10908 add_anchor_token(T_typedef);
10909 add_anchor_token(T_typeid);
10910 add_anchor_token(T_typename);
10911 add_anchor_token(T_typeof);
10912 add_anchor_token(T_union);
10913 add_anchor_token(T_unsigned);
10914 add_anchor_token(T_using);
10915 add_anchor_token(T_void);
10916 add_anchor_token(T_volatile);
10917 add_anchor_token(T_wchar_t);
10918 add_anchor_token(T_while);
10920 size_t const top = environment_top();
10921 scope_t *old_scope = scope_push(&statement->compound.scope);
10923 statement_t **anchor = &statement->compound.statements;
10924 bool only_decls_so_far = true;
10925 while (token.type != '}') {
10926 if (token.type == T_EOF) {
10927 errorf(&statement->base.source_position,
10928 "EOF while parsing compound statement");
10931 statement_t *sub_statement = intern_parse_statement();
10932 if (is_invalid_statement(sub_statement)) {
10933 /* an error occurred. if we are at an anchor, return */
10939 if (warning.declaration_after_statement) {
10940 if (sub_statement->kind != STATEMENT_DECLARATION) {
10941 only_decls_so_far = false;
10942 } else if (!only_decls_so_far) {
10943 warningf(&sub_statement->base.source_position,
10944 "ISO C90 forbids mixed declarations and code");
10948 *anchor = sub_statement;
10950 while (sub_statement->base.next != NULL)
10951 sub_statement = sub_statement->base.next;
10953 anchor = &sub_statement->base.next;
10957 /* look over all statements again to produce no effect warnings */
10958 if (warning.unused_value) {
10959 statement_t *sub_statement = statement->compound.statements;
10960 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10961 if (sub_statement->kind != STATEMENT_EXPRESSION)
10963 /* don't emit a warning for the last expression in an expression
10964 * statement as it has always an effect */
10965 if (inside_expression_statement && sub_statement->base.next == NULL)
10968 expression_t *expression = sub_statement->expression.expression;
10969 if (!expression_has_effect(expression)) {
10970 warningf(&expression->base.source_position,
10971 "statement has no effect");
10977 rem_anchor_token(T_while);
10978 rem_anchor_token(T_wchar_t);
10979 rem_anchor_token(T_volatile);
10980 rem_anchor_token(T_void);
10981 rem_anchor_token(T_using);
10982 rem_anchor_token(T_unsigned);
10983 rem_anchor_token(T_union);
10984 rem_anchor_token(T_typeof);
10985 rem_anchor_token(T_typename);
10986 rem_anchor_token(T_typeid);
10987 rem_anchor_token(T_typedef);
10988 rem_anchor_token(T_try);
10989 rem_anchor_token(T_true);
10990 rem_anchor_token(T_throw);
10991 rem_anchor_token(T_this);
10992 rem_anchor_token(T_template);
10993 rem_anchor_token(T_switch);
10994 rem_anchor_token(T_struct);
10995 rem_anchor_token(T_static_cast);
10996 rem_anchor_token(T_static);
10997 rem_anchor_token(T_sizeof);
10998 rem_anchor_token(T_signed);
10999 rem_anchor_token(T_short);
11000 rem_anchor_token(T_return);
11001 rem_anchor_token(T_restrict);
11002 rem_anchor_token(T_reinterpret_cast);
11003 rem_anchor_token(T_register);
11004 rem_anchor_token(T_operator);
11005 rem_anchor_token(T_new);
11006 rem_anchor_token(T_long);
11007 rem_anchor_token(T_int);
11008 rem_anchor_token(T_inline);
11009 rem_anchor_token(T_if);
11010 rem_anchor_token(T_goto);
11011 rem_anchor_token(T_for);
11012 rem_anchor_token(T_float);
11013 rem_anchor_token(T_false);
11014 rem_anchor_token(T_extern);
11015 rem_anchor_token(T_enum);
11016 rem_anchor_token(T_dynamic_cast);
11017 rem_anchor_token(T_do);
11018 rem_anchor_token(T_double);
11019 rem_anchor_token(T_delete);
11020 rem_anchor_token(T_default);
11021 rem_anchor_token(T_continue);
11022 rem_anchor_token(T_const_cast);
11023 rem_anchor_token(T_const);
11024 rem_anchor_token(T_class);
11025 rem_anchor_token(T_char);
11026 rem_anchor_token(T_case);
11027 rem_anchor_token(T_break);
11028 rem_anchor_token(T_bool);
11029 rem_anchor_token(T_auto);
11030 rem_anchor_token(T_asm);
11031 rem_anchor_token(T___thread);
11032 rem_anchor_token(T___real__);
11033 rem_anchor_token(T___label__);
11034 rem_anchor_token(T___imag__);
11035 rem_anchor_token(T___func__);
11036 rem_anchor_token(T___extension__);
11037 rem_anchor_token(T___builtin_va_start);
11038 rem_anchor_token(T___attribute__);
11039 rem_anchor_token(T___alignof__);
11040 rem_anchor_token(T___PRETTY_FUNCTION__);
11041 rem_anchor_token(T___FUNCTION__);
11042 rem_anchor_token(T__Imaginary);
11043 rem_anchor_token(T__Complex);
11044 rem_anchor_token(T__Bool);
11045 rem_anchor_token(T_WIDE_STRING_LITERAL);
11046 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11047 rem_anchor_token(T_STRING_LITERAL);
11048 rem_anchor_token(T_PLUSPLUS);
11049 rem_anchor_token(T_MINUSMINUS);
11050 rem_anchor_token(T_INTEGER);
11051 rem_anchor_token(T_IDENTIFIER);
11052 rem_anchor_token(T_FLOATINGPOINT);
11053 rem_anchor_token(T_COLONCOLON);
11054 rem_anchor_token(T_CHARACTER_CONSTANT);
11055 rem_anchor_token('~');
11056 rem_anchor_token('{');
11057 rem_anchor_token('-');
11058 rem_anchor_token('+');
11059 rem_anchor_token('*');
11060 rem_anchor_token('(');
11061 rem_anchor_token('&');
11062 rem_anchor_token('!');
11063 rem_anchor_token('}');
11064 assert(current_scope == &statement->compound.scope);
11065 scope_pop(old_scope);
11066 environment_pop_to(top);
11073 * Check for unused global static functions and variables
11075 static void check_unused_globals(void)
11077 if (!warning.unused_function && !warning.unused_variable)
11080 for (const entity_t *entity = file_scope->entities; entity != NULL;
11081 entity = entity->base.next) {
11082 if (!is_declaration(entity))
11085 const declaration_t *declaration = &entity->declaration;
11086 if (declaration->used ||
11087 declaration->modifiers & DM_UNUSED ||
11088 declaration->modifiers & DM_USED ||
11089 declaration->storage_class != STORAGE_CLASS_STATIC)
11092 type_t *const type = declaration->type;
11094 if (entity->kind == ENTITY_FUNCTION) {
11095 /* inhibit warning for static inline functions */
11096 if (entity->function.is_inline)
11099 s = entity->function.statement != NULL ? "defined" : "declared";
11104 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11105 type, declaration->base.symbol, s);
11109 static void parse_global_asm(void)
11111 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11114 expect('(', end_error);
11116 statement->asms.asm_text = parse_string_literals();
11117 statement->base.next = unit->global_asm;
11118 unit->global_asm = statement;
11120 expect(')', end_error);
11121 expect(';', end_error);
11126 static void parse_linkage_specification(void)
11129 assert(token.type == T_STRING_LITERAL);
11131 const char *linkage = parse_string_literals().begin;
11133 linkage_kind_t old_linkage = current_linkage;
11134 linkage_kind_t new_linkage;
11135 if (strcmp(linkage, "C") == 0) {
11136 new_linkage = LINKAGE_C;
11137 } else if (strcmp(linkage, "C++") == 0) {
11138 new_linkage = LINKAGE_CXX;
11140 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11141 new_linkage = LINKAGE_INVALID;
11143 current_linkage = new_linkage;
11145 if (token.type == '{') {
11148 expect('}', end_error);
11154 assert(current_linkage == new_linkage);
11155 current_linkage = old_linkage;
11158 static void parse_external(void)
11160 switch (token.type) {
11161 DECLARATION_START_NO_EXTERN
11163 case T___extension__:
11164 /* tokens below are for implicit int */
11165 case '&': /* & x; -> int& x; (and error later, because C++ has no
11167 case '*': /* * x; -> int* x; */
11168 case '(': /* (x); -> int (x); */
11169 parse_external_declaration();
11173 if (look_ahead(1)->type == T_STRING_LITERAL) {
11174 parse_linkage_specification();
11176 parse_external_declaration();
11181 parse_global_asm();
11185 parse_namespace_definition();
11189 if (!strict_mode) {
11191 warningf(HERE, "stray ';' outside of function");
11198 errorf(HERE, "stray %K outside of function", &token);
11199 if (token.type == '(' || token.type == '{' || token.type == '[')
11200 eat_until_matching_token(token.type);
11206 static void parse_externals(void)
11208 add_anchor_token('}');
11209 add_anchor_token(T_EOF);
11212 unsigned char token_anchor_copy[T_LAST_TOKEN];
11213 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11216 while (token.type != T_EOF && token.type != '}') {
11218 bool anchor_leak = false;
11219 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11220 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11222 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11223 anchor_leak = true;
11226 if (in_gcc_extension) {
11227 errorf(HERE, "Leaked __extension__");
11228 anchor_leak = true;
11238 rem_anchor_token(T_EOF);
11239 rem_anchor_token('}');
11243 * Parse a translation unit.
11245 static void parse_translation_unit(void)
11247 add_anchor_token(T_EOF);
11252 if (token.type == T_EOF)
11255 errorf(HERE, "stray %K outside of function", &token);
11256 if (token.type == '(' || token.type == '{' || token.type == '[')
11257 eat_until_matching_token(token.type);
11265 * @return the translation unit or NULL if errors occurred.
11267 void start_parsing(void)
11269 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11270 label_stack = NEW_ARR_F(stack_entry_t, 0);
11271 diagnostic_count = 0;
11275 type_set_output(stderr);
11276 ast_set_output(stderr);
11278 assert(unit == NULL);
11279 unit = allocate_ast_zero(sizeof(unit[0]));
11281 assert(file_scope == NULL);
11282 file_scope = &unit->scope;
11284 assert(current_scope == NULL);
11285 scope_push(&unit->scope);
11288 translation_unit_t *finish_parsing(void)
11290 assert(current_scope == &unit->scope);
11293 assert(file_scope == &unit->scope);
11294 check_unused_globals();
11297 DEL_ARR_F(environment_stack);
11298 DEL_ARR_F(label_stack);
11300 translation_unit_t *result = unit;
11305 /* GCC allows global arrays without size and assigns them a length of one,
11306 * if no different declaration follows */
11307 static void complete_incomplete_arrays(void)
11309 size_t n = ARR_LEN(incomplete_arrays);
11310 for (size_t i = 0; i != n; ++i) {
11311 declaration_t *const decl = incomplete_arrays[i];
11312 type_t *const orig_type = decl->type;
11313 type_t *const type = skip_typeref(orig_type);
11315 if (!is_type_incomplete(type))
11318 if (warning.other) {
11319 warningf(&decl->base.source_position,
11320 "array '%#T' assumed to have one element",
11321 orig_type, decl->base.symbol);
11324 type_t *const new_type = duplicate_type(type);
11325 new_type->array.size_constant = true;
11326 new_type->array.has_implicit_size = true;
11327 new_type->array.size = 1;
11329 type_t *const result = typehash_insert(new_type);
11330 if (type != result)
11333 decl->type = result;
11339 lookahead_bufpos = 0;
11340 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11343 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11344 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11345 parse_translation_unit();
11346 complete_incomplete_arrays();
11347 DEL_ARR_F(incomplete_arrays);
11348 incomplete_arrays = NULL;
11352 * Initialize the parser.
11354 void init_parser(void)
11356 sym_anonymous = symbol_table_insert("<anonymous>");
11358 if (c_mode & _MS) {
11359 /* add predefined symbols for extended-decl-modifier */
11360 sym_align = symbol_table_insert("align");
11361 sym_allocate = symbol_table_insert("allocate");
11362 sym_dllimport = symbol_table_insert("dllimport");
11363 sym_dllexport = symbol_table_insert("dllexport");
11364 sym_naked = symbol_table_insert("naked");
11365 sym_noinline = symbol_table_insert("noinline");
11366 sym_noreturn = symbol_table_insert("noreturn");
11367 sym_nothrow = symbol_table_insert("nothrow");
11368 sym_novtable = symbol_table_insert("novtable");
11369 sym_property = symbol_table_insert("property");
11370 sym_get = symbol_table_insert("get");
11371 sym_put = symbol_table_insert("put");
11372 sym_selectany = symbol_table_insert("selectany");
11373 sym_thread = symbol_table_insert("thread");
11374 sym_uuid = symbol_table_insert("uuid");
11375 sym_deprecated = symbol_table_insert("deprecated");
11376 sym_restrict = symbol_table_insert("restrict");
11377 sym_noalias = symbol_table_insert("noalias");
11379 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11381 init_expression_parsers();
11382 obstack_init(&temp_obst);
11384 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11385 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11389 * Terminate the parser.
11391 void exit_parser(void)
11393 obstack_free(&temp_obst, NULL);