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
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. */
81 decl_modifiers_t modifiers; /**< declaration modifiers */
82 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
83 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
84 symbol_t *get_property_sym; /**< the name of the get property if set. */
85 symbol_t *put_property_sym; /**< the name of the put property if set. */
90 * An environment for parsing initializers (and compound literals).
92 typedef struct parse_initializer_env_t {
93 type_t *type; /**< the type of the initializer. In case of an
94 array type with unspecified size this gets
95 adjusted to the actual size. */
96 entity_t *entity; /**< the variable that is initialized if any */
97 bool must_be_constant;
98 } parse_initializer_env_t;
100 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
102 /** The current token. */
103 static token_t token;
104 /** The lookahead ring-buffer. */
105 static token_t lookahead_buffer[MAX_LOOKAHEAD];
106 /** Position of the next token in the lookahead buffer. */
107 static int lookahead_bufpos;
108 static stack_entry_t *environment_stack = NULL;
109 static stack_entry_t *label_stack = NULL;
110 /** The global file scope. */
111 static scope_t *file_scope = NULL;
112 /** The current scope. */
113 static scope_t *scope = NULL;
114 /** Point to the current function declaration if inside a function. */
115 static function_t *current_function = NULL;
116 static entity_t *current_init_decl = NULL;
117 static switch_statement_t *current_switch = NULL;
118 static statement_t *current_loop = NULL;
119 static statement_t *current_parent = NULL;
120 static ms_try_statement_t *current_try = NULL;
121 static goto_statement_t *goto_first = NULL;
122 static goto_statement_t *goto_last = NULL;
123 static label_statement_t *label_first = NULL;
124 static label_statement_t *label_last = NULL;
125 /** current translation unit. */
126 static translation_unit_t *unit = NULL;
127 /** true if we are in a type property context (evaluation only for type. */
128 static bool in_type_prop = false;
129 /** true in we are in a __extension__ context. */
130 static bool in_gcc_extension = false;
131 static struct obstack temp_obst;
134 #define PUSH_PARENT(stmt) \
135 statement_t *const prev_parent = current_parent; \
136 ((void)(current_parent = (stmt)))
137 #define POP_PARENT ((void)(current_parent = prev_parent))
139 /** special symbol used for anonymous entities. */
140 static const symbol_t *sym_anonymous = NULL;
142 /* symbols for Microsoft extended-decl-modifier */
143 static const symbol_t *sym_align = NULL;
144 static const symbol_t *sym_allocate = NULL;
145 static const symbol_t *sym_dllimport = NULL;
146 static const symbol_t *sym_dllexport = NULL;
147 static const symbol_t *sym_naked = NULL;
148 static const symbol_t *sym_noinline = NULL;
149 static const symbol_t *sym_noreturn = NULL;
150 static const symbol_t *sym_nothrow = NULL;
151 static const symbol_t *sym_novtable = NULL;
152 static const symbol_t *sym_property = NULL;
153 static const symbol_t *sym_get = NULL;
154 static const symbol_t *sym_put = NULL;
155 static const symbol_t *sym_selectany = NULL;
156 static const symbol_t *sym_thread = NULL;
157 static const symbol_t *sym_uuid = NULL;
158 static const symbol_t *sym_deprecated = NULL;
159 static const symbol_t *sym_restrict = NULL;
160 static const symbol_t *sym_noalias = NULL;
162 /** The token anchor set */
163 static unsigned char token_anchor_set[T_LAST_TOKEN];
165 /** The current source position. */
166 #define HERE (&token.source_position)
168 /** true if we are in GCC mode. */
169 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
171 static type_t *type_valist;
173 static statement_t *parse_compound_statement(bool inside_expression_statement);
174 static statement_t *parse_statement(void);
176 static expression_t *parse_sub_expression(precedence_t);
177 static expression_t *parse_expression(void);
178 static type_t *parse_typename(void);
180 static void parse_compound_type_entries(compound_t *compound_declaration);
181 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
182 bool may_be_abstract,
183 bool create_compound_member);
184 static entity_t *record_entity(entity_t *entity, bool is_definition);
186 static void semantic_comparison(binary_expression_t *expression);
188 #define STORAGE_CLASSES \
196 #define TYPE_QUALIFIERS \
201 case T__forceinline: \
202 case T___attribute__:
204 #define COMPLEX_SPECIFIERS \
206 #define IMAGINARY_SPECIFIERS \
209 #define TYPE_SPECIFIERS \
211 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define TYPENAME_START \
239 #define EXPRESSION_START \
248 case T_CHARACTER_CONSTANT: \
249 case T_FLOATINGPOINT: \
253 case T_STRING_LITERAL: \
254 case T_WIDE_CHARACTER_CONSTANT: \
255 case T_WIDE_STRING_LITERAL: \
256 case T___FUNCDNAME__: \
257 case T___FUNCSIG__: \
258 case T___FUNCTION__: \
259 case T___PRETTY_FUNCTION__: \
260 case T___alignof__: \
261 case T___builtin_alloca: \
262 case T___builtin_classify_type: \
263 case T___builtin_constant_p: \
264 case T___builtin_expect: \
265 case T___builtin_huge_val: \
266 case T___builtin_inf: \
267 case T___builtin_inff: \
268 case T___builtin_infl: \
269 case T___builtin_isgreater: \
270 case T___builtin_isgreaterequal: \
271 case T___builtin_isless: \
272 case T___builtin_islessequal: \
273 case T___builtin_islessgreater: \
274 case T___builtin_isunordered: \
275 case T___builtin_nan: \
276 case T___builtin_nanf: \
277 case T___builtin_nanl: \
278 case T___builtin_offsetof: \
279 case T___builtin_prefetch: \
280 case T___builtin_va_arg: \
281 case T___builtin_va_end: \
282 case T___builtin_va_start: \
293 * Allocate an AST node with given size and
294 * initialize all fields with zero.
296 static void *allocate_ast_zero(size_t size)
298 void *res = allocate_ast(size);
299 memset(res, 0, size);
303 static size_t get_entity_struct_size(entity_kind_t kind)
305 static const size_t sizes[] = {
306 [ENTITY_VARIABLE] = sizeof(variable_t),
307 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
308 [ENTITY_FUNCTION] = sizeof(function_t),
309 [ENTITY_TYPEDEF] = sizeof(typedef_t),
310 [ENTITY_STRUCT] = sizeof(compound_t),
311 [ENTITY_UNION] = sizeof(compound_t),
312 [ENTITY_ENUM] = sizeof(enum_t),
313 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
314 [ENTITY_LABEL] = sizeof(label_t),
315 [ENTITY_LOCAL_LABEL] = sizeof(label_t)
317 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
318 assert(sizes[kind] != 0);
322 static entity_t *allocate_entity_zero(entity_kind_t kind)
324 size_t size = get_entity_struct_size(kind);
325 entity_t *entity = allocate_ast_zero(size);
331 * Returns the size of a statement node.
333 * @param kind the statement kind
335 static size_t get_statement_struct_size(statement_kind_t kind)
337 static const size_t sizes[] = {
338 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
339 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
340 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
341 [STATEMENT_RETURN] = sizeof(return_statement_t),
342 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
343 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
344 [STATEMENT_IF] = sizeof(if_statement_t),
345 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
346 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
347 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
348 [STATEMENT_BREAK] = sizeof(statement_base_t),
349 [STATEMENT_GOTO] = sizeof(goto_statement_t),
350 [STATEMENT_LABEL] = sizeof(label_statement_t),
351 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
352 [STATEMENT_WHILE] = sizeof(while_statement_t),
353 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
354 [STATEMENT_FOR] = sizeof(for_statement_t),
355 [STATEMENT_ASM] = sizeof(asm_statement_t),
356 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
357 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
359 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
360 assert(sizes[kind] != 0);
365 * Returns the size of an expression node.
367 * @param kind the expression kind
369 static size_t get_expression_struct_size(expression_kind_t kind)
371 static const size_t sizes[] = {
372 [EXPR_INVALID] = sizeof(expression_base_t),
373 [EXPR_REFERENCE] = sizeof(reference_expression_t),
374 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
375 [EXPR_CONST] = sizeof(const_expression_t),
376 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
377 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
378 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
379 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
380 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
381 [EXPR_CALL] = sizeof(call_expression_t),
382 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
383 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
384 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
385 [EXPR_SELECT] = sizeof(select_expression_t),
386 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
387 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
388 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
389 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
390 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
391 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
392 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
393 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
394 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
395 [EXPR_VA_START] = sizeof(va_start_expression_t),
396 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
397 [EXPR_STATEMENT] = sizeof(statement_expression_t),
398 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
400 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
401 return sizes[EXPR_UNARY_FIRST];
403 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
404 return sizes[EXPR_BINARY_FIRST];
406 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
407 assert(sizes[kind] != 0);
412 * Allocate a statement node of given kind and initialize all
415 static statement_t *allocate_statement_zero(statement_kind_t kind)
417 size_t size = get_statement_struct_size(kind);
418 statement_t *res = allocate_ast_zero(size);
420 res->base.kind = kind;
421 res->base.parent = current_parent;
422 res->base.source_position = token.source_position;
427 * Allocate an expression node of given kind and initialize all
430 static expression_t *allocate_expression_zero(expression_kind_t kind)
432 size_t size = get_expression_struct_size(kind);
433 expression_t *res = allocate_ast_zero(size);
435 res->base.kind = kind;
436 res->base.type = type_error_type;
437 res->base.source_position = token.source_position;
442 * Creates a new invalid expression.
444 static expression_t *create_invalid_expression(void)
446 return allocate_expression_zero(EXPR_INVALID);
450 * Creates a new invalid statement.
452 static statement_t *create_invalid_statement(void)
454 return allocate_statement_zero(STATEMENT_INVALID);
458 * Allocate a new empty statement.
460 static statement_t *create_empty_statement(void)
462 return allocate_statement_zero(STATEMENT_EMPTY);
466 * Returns the size of a type node.
468 * @param kind the type kind
470 static size_t get_type_struct_size(type_kind_t kind)
472 static const size_t sizes[] = {
473 [TYPE_ATOMIC] = sizeof(atomic_type_t),
474 [TYPE_COMPLEX] = sizeof(complex_type_t),
475 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
476 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
477 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
478 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
479 [TYPE_ENUM] = sizeof(enum_type_t),
480 [TYPE_FUNCTION] = sizeof(function_type_t),
481 [TYPE_POINTER] = sizeof(pointer_type_t),
482 [TYPE_ARRAY] = sizeof(array_type_t),
483 [TYPE_BUILTIN] = sizeof(builtin_type_t),
484 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
485 [TYPE_TYPEOF] = sizeof(typeof_type_t),
487 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
488 assert(kind <= TYPE_TYPEOF);
489 assert(sizes[kind] != 0);
494 * Allocate a type node of given kind and initialize all
497 * @param kind type kind to allocate
499 static type_t *allocate_type_zero(type_kind_t kind)
501 size_t size = get_type_struct_size(kind);
502 type_t *res = obstack_alloc(type_obst, size);
503 memset(res, 0, size);
504 res->base.kind = kind;
510 * Returns the size of an initializer node.
512 * @param kind the initializer kind
514 static size_t get_initializer_size(initializer_kind_t kind)
516 static const size_t sizes[] = {
517 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
518 [INITIALIZER_STRING] = sizeof(initializer_string_t),
519 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
520 [INITIALIZER_LIST] = sizeof(initializer_list_t),
521 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
523 assert(kind < sizeof(sizes) / sizeof(*sizes));
524 assert(sizes[kind] != 0);
529 * Allocate an initializer node of given kind and initialize all
532 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
534 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
541 * Free a type from the type obstack.
543 static void free_type(void *type)
545 obstack_free(type_obst, type);
549 * Returns the index of the top element of the environment stack.
551 static size_t environment_top(void)
553 return ARR_LEN(environment_stack);
557 * Returns the index of the top element of the global label stack.
559 static size_t label_top(void)
561 return ARR_LEN(label_stack);
565 * Return the next token.
567 static inline void next_token(void)
569 token = lookahead_buffer[lookahead_bufpos];
570 lookahead_buffer[lookahead_bufpos] = lexer_token;
573 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
576 print_token(stderr, &token);
577 fprintf(stderr, "\n");
582 * Return the next token with a given lookahead.
584 static inline const token_t *look_ahead(int num)
586 assert(num > 0 && num <= MAX_LOOKAHEAD);
587 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
588 return &lookahead_buffer[pos];
592 * Adds a token to the token anchor set (a multi-set).
594 static void add_anchor_token(int token_type)
596 assert(0 <= token_type && token_type < T_LAST_TOKEN);
597 ++token_anchor_set[token_type];
600 static int save_and_reset_anchor_state(int token_type)
602 assert(0 <= token_type && token_type < T_LAST_TOKEN);
603 int count = token_anchor_set[token_type];
604 token_anchor_set[token_type] = 0;
608 static void restore_anchor_state(int token_type, int count)
610 assert(0 <= token_type && token_type < T_LAST_TOKEN);
611 token_anchor_set[token_type] = count;
615 * Remove a token from the token anchor set (a multi-set).
617 static void rem_anchor_token(int token_type)
619 assert(0 <= token_type && token_type < T_LAST_TOKEN);
620 assert(token_anchor_set[token_type] != 0);
621 --token_anchor_set[token_type];
624 static bool at_anchor(void)
628 return token_anchor_set[token.type];
632 * Eat tokens until a matching token is found.
634 static void eat_until_matching_token(int type)
638 case '(': end_token = ')'; break;
639 case '{': end_token = '}'; break;
640 case '[': end_token = ']'; break;
641 default: end_token = type; break;
644 unsigned parenthesis_count = 0;
645 unsigned brace_count = 0;
646 unsigned bracket_count = 0;
647 while (token.type != end_token ||
648 parenthesis_count != 0 ||
650 bracket_count != 0) {
651 switch (token.type) {
653 case '(': ++parenthesis_count; break;
654 case '{': ++brace_count; break;
655 case '[': ++bracket_count; break;
658 if (parenthesis_count > 0)
668 if (bracket_count > 0)
671 if (token.type == end_token &&
672 parenthesis_count == 0 &&
686 * Eat input tokens until an anchor is found.
688 static void eat_until_anchor(void)
690 while (token_anchor_set[token.type] == 0) {
691 if (token.type == '(' || token.type == '{' || token.type == '[')
692 eat_until_matching_token(token.type);
697 static void eat_block(void)
699 eat_until_matching_token('{');
700 if (token.type == '}')
704 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
707 * Report a parse error because an expected token was not found.
710 #if defined __GNUC__ && __GNUC__ >= 4
711 __attribute__((sentinel))
713 void parse_error_expected(const char *message, ...)
715 if (message != NULL) {
716 errorf(HERE, "%s", message);
719 va_start(ap, message);
720 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
725 * Report a type error.
727 static void type_error(const char *msg, const source_position_t *source_position,
730 errorf(source_position, "%s, but found type '%T'", msg, type);
734 * Report an incompatible type.
736 static void type_error_incompatible(const char *msg,
737 const source_position_t *source_position, type_t *type1, type_t *type2)
739 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
744 * Expect the the current token is the expected token.
745 * If not, generate an error, eat the current statement,
746 * and goto the end_error label.
748 #define expect(expected) \
750 if (UNLIKELY(token.type != (expected))) { \
751 parse_error_expected(NULL, (expected), NULL); \
752 add_anchor_token(expected); \
753 eat_until_anchor(); \
754 if (token.type == expected) \
756 rem_anchor_token(expected); \
762 static void scope_push(scope_t *new_scope)
765 new_scope->depth = scope->depth + 1;
767 new_scope->parent = scope;
771 static void scope_pop(void)
773 scope = scope->parent;
777 * Search an entity by its symbol in a given namespace.
779 static entity_t *get_entity(const symbol_t *const symbol, namespace_t namespc)
781 entity_t *entity = symbol->entity;
782 for( ; entity != NULL; entity = entity->base.symbol_next) {
783 if (entity->base.namespc == namespc)
791 * pushs an entity on the environment stack and links the corresponding symbol
794 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
796 symbol_t *symbol = entity->base.symbol;
797 namespace_t namespc = entity->base.namespc;
798 assert(namespc != NAMESPACE_INVALID);
800 /* replace/add entity into entity list of the symbol */
803 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
808 /* replace an entry? */
809 if (iter->base.namespc == namespc) {
810 entity->base.symbol_next = iter->base.symbol_next;
816 /* remember old declaration */
818 entry.symbol = symbol;
819 entry.old_entity = iter;
820 entry.namespc = namespc;
821 ARR_APP1(stack_entry_t, *stack_ptr, entry);
825 * Push an entity on the environment stack.
827 static void environment_push(entity_t *entity)
829 assert(entity->base.source_position.input_name != NULL);
830 assert(entity->base.parent_scope != NULL);
831 stack_push(&environment_stack, entity);
835 * Push a declaration on the global label stack.
837 * @param declaration the declaration
839 static void label_push(entity_t *label)
841 /* we abuse the parameters scope as parent for the labels */
842 label->base.parent_scope = ¤t_function->parameters;
843 stack_push(&label_stack, label);
847 * pops symbols from the environment stack until @p new_top is the top element
849 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
851 stack_entry_t *stack = *stack_ptr;
852 size_t top = ARR_LEN(stack);
855 assert(new_top <= top);
859 for(i = top; i > new_top; --i) {
860 stack_entry_t *entry = &stack[i - 1];
862 entity_t *old_entity = entry->old_entity;
863 symbol_t *symbol = entry->symbol;
864 namespace_t namespc = entry->namespc;
866 /* replace with old_entity/remove */
869 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
871 assert(iter != NULL);
872 /* replace an entry? */
873 if (iter->base.namespc == namespc)
877 /* restore definition from outer scopes (if there was one) */
878 if (old_entity != NULL) {
879 old_entity->base.symbol_next = iter->base.symbol_next;
880 *anchor = old_entity;
882 /* remove entry from list */
883 *anchor = iter->base.symbol_next;
887 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
891 * Pop all entries from the environment stack until the new_top
894 * @param new_top the new stack top
896 static void environment_pop_to(size_t new_top)
898 stack_pop_to(&environment_stack, new_top);
902 * Pop all entries from the global label stack until the new_top
905 * @param new_top the new stack top
907 static void label_pop_to(size_t new_top)
909 stack_pop_to(&label_stack, new_top);
912 static int get_akind_rank(atomic_type_kind_t akind)
917 static int get_rank(const type_t *type)
919 assert(!is_typeref(type));
920 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
921 * and esp. footnote 108). However we can't fold constants (yet), so we
922 * can't decide whether unsigned int is possible, while int always works.
923 * (unsigned int would be preferable when possible... for stuff like
924 * struct { enum { ... } bla : 4; } ) */
925 if (type->kind == TYPE_ENUM)
926 return get_akind_rank(ATOMIC_TYPE_INT);
928 assert(type->kind == TYPE_ATOMIC);
929 return get_akind_rank(type->atomic.akind);
932 static type_t *promote_integer(type_t *type)
934 if (type->kind == TYPE_BITFIELD)
935 type = type->bitfield.base_type;
937 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
944 * Create a cast expression.
946 * @param expression the expression to cast
947 * @param dest_type the destination type
949 static expression_t *create_cast_expression(expression_t *expression,
952 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
954 cast->unary.value = expression;
955 cast->base.type = dest_type;
961 * Check if a given expression represents the 0 pointer constant.
963 static bool is_null_pointer_constant(const expression_t *expression)
965 /* skip void* cast */
966 if (expression->kind == EXPR_UNARY_CAST
967 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
968 expression = expression->unary.value;
971 /* TODO: not correct yet, should be any constant integer expression
972 * which evaluates to 0 */
973 if (expression->kind != EXPR_CONST)
976 type_t *const type = skip_typeref(expression->base.type);
977 if (!is_type_integer(type))
980 return expression->conste.v.int_value == 0;
984 * Create an implicit cast expression.
986 * @param expression the expression to cast
987 * @param dest_type the destination type
989 static expression_t *create_implicit_cast(expression_t *expression,
992 type_t *const source_type = expression->base.type;
994 if (source_type == dest_type)
997 return create_cast_expression(expression, dest_type);
1000 typedef enum assign_error_t {
1002 ASSIGN_ERROR_INCOMPATIBLE,
1003 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1004 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1005 ASSIGN_WARNING_POINTER_FROM_INT,
1006 ASSIGN_WARNING_INT_FROM_POINTER
1009 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1010 const expression_t *const right,
1011 const char *context,
1012 const source_position_t *source_position)
1014 type_t *const orig_type_right = right->base.type;
1015 type_t *const type_left = skip_typeref(orig_type_left);
1016 type_t *const type_right = skip_typeref(orig_type_right);
1019 case ASSIGN_SUCCESS:
1021 case ASSIGN_ERROR_INCOMPATIBLE:
1022 errorf(source_position,
1023 "destination type '%T' in %s is incompatible with type '%T'",
1024 orig_type_left, context, orig_type_right);
1027 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1028 if (warning.other) {
1029 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1030 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1032 /* the left type has all qualifiers from the right type */
1033 unsigned missing_qualifiers
1034 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1035 warningf(source_position,
1036 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1037 orig_type_left, context, orig_type_right, missing_qualifiers);
1042 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1043 if (warning.other) {
1044 warningf(source_position,
1045 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1046 orig_type_left, context, right, orig_type_right);
1050 case ASSIGN_WARNING_POINTER_FROM_INT:
1051 if (warning.other) {
1052 warningf(source_position,
1053 "%s makes pointer '%T' from integer '%T' without a cast",
1054 context, orig_type_left, orig_type_right);
1058 case ASSIGN_WARNING_INT_FROM_POINTER:
1059 if (warning.other) {
1060 warningf(source_position,
1061 "%s makes integer '%T' from pointer '%T' without a cast",
1062 context, orig_type_left, orig_type_right);
1067 panic("invalid error value");
1071 /** Implements the rules from § 6.5.16.1 */
1072 static assign_error_t semantic_assign(type_t *orig_type_left,
1073 const expression_t *const right)
1075 type_t *const orig_type_right = right->base.type;
1076 type_t *const type_left = skip_typeref(orig_type_left);
1077 type_t *const type_right = skip_typeref(orig_type_right);
1079 if (is_type_pointer(type_left)) {
1080 if (is_null_pointer_constant(right)) {
1081 return ASSIGN_SUCCESS;
1082 } else if (is_type_pointer(type_right)) {
1083 type_t *points_to_left
1084 = skip_typeref(type_left->pointer.points_to);
1085 type_t *points_to_right
1086 = skip_typeref(type_right->pointer.points_to);
1087 assign_error_t res = ASSIGN_SUCCESS;
1089 /* the left type has all qualifiers from the right type */
1090 unsigned missing_qualifiers
1091 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1092 if (missing_qualifiers != 0) {
1093 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1096 points_to_left = get_unqualified_type(points_to_left);
1097 points_to_right = get_unqualified_type(points_to_right);
1099 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1102 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1103 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1104 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1107 if (!types_compatible(points_to_left, points_to_right)) {
1108 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1112 } else if (is_type_integer(type_right)) {
1113 return ASSIGN_WARNING_POINTER_FROM_INT;
1115 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1116 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1117 && is_type_pointer(type_right))) {
1118 return ASSIGN_SUCCESS;
1119 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1120 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1121 type_t *const unqual_type_left = get_unqualified_type(type_left);
1122 type_t *const unqual_type_right = get_unqualified_type(type_right);
1123 if (types_compatible(unqual_type_left, unqual_type_right)) {
1124 return ASSIGN_SUCCESS;
1126 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1127 return ASSIGN_WARNING_INT_FROM_POINTER;
1130 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1131 return ASSIGN_SUCCESS;
1133 return ASSIGN_ERROR_INCOMPATIBLE;
1136 static expression_t *parse_constant_expression(void)
1138 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1140 if (!is_constant_expression(result)) {
1141 errorf(&result->base.source_position,
1142 "expression '%E' is not constant\n", result);
1148 static expression_t *parse_assignment_expression(void)
1150 return parse_sub_expression(PREC_ASSIGNMENT);
1153 static string_t parse_string_literals(void)
1155 assert(token.type == T_STRING_LITERAL);
1156 string_t result = token.v.string;
1160 while (token.type == T_STRING_LITERAL) {
1161 result = concat_strings(&result, &token.v.string);
1168 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1169 [GNU_AK_CONST] = "const",
1170 [GNU_AK_VOLATILE] = "volatile",
1171 [GNU_AK_CDECL] = "cdecl",
1172 [GNU_AK_STDCALL] = "stdcall",
1173 [GNU_AK_FASTCALL] = "fastcall",
1174 [GNU_AK_DEPRECATED] = "deprecated",
1175 [GNU_AK_NOINLINE] = "noinline",
1176 [GNU_AK_NORETURN] = "noreturn",
1177 [GNU_AK_NAKED] = "naked",
1178 [GNU_AK_PURE] = "pure",
1179 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1180 [GNU_AK_MALLOC] = "malloc",
1181 [GNU_AK_WEAK] = "weak",
1182 [GNU_AK_CONSTRUCTOR] = "constructor",
1183 [GNU_AK_DESTRUCTOR] = "destructor",
1184 [GNU_AK_NOTHROW] = "nothrow",
1185 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1186 [GNU_AK_COMMON] = "common",
1187 [GNU_AK_NOCOMMON] = "nocommon",
1188 [GNU_AK_PACKED] = "packed",
1189 [GNU_AK_SHARED] = "shared",
1190 [GNU_AK_NOTSHARED] = "notshared",
1191 [GNU_AK_USED] = "used",
1192 [GNU_AK_UNUSED] = "unused",
1193 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1194 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1195 [GNU_AK_LONGCALL] = "longcall",
1196 [GNU_AK_SHORTCALL] = "shortcall",
1197 [GNU_AK_LONG_CALL] = "long_call",
1198 [GNU_AK_SHORT_CALL] = "short_call",
1199 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1200 [GNU_AK_INTERRUPT] = "interrupt",
1201 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1202 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1203 [GNU_AK_NESTING] = "nesting",
1204 [GNU_AK_NEAR] = "near",
1205 [GNU_AK_FAR] = "far",
1206 [GNU_AK_SIGNAL] = "signal",
1207 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1208 [GNU_AK_TINY_DATA] = "tiny_data",
1209 [GNU_AK_SAVEALL] = "saveall",
1210 [GNU_AK_FLATTEN] = "flatten",
1211 [GNU_AK_SSEREGPARM] = "sseregparm",
1212 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1213 [GNU_AK_RETURN_TWICE] = "return_twice",
1214 [GNU_AK_MAY_ALIAS] = "may_alias",
1215 [GNU_AK_MS_STRUCT] = "ms_struct",
1216 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1217 [GNU_AK_DLLIMPORT] = "dllimport",
1218 [GNU_AK_DLLEXPORT] = "dllexport",
1219 [GNU_AK_ALIGNED] = "aligned",
1220 [GNU_AK_ALIAS] = "alias",
1221 [GNU_AK_SECTION] = "section",
1222 [GNU_AK_FORMAT] = "format",
1223 [GNU_AK_FORMAT_ARG] = "format_arg",
1224 [GNU_AK_WEAKREF] = "weakref",
1225 [GNU_AK_NONNULL] = "nonnull",
1226 [GNU_AK_TLS_MODEL] = "tls_model",
1227 [GNU_AK_VISIBILITY] = "visibility",
1228 [GNU_AK_REGPARM] = "regparm",
1229 [GNU_AK_MODE] = "mode",
1230 [GNU_AK_MODEL] = "model",
1231 [GNU_AK_TRAP_EXIT] = "trap_exit",
1232 [GNU_AK_SP_SWITCH] = "sp_switch",
1233 [GNU_AK_SENTINEL] = "sentinel"
1237 * compare two string, ignoring double underscores on the second.
1239 static int strcmp_underscore(const char *s1, const char *s2)
1241 if (s2[0] == '_' && s2[1] == '_') {
1242 size_t len2 = strlen(s2);
1243 size_t len1 = strlen(s1);
1244 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1245 return strncmp(s1, s2+2, len2-4);
1249 return strcmp(s1, s2);
1253 * Allocate a new gnu temporal attribute.
1255 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1257 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1258 attribute->kind = kind;
1259 attribute->next = NULL;
1260 attribute->invalid = false;
1261 attribute->have_arguments = false;
1267 * parse one constant expression argument.
1269 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1271 expression_t *expression;
1272 add_anchor_token(')');
1273 expression = parse_constant_expression();
1274 rem_anchor_token(')');
1276 attribute->u.argument = fold_constant(expression);
1279 attribute->invalid = true;
1283 * parse a list of constant expressions arguments.
1285 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1287 argument_list_t **list = &attribute->u.arguments;
1288 argument_list_t *entry;
1289 expression_t *expression;
1290 add_anchor_token(')');
1291 add_anchor_token(',');
1293 expression = parse_constant_expression();
1294 entry = obstack_alloc(&temp_obst, sizeof(entry));
1295 entry->argument = fold_constant(expression);
1298 list = &entry->next;
1299 if (token.type != ',')
1303 rem_anchor_token(',');
1304 rem_anchor_token(')');
1308 attribute->invalid = true;
1312 * parse one string literal argument.
1314 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1317 add_anchor_token('(');
1318 if (token.type != T_STRING_LITERAL) {
1319 parse_error_expected("while parsing attribute directive",
1320 T_STRING_LITERAL, NULL);
1323 *string = parse_string_literals();
1324 rem_anchor_token('(');
1328 attribute->invalid = true;
1332 * parse one tls model.
1334 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1336 static const char *const tls_models[] = {
1342 string_t string = { NULL, 0 };
1343 parse_gnu_attribute_string_arg(attribute, &string);
1344 if (string.begin != NULL) {
1345 for(size_t i = 0; i < 4; ++i) {
1346 if (strcmp(tls_models[i], string.begin) == 0) {
1347 attribute->u.value = i;
1351 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1353 attribute->invalid = true;
1357 * parse one tls model.
1359 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1361 static const char *const visibilities[] = {
1367 string_t string = { NULL, 0 };
1368 parse_gnu_attribute_string_arg(attribute, &string);
1369 if (string.begin != NULL) {
1370 for(size_t i = 0; i < 4; ++i) {
1371 if (strcmp(visibilities[i], string.begin) == 0) {
1372 attribute->u.value = i;
1376 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1378 attribute->invalid = true;
1382 * parse one (code) model.
1384 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1386 static const char *const visibilities[] = {
1391 string_t string = { NULL, 0 };
1392 parse_gnu_attribute_string_arg(attribute, &string);
1393 if (string.begin != NULL) {
1394 for(int i = 0; i < 3; ++i) {
1395 if (strcmp(visibilities[i], string.begin) == 0) {
1396 attribute->u.value = i;
1400 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1402 attribute->invalid = true;
1405 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1407 /* TODO: find out what is allowed here... */
1409 /* at least: byte, word, pointer, list of machine modes
1410 * __XXX___ is interpreted as XXX */
1411 add_anchor_token(')');
1413 if (token.type != T_IDENTIFIER) {
1414 expect(T_IDENTIFIER);
1417 /* This isn't really correct, the backend should provide a list of machine
1418 * specific modes (according to gcc philosophy that is...) */
1419 const char *symbol_str = token.v.symbol->string;
1420 if (strcmp_underscore("QI", symbol_str) == 0 ||
1421 strcmp_underscore("byte", symbol_str) == 0) {
1422 attribute->u.akind = ATOMIC_TYPE_CHAR;
1423 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1424 attribute->u.akind = ATOMIC_TYPE_SHORT;
1425 } else if (strcmp_underscore("SI", symbol_str) == 0
1426 || strcmp_underscore("word", symbol_str) == 0
1427 || strcmp_underscore("pointer", symbol_str) == 0) {
1428 attribute->u.akind = ATOMIC_TYPE_INT;
1429 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1430 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1433 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1434 attribute->invalid = true;
1438 rem_anchor_token(')');
1442 attribute->invalid = true;
1446 * parse one interrupt argument.
1448 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1450 static const char *const interrupts[] = {
1457 string_t string = { NULL, 0 };
1458 parse_gnu_attribute_string_arg(attribute, &string);
1459 if (string.begin != NULL) {
1460 for(size_t i = 0; i < 5; ++i) {
1461 if (strcmp(interrupts[i], string.begin) == 0) {
1462 attribute->u.value = i;
1466 errorf(HERE, "'%s' is not an interrupt", string.begin);
1468 attribute->invalid = true;
1472 * parse ( identifier, const expression, const expression )
1474 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1476 static const char *const format_names[] = {
1484 if (token.type != T_IDENTIFIER) {
1485 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1488 const char *name = token.v.symbol->string;
1489 for(i = 0; i < 4; ++i) {
1490 if (strcmp_underscore(format_names[i], name) == 0)
1494 if (warning.attribute)
1495 warningf(HERE, "'%s' is an unrecognized format function type", name);
1500 add_anchor_token(')');
1501 add_anchor_token(',');
1502 parse_constant_expression();
1503 rem_anchor_token(',');
1504 rem_anchor_token(')');
1507 add_anchor_token(')');
1508 parse_constant_expression();
1509 rem_anchor_token(')');
1513 attribute->u.value = true;
1516 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1518 if (!attribute->have_arguments)
1521 /* should have no arguments */
1522 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1523 eat_until_matching_token('(');
1524 /* we have already consumed '(', so we stop before ')', eat it */
1526 attribute->invalid = true;
1530 * Parse one GNU attribute.
1532 * Note that attribute names can be specified WITH or WITHOUT
1533 * double underscores, ie const or __const__.
1535 * The following attributes are parsed without arguments
1560 * no_instrument_function
1561 * warn_unused_result
1578 * externally_visible
1586 * The following attributes are parsed with arguments
1587 * aligned( const expression )
1588 * alias( string literal )
1589 * section( string literal )
1590 * format( identifier, const expression, const expression )
1591 * format_arg( const expression )
1592 * tls_model( string literal )
1593 * visibility( string literal )
1594 * regparm( const expression )
1595 * model( string leteral )
1596 * trap_exit( const expression )
1597 * sp_switch( string literal )
1599 * The following attributes might have arguments
1600 * weak_ref( string literal )
1601 * non_null( const expression // ',' )
1602 * interrupt( string literal )
1603 * sentinel( constant expression )
1605 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1607 gnu_attribute_t *head = *attributes;
1608 gnu_attribute_t *last = *attributes;
1609 decl_modifiers_t modifiers = 0;
1610 gnu_attribute_t *attribute;
1612 eat(T___attribute__);
1616 if (token.type != ')') {
1617 /* find the end of the list */
1619 while (last->next != NULL)
1623 /* non-empty attribute list */
1626 if (token.type == T_const) {
1628 } else if (token.type == T_volatile) {
1630 } else if (token.type == T_cdecl) {
1631 /* __attribute__((cdecl)), WITH ms mode */
1633 } else if (token.type == T_IDENTIFIER) {
1634 const symbol_t *sym = token.v.symbol;
1637 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1644 for(i = 0; i < GNU_AK_LAST; ++i) {
1645 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1648 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1651 if (kind == GNU_AK_LAST) {
1652 if (warning.attribute)
1653 warningf(HERE, "'%s' attribute directive ignored", name);
1655 /* skip possible arguments */
1656 if (token.type == '(') {
1657 eat_until_matching_token(')');
1660 /* check for arguments */
1661 attribute = allocate_gnu_attribute(kind);
1662 if (token.type == '(') {
1664 if (token.type == ')') {
1665 /* empty args are allowed */
1668 attribute->have_arguments = true;
1672 case GNU_AK_VOLATILE:
1677 case GNU_AK_NOCOMMON:
1679 case GNU_AK_NOTSHARED:
1680 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1681 case GNU_AK_WARN_UNUSED_RESULT:
1682 case GNU_AK_LONGCALL:
1683 case GNU_AK_SHORTCALL:
1684 case GNU_AK_LONG_CALL:
1685 case GNU_AK_SHORT_CALL:
1686 case GNU_AK_FUNCTION_VECTOR:
1687 case GNU_AK_INTERRUPT_HANDLER:
1688 case GNU_AK_NMI_HANDLER:
1689 case GNU_AK_NESTING:
1693 case GNU_AK_EIGTHBIT_DATA:
1694 case GNU_AK_TINY_DATA:
1695 case GNU_AK_SAVEALL:
1696 case GNU_AK_FLATTEN:
1697 case GNU_AK_SSEREGPARM:
1698 case GNU_AK_EXTERNALLY_VISIBLE:
1699 case GNU_AK_RETURN_TWICE:
1700 case GNU_AK_MAY_ALIAS:
1701 case GNU_AK_MS_STRUCT:
1702 case GNU_AK_GCC_STRUCT:
1705 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1706 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1707 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1708 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1709 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1710 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1711 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1712 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1713 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1714 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1715 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1716 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1717 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1718 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1719 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1720 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1721 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1722 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1724 case GNU_AK_ALIGNED:
1725 /* __align__ may be used without an argument */
1726 if (attribute->have_arguments) {
1727 parse_gnu_attribute_const_arg(attribute);
1731 case GNU_AK_FORMAT_ARG:
1732 case GNU_AK_REGPARM:
1733 case GNU_AK_TRAP_EXIT:
1734 if (!attribute->have_arguments) {
1735 /* should have arguments */
1736 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1737 attribute->invalid = true;
1739 parse_gnu_attribute_const_arg(attribute);
1742 case GNU_AK_SECTION:
1743 case GNU_AK_SP_SWITCH:
1744 if (!attribute->have_arguments) {
1745 /* should have arguments */
1746 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1747 attribute->invalid = true;
1749 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1752 if (!attribute->have_arguments) {
1753 /* should have arguments */
1754 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1755 attribute->invalid = true;
1757 parse_gnu_attribute_format_args(attribute);
1759 case GNU_AK_WEAKREF:
1760 /* may have one string argument */
1761 if (attribute->have_arguments)
1762 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1764 case GNU_AK_NONNULL:
1765 if (attribute->have_arguments)
1766 parse_gnu_attribute_const_arg_list(attribute);
1768 case GNU_AK_TLS_MODEL:
1769 if (!attribute->have_arguments) {
1770 /* should have arguments */
1771 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1773 parse_gnu_attribute_tls_model_arg(attribute);
1775 case GNU_AK_VISIBILITY:
1776 if (!attribute->have_arguments) {
1777 /* should have arguments */
1778 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1780 parse_gnu_attribute_visibility_arg(attribute);
1783 if (!attribute->have_arguments) {
1784 /* should have arguments */
1785 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1787 parse_gnu_attribute_model_arg(attribute);
1791 if (!attribute->have_arguments) {
1792 /* should have arguments */
1793 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1795 parse_gnu_attribute_mode_arg(attribute);
1798 case GNU_AK_INTERRUPT:
1799 /* may have one string argument */
1800 if (attribute->have_arguments)
1801 parse_gnu_attribute_interrupt_arg(attribute);
1803 case GNU_AK_SENTINEL:
1804 /* may have one string argument */
1805 if (attribute->have_arguments)
1806 parse_gnu_attribute_const_arg(attribute);
1809 /* already handled */
1813 check_no_argument(attribute, name);
1816 if (attribute != NULL) {
1818 last->next = attribute;
1821 head = last = attribute;
1825 if (token.type != ',')
1839 * Parse GNU attributes.
1841 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1843 decl_modifiers_t modifiers = 0;
1846 switch (token.type) {
1847 case T___attribute__:
1848 modifiers |= parse_gnu_attribute(attributes);
1854 if (token.type != T_STRING_LITERAL) {
1855 parse_error_expected("while parsing assembler attribute",
1856 T_STRING_LITERAL, NULL);
1857 eat_until_matching_token('(');
1860 parse_string_literals();
1865 case T_cdecl: modifiers |= DM_CDECL; break;
1866 case T__fastcall: modifiers |= DM_FASTCALL; break;
1867 case T__stdcall: modifiers |= DM_STDCALL; break;
1870 /* TODO record modifier */
1872 warningf(HERE, "Ignoring declaration modifier %K", &token);
1876 default: return modifiers;
1883 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1885 static variable_t *determine_lhs_var(expression_t *const expr,
1886 variable_t *lhs_var)
1888 switch (expr->kind) {
1889 case EXPR_REFERENCE: {
1890 entity_t *const entity = expr->reference.entity;
1891 /* we should only find variables as lavlues... */
1892 if (entity->base.kind != ENTITY_VARIABLE)
1895 return &entity->variable;
1898 case EXPR_ARRAY_ACCESS: {
1899 expression_t *const ref = expr->array_access.array_ref;
1900 variable_t * var = NULL;
1901 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1902 var = determine_lhs_var(ref, lhs_var);
1905 mark_vars_read(expr->select.compound, lhs_var);
1907 mark_vars_read(expr->array_access.index, lhs_var);
1912 if (is_type_compound(skip_typeref(expr->base.type))) {
1913 return determine_lhs_var(expr->select.compound, lhs_var);
1915 mark_vars_read(expr->select.compound, lhs_var);
1920 case EXPR_UNARY_DEREFERENCE: {
1921 expression_t *const val = expr->unary.value;
1922 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1924 return determine_lhs_var(val->unary.value, lhs_var);
1926 mark_vars_read(val, NULL);
1932 mark_vars_read(expr, NULL);
1937 #define VAR_ANY ((variable_t*)-1)
1940 * Mark declarations, which are read. This is used to deted variables, which
1944 * x is not marked as "read", because it is only read to calculate its own new
1948 * x and y are not detected as "not read", because multiple variables are
1951 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1953 switch (expr->kind) {
1954 case EXPR_REFERENCE: {
1955 entity_t *const entity = expr->reference.entity;
1956 if (entity->kind != ENTITY_VARIABLE)
1959 variable_t *variable = &entity->variable;
1960 if (lhs_var != variable && lhs_var != VAR_ANY) {
1961 variable->read = true;
1967 // TODO respect pure/const
1968 mark_vars_read(expr->call.function, NULL);
1969 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1970 mark_vars_read(arg->expression, NULL);
1974 case EXPR_CONDITIONAL:
1975 // TODO lhs_decl should depend on whether true/false have an effect
1976 mark_vars_read(expr->conditional.condition, NULL);
1977 if (expr->conditional.true_expression != NULL)
1978 mark_vars_read(expr->conditional.true_expression, lhs_var);
1979 mark_vars_read(expr->conditional.false_expression, lhs_var);
1983 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
1985 mark_vars_read(expr->select.compound, lhs_var);
1988 case EXPR_ARRAY_ACCESS: {
1989 expression_t *const ref = expr->array_access.array_ref;
1990 mark_vars_read(ref, lhs_var);
1991 lhs_var = determine_lhs_var(ref, lhs_var);
1992 mark_vars_read(expr->array_access.index, lhs_var);
1997 mark_vars_read(expr->va_arge.ap, lhs_var);
2000 case EXPR_UNARY_CAST:
2001 /* Special case: Use void cast to mark a variable as "read" */
2002 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2007 case EXPR_UNARY_THROW:
2008 if (expr->unary.value == NULL)
2011 case EXPR_UNARY_DEREFERENCE:
2012 case EXPR_UNARY_DELETE:
2013 case EXPR_UNARY_DELETE_ARRAY:
2014 if (lhs_var == VAR_ANY)
2018 case EXPR_UNARY_NEGATE:
2019 case EXPR_UNARY_PLUS:
2020 case EXPR_UNARY_BITWISE_NEGATE:
2021 case EXPR_UNARY_NOT:
2022 case EXPR_UNARY_TAKE_ADDRESS:
2023 case EXPR_UNARY_POSTFIX_INCREMENT:
2024 case EXPR_UNARY_POSTFIX_DECREMENT:
2025 case EXPR_UNARY_PREFIX_INCREMENT:
2026 case EXPR_UNARY_PREFIX_DECREMENT:
2027 case EXPR_UNARY_CAST_IMPLICIT:
2028 case EXPR_UNARY_ASSUME:
2030 mark_vars_read(expr->unary.value, lhs_var);
2033 case EXPR_BINARY_ADD:
2034 case EXPR_BINARY_SUB:
2035 case EXPR_BINARY_MUL:
2036 case EXPR_BINARY_DIV:
2037 case EXPR_BINARY_MOD:
2038 case EXPR_BINARY_EQUAL:
2039 case EXPR_BINARY_NOTEQUAL:
2040 case EXPR_BINARY_LESS:
2041 case EXPR_BINARY_LESSEQUAL:
2042 case EXPR_BINARY_GREATER:
2043 case EXPR_BINARY_GREATEREQUAL:
2044 case EXPR_BINARY_BITWISE_AND:
2045 case EXPR_BINARY_BITWISE_OR:
2046 case EXPR_BINARY_BITWISE_XOR:
2047 case EXPR_BINARY_LOGICAL_AND:
2048 case EXPR_BINARY_LOGICAL_OR:
2049 case EXPR_BINARY_SHIFTLEFT:
2050 case EXPR_BINARY_SHIFTRIGHT:
2051 case EXPR_BINARY_COMMA:
2052 case EXPR_BINARY_ISGREATER:
2053 case EXPR_BINARY_ISGREATEREQUAL:
2054 case EXPR_BINARY_ISLESS:
2055 case EXPR_BINARY_ISLESSEQUAL:
2056 case EXPR_BINARY_ISLESSGREATER:
2057 case EXPR_BINARY_ISUNORDERED:
2058 mark_vars_read(expr->binary.left, lhs_var);
2059 mark_vars_read(expr->binary.right, lhs_var);
2062 case EXPR_BINARY_ASSIGN:
2063 case EXPR_BINARY_MUL_ASSIGN:
2064 case EXPR_BINARY_DIV_ASSIGN:
2065 case EXPR_BINARY_MOD_ASSIGN:
2066 case EXPR_BINARY_ADD_ASSIGN:
2067 case EXPR_BINARY_SUB_ASSIGN:
2068 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2069 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2070 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2071 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2072 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2073 if (lhs_var == VAR_ANY)
2075 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2076 mark_vars_read(expr->binary.right, lhs_var);
2081 determine_lhs_var(expr->va_starte.ap, lhs_var);
2087 case EXPR_CHARACTER_CONSTANT:
2088 case EXPR_WIDE_CHARACTER_CONSTANT:
2089 case EXPR_STRING_LITERAL:
2090 case EXPR_WIDE_STRING_LITERAL:
2091 case EXPR_COMPOUND_LITERAL: // TODO init?
2093 case EXPR_CLASSIFY_TYPE:
2096 case EXPR_BUILTIN_SYMBOL:
2097 case EXPR_BUILTIN_CONSTANT_P:
2098 case EXPR_BUILTIN_PREFETCH:
2100 case EXPR_STATEMENT: // TODO
2101 case EXPR_LABEL_ADDRESS:
2102 case EXPR_BINARY_BUILTIN_EXPECT:
2103 case EXPR_REFERENCE_ENUM_VALUE:
2107 panic("unhandled expression");
2110 static designator_t *parse_designation(void)
2112 designator_t *result = NULL;
2113 designator_t *last = NULL;
2116 designator_t *designator;
2117 switch (token.type) {
2119 designator = allocate_ast_zero(sizeof(designator[0]));
2120 designator->source_position = token.source_position;
2122 add_anchor_token(']');
2123 designator->array_index = parse_constant_expression();
2124 rem_anchor_token(']');
2128 designator = allocate_ast_zero(sizeof(designator[0]));
2129 designator->source_position = token.source_position;
2131 if (token.type != T_IDENTIFIER) {
2132 parse_error_expected("while parsing designator",
2133 T_IDENTIFIER, NULL);
2136 designator->symbol = token.v.symbol;
2144 assert(designator != NULL);
2146 last->next = designator;
2148 result = designator;
2156 static initializer_t *initializer_from_string(array_type_t *type,
2157 const string_t *const string)
2159 /* TODO: check len vs. size of array type */
2162 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2163 initializer->string.string = *string;
2168 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2169 wide_string_t *const string)
2171 /* TODO: check len vs. size of array type */
2174 initializer_t *const initializer =
2175 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2176 initializer->wide_string.string = *string;
2182 * Build an initializer from a given expression.
2184 static initializer_t *initializer_from_expression(type_t *orig_type,
2185 expression_t *expression)
2187 /* TODO check that expression is a constant expression */
2189 /* § 6.7.8.14/15 char array may be initialized by string literals */
2190 type_t *type = skip_typeref(orig_type);
2191 type_t *expr_type_orig = expression->base.type;
2192 type_t *expr_type = skip_typeref(expr_type_orig);
2193 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2194 array_type_t *const array_type = &type->array;
2195 type_t *const element_type = skip_typeref(array_type->element_type);
2197 if (element_type->kind == TYPE_ATOMIC) {
2198 atomic_type_kind_t akind = element_type->atomic.akind;
2199 switch (expression->kind) {
2200 case EXPR_STRING_LITERAL:
2201 if (akind == ATOMIC_TYPE_CHAR
2202 || akind == ATOMIC_TYPE_SCHAR
2203 || akind == ATOMIC_TYPE_UCHAR) {
2204 return initializer_from_string(array_type,
2205 &expression->string.value);
2208 case EXPR_WIDE_STRING_LITERAL: {
2209 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2210 if (get_unqualified_type(element_type) == bare_wchar_type) {
2211 return initializer_from_wide_string(array_type,
2212 &expression->wide_string.value);
2222 assign_error_t error = semantic_assign(type, expression);
2223 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2225 report_assign_error(error, type, expression, "initializer",
2226 &expression->base.source_position);
2228 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2230 if (type->kind == TYPE_BITFIELD) {
2231 type = type->bitfield.base_type;
2234 result->value.value = create_implicit_cast(expression, type);
2240 * Checks if a given expression can be used as an constant initializer.
2242 static bool is_initializer_constant(const expression_t *expression)
2244 return is_constant_expression(expression)
2245 || is_address_constant(expression);
2249 * Parses an scalar initializer.
2251 * § 6.7.8.11; eat {} without warning
2253 static initializer_t *parse_scalar_initializer(type_t *type,
2254 bool must_be_constant)
2256 /* there might be extra {} hierarchies */
2258 if (token.type == '{') {
2260 warningf(HERE, "extra curly braces around scalar initializer");
2264 } while (token.type == '{');
2267 expression_t *expression = parse_assignment_expression();
2268 mark_vars_read(expression, NULL);
2269 if (must_be_constant && !is_initializer_constant(expression)) {
2270 errorf(&expression->base.source_position,
2271 "Initialisation expression '%E' is not constant\n",
2275 initializer_t *initializer = initializer_from_expression(type, expression);
2277 if (initializer == NULL) {
2278 errorf(&expression->base.source_position,
2279 "expression '%E' (type '%T') doesn't match expected type '%T'",
2280 expression, expression->base.type, type);
2285 bool additional_warning_displayed = false;
2286 while (braces > 0) {
2287 if (token.type == ',') {
2290 if (token.type != '}') {
2291 if (!additional_warning_displayed && warning.other) {
2292 warningf(HERE, "additional elements in scalar initializer");
2293 additional_warning_displayed = true;
2304 * An entry in the type path.
2306 typedef struct type_path_entry_t type_path_entry_t;
2307 struct type_path_entry_t {
2308 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2310 size_t index; /**< For array types: the current index. */
2311 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2316 * A type path expression a position inside compound or array types.
2318 typedef struct type_path_t type_path_t;
2319 struct type_path_t {
2320 type_path_entry_t *path; /**< An flexible array containing the current path. */
2321 type_t *top_type; /**< type of the element the path points */
2322 size_t max_index; /**< largest index in outermost array */
2326 * Prints a type path for debugging.
2328 static __attribute__((unused)) void debug_print_type_path(
2329 const type_path_t *path)
2331 size_t len = ARR_LEN(path->path);
2333 for(size_t i = 0; i < len; ++i) {
2334 const type_path_entry_t *entry = & path->path[i];
2336 type_t *type = skip_typeref(entry->type);
2337 if (is_type_compound(type)) {
2338 /* in gcc mode structs can have no members */
2339 if (entry->v.compound_entry == NULL) {
2343 fprintf(stderr, ".%s",
2344 entry->v.compound_entry->base.symbol->string);
2345 } else if (is_type_array(type)) {
2346 fprintf(stderr, "[%zu]", entry->v.index);
2348 fprintf(stderr, "-INVALID-");
2351 if (path->top_type != NULL) {
2352 fprintf(stderr, " (");
2353 print_type(path->top_type);
2354 fprintf(stderr, ")");
2359 * Return the top type path entry, ie. in a path
2360 * (type).a.b returns the b.
2362 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2364 size_t len = ARR_LEN(path->path);
2366 return &path->path[len-1];
2370 * Enlarge the type path by an (empty) element.
2372 static type_path_entry_t *append_to_type_path(type_path_t *path)
2374 size_t len = ARR_LEN(path->path);
2375 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2377 type_path_entry_t *result = & path->path[len];
2378 memset(result, 0, sizeof(result[0]));
2383 * Descending into a sub-type. Enter the scope of the current top_type.
2385 static void descend_into_subtype(type_path_t *path)
2387 type_t *orig_top_type = path->top_type;
2388 type_t *top_type = skip_typeref(orig_top_type);
2390 type_path_entry_t *top = append_to_type_path(path);
2391 top->type = top_type;
2393 if (is_type_compound(top_type)) {
2394 compound_t *compound = top_type->compound.compound;
2395 entity_t *entry = compound->members.entities;
2397 if (entry != NULL) {
2398 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2399 top->v.compound_entry = &entry->declaration;
2400 path->top_type = entry->declaration.type;
2402 path->top_type = NULL;
2404 } else if (is_type_array(top_type)) {
2406 path->top_type = top_type->array.element_type;
2408 assert(!is_type_valid(top_type));
2413 * Pop an entry from the given type path, ie. returning from
2414 * (type).a.b to (type).a
2416 static void ascend_from_subtype(type_path_t *path)
2418 type_path_entry_t *top = get_type_path_top(path);
2420 path->top_type = top->type;
2422 size_t len = ARR_LEN(path->path);
2423 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2427 * Pop entries from the given type path until the given
2428 * path level is reached.
2430 static void ascend_to(type_path_t *path, size_t top_path_level)
2432 size_t len = ARR_LEN(path->path);
2434 while (len > top_path_level) {
2435 ascend_from_subtype(path);
2436 len = ARR_LEN(path->path);
2440 static bool walk_designator(type_path_t *path, const designator_t *designator,
2441 bool used_in_offsetof)
2443 for( ; designator != NULL; designator = designator->next) {
2444 type_path_entry_t *top = get_type_path_top(path);
2445 type_t *orig_type = top->type;
2447 type_t *type = skip_typeref(orig_type);
2449 if (designator->symbol != NULL) {
2450 symbol_t *symbol = designator->symbol;
2451 if (!is_type_compound(type)) {
2452 if (is_type_valid(type)) {
2453 errorf(&designator->source_position,
2454 "'.%Y' designator used for non-compound type '%T'",
2458 top->type = type_error_type;
2459 top->v.compound_entry = NULL;
2460 orig_type = type_error_type;
2462 compound_t *compound = type->compound.compound;
2463 entity_t *iter = compound->members.entities;
2464 for( ; iter != NULL; iter = iter->base.next) {
2465 if (iter->base.symbol == symbol) {
2470 errorf(&designator->source_position,
2471 "'%T' has no member named '%Y'", orig_type, symbol);
2474 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2475 if (used_in_offsetof) {
2476 type_t *real_type = skip_typeref(iter->declaration.type);
2477 if (real_type->kind == TYPE_BITFIELD) {
2478 errorf(&designator->source_position,
2479 "offsetof designator '%Y' may not specify bitfield",
2485 top->type = orig_type;
2486 top->v.compound_entry = &iter->declaration;
2487 orig_type = iter->declaration.type;
2490 expression_t *array_index = designator->array_index;
2491 assert(designator->array_index != NULL);
2493 if (!is_type_array(type)) {
2494 if (is_type_valid(type)) {
2495 errorf(&designator->source_position,
2496 "[%E] designator used for non-array type '%T'",
2497 array_index, orig_type);
2502 long index = fold_constant(array_index);
2503 if (!used_in_offsetof) {
2505 errorf(&designator->source_position,
2506 "array index [%E] must be positive", array_index);
2507 } else if (type->array.size_constant) {
2508 long array_size = type->array.size;
2509 if (index >= array_size) {
2510 errorf(&designator->source_position,
2511 "designator [%E] (%d) exceeds array size %d",
2512 array_index, index, array_size);
2517 top->type = orig_type;
2518 top->v.index = (size_t) index;
2519 orig_type = type->array.element_type;
2521 path->top_type = orig_type;
2523 if (designator->next != NULL) {
2524 descend_into_subtype(path);
2533 static void advance_current_object(type_path_t *path, size_t top_path_level)
2535 type_path_entry_t *top = get_type_path_top(path);
2537 type_t *type = skip_typeref(top->type);
2538 if (is_type_union(type)) {
2539 /* in unions only the first element is initialized */
2540 top->v.compound_entry = NULL;
2541 } else if (is_type_struct(type)) {
2542 declaration_t *entry = top->v.compound_entry;
2544 entity_t *next_entity = entry->base.next;
2545 if (next_entity != NULL) {
2546 assert(is_declaration(next_entity));
2547 entry = &next_entity->declaration;
2552 top->v.compound_entry = entry;
2553 if (entry != NULL) {
2554 path->top_type = entry->type;
2557 } else if (is_type_array(type)) {
2558 assert(is_type_array(type));
2562 if (!type->array.size_constant || top->v.index < type->array.size) {
2566 assert(!is_type_valid(type));
2570 /* we're past the last member of the current sub-aggregate, try if we
2571 * can ascend in the type hierarchy and continue with another subobject */
2572 size_t len = ARR_LEN(path->path);
2574 if (len > top_path_level) {
2575 ascend_from_subtype(path);
2576 advance_current_object(path, top_path_level);
2578 path->top_type = NULL;
2583 * skip until token is found.
2585 static void skip_until(int type)
2587 while (token.type != type) {
2588 if (token.type == T_EOF)
2595 * skip any {...} blocks until a closing bracket is reached.
2597 static void skip_initializers(void)
2599 if (token.type == '{')
2602 while (token.type != '}') {
2603 if (token.type == T_EOF)
2605 if (token.type == '{') {
2613 static initializer_t *create_empty_initializer(void)
2615 static initializer_t empty_initializer
2616 = { .list = { { INITIALIZER_LIST }, 0 } };
2617 return &empty_initializer;
2621 * Parse a part of an initialiser for a struct or union,
2623 static initializer_t *parse_sub_initializer(type_path_t *path,
2624 type_t *outer_type, size_t top_path_level,
2625 parse_initializer_env_t *env)
2627 if (token.type == '}') {
2628 /* empty initializer */
2629 return create_empty_initializer();
2632 type_t *orig_type = path->top_type;
2633 type_t *type = NULL;
2635 if (orig_type == NULL) {
2636 /* We are initializing an empty compound. */
2638 type = skip_typeref(orig_type);
2641 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2644 designator_t *designator = NULL;
2645 if (token.type == '.' || token.type == '[') {
2646 designator = parse_designation();
2647 goto finish_designator;
2648 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2649 /* GNU-style designator ("identifier: value") */
2650 designator = allocate_ast_zero(sizeof(designator[0]));
2651 designator->source_position = token.source_position;
2652 designator->symbol = token.v.symbol;
2657 /* reset path to toplevel, evaluate designator from there */
2658 ascend_to(path, top_path_level);
2659 if (!walk_designator(path, designator, false)) {
2660 /* can't continue after designation error */
2664 initializer_t *designator_initializer
2665 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2666 designator_initializer->designator.designator = designator;
2667 ARR_APP1(initializer_t*, initializers, designator_initializer);
2669 orig_type = path->top_type;
2670 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2675 if (token.type == '{') {
2676 if (type != NULL && is_type_scalar(type)) {
2677 sub = parse_scalar_initializer(type, env->must_be_constant);
2681 if (env->entity != NULL) {
2683 "extra brace group at end of initializer for '%Y'",
2684 env->entity->base.symbol);
2686 errorf(HERE, "extra brace group at end of initializer");
2689 descend_into_subtype(path);
2691 add_anchor_token('}');
2692 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2694 rem_anchor_token('}');
2697 ascend_from_subtype(path);
2701 goto error_parse_next;
2705 /* must be an expression */
2706 expression_t *expression = parse_assignment_expression();
2708 if (env->must_be_constant && !is_initializer_constant(expression)) {
2709 errorf(&expression->base.source_position,
2710 "Initialisation expression '%E' is not constant\n",
2715 /* we are already outside, ... */
2716 type_t *const outer_type_skip = skip_typeref(outer_type);
2717 if (is_type_compound(outer_type_skip) &&
2718 !outer_type_skip->compound.compound->complete) {
2719 goto error_parse_next;
2724 /* handle { "string" } special case */
2725 if ((expression->kind == EXPR_STRING_LITERAL
2726 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2727 && outer_type != NULL) {
2728 sub = initializer_from_expression(outer_type, expression);
2730 if (token.type == ',') {
2733 if (token.type != '}' && warning.other) {
2734 warningf(HERE, "excessive elements in initializer for type '%T'",
2737 /* TODO: eat , ... */
2742 /* descend into subtypes until expression matches type */
2744 orig_type = path->top_type;
2745 type = skip_typeref(orig_type);
2747 sub = initializer_from_expression(orig_type, expression);
2751 if (!is_type_valid(type)) {
2754 if (is_type_scalar(type)) {
2755 errorf(&expression->base.source_position,
2756 "expression '%E' doesn't match expected type '%T'",
2757 expression, orig_type);
2761 descend_into_subtype(path);
2765 /* update largest index of top array */
2766 const type_path_entry_t *first = &path->path[0];
2767 type_t *first_type = first->type;
2768 first_type = skip_typeref(first_type);
2769 if (is_type_array(first_type)) {
2770 size_t index = first->v.index;
2771 if (index > path->max_index)
2772 path->max_index = index;
2776 /* append to initializers list */
2777 ARR_APP1(initializer_t*, initializers, sub);
2780 if (warning.other) {
2781 if (env->entity != NULL) {
2782 warningf(HERE, "excess elements in struct initializer for '%Y'",
2783 env->entity->base.symbol);
2785 warningf(HERE, "excess elements in struct initializer");
2791 if (token.type == '}') {
2795 if (token.type == '}') {
2800 /* advance to the next declaration if we are not at the end */
2801 advance_current_object(path, top_path_level);
2802 orig_type = path->top_type;
2803 if (orig_type != NULL)
2804 type = skip_typeref(orig_type);
2810 size_t len = ARR_LEN(initializers);
2811 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2812 initializer_t *result = allocate_ast_zero(size);
2813 result->kind = INITIALIZER_LIST;
2814 result->list.len = len;
2815 memcpy(&result->list.initializers, initializers,
2816 len * sizeof(initializers[0]));
2818 DEL_ARR_F(initializers);
2819 ascend_to(path, top_path_level+1);
2824 skip_initializers();
2825 DEL_ARR_F(initializers);
2826 ascend_to(path, top_path_level+1);
2831 * Parses an initializer. Parsers either a compound literal
2832 * (env->declaration == NULL) or an initializer of a declaration.
2834 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2836 type_t *type = skip_typeref(env->type);
2837 initializer_t *result = NULL;
2840 if (is_type_scalar(type)) {
2841 result = parse_scalar_initializer(type, env->must_be_constant);
2842 } else if (token.type == '{') {
2846 memset(&path, 0, sizeof(path));
2847 path.top_type = env->type;
2848 path.path = NEW_ARR_F(type_path_entry_t, 0);
2850 descend_into_subtype(&path);
2852 add_anchor_token('}');
2853 result = parse_sub_initializer(&path, env->type, 1, env);
2854 rem_anchor_token('}');
2856 max_index = path.max_index;
2857 DEL_ARR_F(path.path);
2861 /* parse_scalar_initializer() also works in this case: we simply
2862 * have an expression without {} around it */
2863 result = parse_scalar_initializer(type, env->must_be_constant);
2866 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2867 * the array type size */
2868 if (is_type_array(type) && type->array.size_expression == NULL
2869 && result != NULL) {
2871 switch (result->kind) {
2872 case INITIALIZER_LIST:
2873 size = max_index + 1;
2876 case INITIALIZER_STRING:
2877 size = result->string.string.size;
2880 case INITIALIZER_WIDE_STRING:
2881 size = result->wide_string.string.size;
2884 case INITIALIZER_DESIGNATOR:
2885 case INITIALIZER_VALUE:
2886 /* can happen for parse errors */
2891 internal_errorf(HERE, "invalid initializer type");
2894 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2895 cnst->base.type = type_size_t;
2896 cnst->conste.v.int_value = size;
2898 type_t *new_type = duplicate_type(type);
2900 new_type->array.size_expression = cnst;
2901 new_type->array.size_constant = true;
2902 new_type->array.has_implicit_size = true;
2903 new_type->array.size = size;
2904 env->type = new_type;
2912 static void append_entity(scope_t *scope, entity_t *entity)
2914 if (scope->last_entity != NULL) {
2915 scope->last_entity->base.next = entity;
2917 scope->entities = entity;
2919 scope->last_entity = entity;
2923 static compound_t *parse_compound_type_specifier(bool is_struct)
2925 gnu_attribute_t *attributes = NULL;
2926 decl_modifiers_t modifiers = 0;
2933 symbol_t *symbol = NULL;
2934 compound_t *compound = NULL;
2936 if (token.type == T___attribute__) {
2937 modifiers |= parse_attributes(&attributes);
2940 if (token.type == T_IDENTIFIER) {
2941 symbol = token.v.symbol;
2944 namespace_t const namespc =
2945 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2946 entity_t *entity = get_entity(symbol, namespc);
2947 if (entity != NULL) {
2948 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2949 compound = &entity->compound;
2950 if (compound->base.parent_scope != scope &&
2951 (token.type == '{' || token.type == ';')) {
2952 /* we're in an inner scope and have a definition. Override
2953 existing definition in outer scope */
2955 } else if (compound->complete && token.type == '{') {
2956 assert(symbol != NULL);
2957 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2958 is_struct ? "struct" : "union", symbol,
2959 &compound->base.source_position);
2960 /* clear members in the hope to avoid further errors */
2961 compound->members.entities = NULL;
2964 } else if (token.type != '{') {
2966 parse_error_expected("while parsing struct type specifier",
2967 T_IDENTIFIER, '{', NULL);
2969 parse_error_expected("while parsing union type specifier",
2970 T_IDENTIFIER, '{', NULL);
2976 if (compound == NULL) {
2977 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2978 entity_t *entity = allocate_entity_zero(kind);
2979 compound = &entity->compound;
2981 compound->base.namespc =
2982 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2983 compound->base.source_position = token.source_position;
2984 compound->base.symbol = symbol;
2985 compound->base.parent_scope = scope;
2986 if (symbol != NULL) {
2987 environment_push(entity);
2989 append_entity(scope, entity);
2992 if (token.type == '{') {
2993 compound->complete = true;
2995 parse_compound_type_entries(compound);
2996 modifiers |= parse_attributes(&attributes);
2999 compound->modifiers |= modifiers;
3003 static void parse_enum_entries(type_t *const enum_type)
3007 if (token.type == '}') {
3009 errorf(HERE, "empty enum not allowed");
3013 add_anchor_token('}');
3015 if (token.type != T_IDENTIFIER) {
3016 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3018 rem_anchor_token('}');
3022 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3023 entity->enum_value.enum_type = enum_type;
3024 entity->base.symbol = token.v.symbol;
3025 entity->base.source_position = token.source_position;
3028 if (token.type == '=') {
3030 expression_t *value = parse_constant_expression();
3032 value = create_implicit_cast(value, enum_type);
3033 entity->enum_value.value = value;
3038 record_entity(entity, false);
3040 if (token.type != ',')
3043 } while (token.type != '}');
3044 rem_anchor_token('}');
3052 static type_t *parse_enum_specifier(void)
3054 gnu_attribute_t *attributes = NULL;
3059 if (token.type == T_IDENTIFIER) {
3060 symbol = token.v.symbol;
3063 entity = get_entity(symbol, NAMESPACE_ENUM);
3064 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3065 } else if (token.type != '{') {
3066 parse_error_expected("while parsing enum type specifier",
3067 T_IDENTIFIER, '{', NULL);
3074 if (entity == NULL) {
3075 entity = allocate_entity_zero(ENTITY_ENUM);
3076 entity->base.namespc = NAMESPACE_ENUM;
3077 entity->base.source_position = token.source_position;
3078 entity->base.symbol = symbol;
3079 entity->base.parent_scope = scope;
3082 type_t *const type = allocate_type_zero(TYPE_ENUM);
3083 type->enumt.enume = &entity->enume;
3085 if (token.type == '{') {
3086 if (entity->enume.complete) {
3087 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3088 symbol, &entity->base.source_position);
3090 if (symbol != NULL) {
3091 environment_push(entity);
3093 append_entity(scope, entity);
3094 entity->enume.complete = true;
3096 parse_enum_entries(type);
3097 parse_attributes(&attributes);
3098 } else if(!entity->enume.complete && !(c_mode & _GNUC)) {
3099 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3107 * if a symbol is a typedef to another type, return true
3109 static bool is_typedef_symbol(symbol_t *symbol)
3111 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3112 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3115 static type_t *parse_typeof(void)
3122 add_anchor_token(')');
3124 expression_t *expression = NULL;
3126 bool old_type_prop = in_type_prop;
3127 bool old_gcc_extension = in_gcc_extension;
3128 in_type_prop = true;
3130 while (token.type == T___extension__) {
3131 /* This can be a prefix to a typename or an expression. */
3133 in_gcc_extension = true;
3135 switch (token.type) {
3137 if (is_typedef_symbol(token.v.symbol)) {
3138 type = parse_typename();
3140 expression = parse_expression();
3141 type = expression->base.type;
3146 type = parse_typename();
3150 expression = parse_expression();
3151 type = expression->base.type;
3154 in_type_prop = old_type_prop;
3155 in_gcc_extension = old_gcc_extension;
3157 rem_anchor_token(')');
3160 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3161 typeof_type->typeoft.expression = expression;
3162 typeof_type->typeoft.typeof_type = type;
3169 typedef enum specifiers_t {
3170 SPECIFIER_SIGNED = 1 << 0,
3171 SPECIFIER_UNSIGNED = 1 << 1,
3172 SPECIFIER_LONG = 1 << 2,
3173 SPECIFIER_INT = 1 << 3,
3174 SPECIFIER_DOUBLE = 1 << 4,
3175 SPECIFIER_CHAR = 1 << 5,
3176 SPECIFIER_SHORT = 1 << 6,
3177 SPECIFIER_LONG_LONG = 1 << 7,
3178 SPECIFIER_FLOAT = 1 << 8,
3179 SPECIFIER_BOOL = 1 << 9,
3180 SPECIFIER_VOID = 1 << 10,
3181 SPECIFIER_INT8 = 1 << 11,
3182 SPECIFIER_INT16 = 1 << 12,
3183 SPECIFIER_INT32 = 1 << 13,
3184 SPECIFIER_INT64 = 1 << 14,
3185 SPECIFIER_INT128 = 1 << 15,
3186 SPECIFIER_COMPLEX = 1 << 16,
3187 SPECIFIER_IMAGINARY = 1 << 17,
3190 static type_t *create_builtin_type(symbol_t *const symbol,
3191 type_t *const real_type)
3193 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3194 type->builtin.symbol = symbol;
3195 type->builtin.real_type = real_type;
3197 type_t *result = typehash_insert(type);
3198 if (type != result) {
3205 static type_t *get_typedef_type(symbol_t *symbol)
3207 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3208 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3211 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3212 type->typedeft.typedefe = &entity->typedefe;
3218 * check for the allowed MS alignment values.
3220 static bool check_alignment_value(long long intvalue)
3222 if (intvalue < 1 || intvalue > 8192) {
3223 errorf(HERE, "illegal alignment value");
3226 unsigned v = (unsigned)intvalue;
3227 for (unsigned i = 1; i <= 8192; i += i) {
3231 errorf(HERE, "alignment must be power of two");
3235 #define DET_MOD(name, tag) do { \
3236 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3237 *modifiers |= tag; \
3240 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3242 decl_modifiers_t *modifiers = &specifiers->modifiers;
3245 if (token.type == T_restrict) {
3247 DET_MOD(restrict, DM_RESTRICT);
3249 } else if (token.type != T_IDENTIFIER)
3251 symbol_t *symbol = token.v.symbol;
3252 if (symbol == sym_align) {
3255 if (token.type != T_INTEGER)
3257 if (check_alignment_value(token.v.intvalue)) {
3258 if (specifiers->alignment != 0 && warning.other)
3259 warningf(HERE, "align used more than once");
3260 specifiers->alignment = (unsigned char)token.v.intvalue;
3264 } else if (symbol == sym_allocate) {
3267 if (token.type != T_IDENTIFIER)
3269 (void)token.v.symbol;
3271 } else if (symbol == sym_dllimport) {
3273 DET_MOD(dllimport, DM_DLLIMPORT);
3274 } else if (symbol == sym_dllexport) {
3276 DET_MOD(dllexport, DM_DLLEXPORT);
3277 } else if (symbol == sym_thread) {
3279 DET_MOD(thread, DM_THREAD);
3280 } else if (symbol == sym_naked) {
3282 DET_MOD(naked, DM_NAKED);
3283 } else if (symbol == sym_noinline) {
3285 DET_MOD(noinline, DM_NOINLINE);
3286 } else if (symbol == sym_noreturn) {
3288 DET_MOD(noreturn, DM_NORETURN);
3289 } else if (symbol == sym_nothrow) {
3291 DET_MOD(nothrow, DM_NOTHROW);
3292 } else if (symbol == sym_novtable) {
3294 DET_MOD(novtable, DM_NOVTABLE);
3295 } else if (symbol == sym_property) {
3299 bool is_get = false;
3300 if (token.type != T_IDENTIFIER)
3302 if (token.v.symbol == sym_get) {
3304 } else if (token.v.symbol == sym_put) {
3306 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3311 if (token.type != T_IDENTIFIER)
3314 if (specifiers->get_property_sym != NULL) {
3315 errorf(HERE, "get property name already specified");
3317 specifiers->get_property_sym = token.v.symbol;
3320 if (specifiers->put_property_sym != NULL) {
3321 errorf(HERE, "put property name already specified");
3323 specifiers->put_property_sym = token.v.symbol;
3327 if (token.type == ',') {
3334 } else if (symbol == sym_selectany) {
3336 DET_MOD(selectany, DM_SELECTANY);
3337 } else if (symbol == sym_uuid) {
3340 if (token.type != T_STRING_LITERAL)
3344 } else if (symbol == sym_deprecated) {
3346 if (specifiers->deprecated != 0 && warning.other)
3347 warningf(HERE, "deprecated used more than once");
3348 specifiers->deprecated = true;
3349 if (token.type == '(') {
3351 if (token.type == T_STRING_LITERAL) {
3352 specifiers->deprecated_string = token.v.string.begin;
3355 errorf(HERE, "string literal expected");
3359 } else if (symbol == sym_noalias) {
3361 DET_MOD(noalias, DM_NOALIAS);
3364 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3366 if (token.type == '(')
3370 if (token.type == ',')
3377 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3379 entity_t *entity = allocate_entity_zero(kind);
3380 entity->base.source_position = *HERE;
3381 entity->base.symbol = symbol;
3382 if (is_declaration(entity)) {
3383 entity->declaration.type = type_error_type;
3384 entity->declaration.implicit = true;
3385 } else if (kind == ENTITY_TYPEDEF) {
3386 entity->typedefe.type = type_error_type;
3388 record_entity(entity, false);
3393 * Finish the construction of a struct type by calculating
3394 * its size, offsets, alignment.
3396 static void finish_struct_type(compound_type_t *type)
3398 assert(type->compound != NULL);
3400 compound_t *compound = type->compound;
3401 if (!compound->complete)
3406 il_alignment_t alignment = 1;
3407 bool need_pad = false;
3409 entity_t *entry = compound->members.entities;
3410 for (; entry != NULL; entry = entry->base.next) {
3411 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3414 type_t *m_type = skip_typeref(entry->declaration.type);
3415 if (! is_type_valid(m_type)) {
3416 /* simply ignore errors here */
3419 il_alignment_t m_alignment = m_type->base.alignment;
3420 if (m_alignment > alignment)
3421 alignment = m_alignment;
3423 offset = (size + m_alignment - 1) & -m_alignment;
3427 entry->compound_member.offset = offset;
3428 size = offset + m_type->base.size;
3430 if (type->base.alignment != 0) {
3431 alignment = type->base.alignment;
3434 offset = (size + alignment - 1) & -alignment;
3438 if (warning.padded && need_pad) {
3439 warningf(&compound->base.source_position,
3440 "'%#T' needs padding", type, compound->base.symbol);
3442 if (warning.packed && !need_pad) {
3443 warningf(&compound->base.source_position,
3444 "superfluous packed attribute on '%#T'",
3445 type, compound->base.symbol);
3448 type->base.size = offset;
3449 type->base.alignment = alignment;
3453 * Finish the construction of an union type by calculating
3454 * its size and alignment.
3456 static void finish_union_type(compound_type_t *type)
3458 assert(type->compound != NULL);
3460 compound_t *compound = type->compound;
3461 if (! compound->complete)
3465 il_alignment_t alignment = 1;
3467 entity_t *entry = compound->members.entities;
3468 for (; entry != NULL; entry = entry->base.next) {
3469 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3472 type_t *m_type = skip_typeref(entry->declaration.type);
3473 if (! is_type_valid(m_type))
3476 entry->compound_member.offset = 0;
3477 if (m_type->base.size > size)
3478 size = m_type->base.size;
3479 if (m_type->base.alignment > alignment)
3480 alignment = m_type->base.alignment;
3482 if (type->base.alignment != 0) {
3483 alignment = type->base.alignment;
3485 size = (size + alignment - 1) & -alignment;
3486 type->base.size = size;
3487 type->base.alignment = alignment;
3490 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3492 type_t *type = NULL;
3493 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3494 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3495 unsigned type_specifiers = 0;
3496 bool newtype = false;
3497 bool saw_error = false;
3498 bool old_gcc_extension = in_gcc_extension;
3500 specifiers->source_position = token.source_position;
3503 specifiers->modifiers
3504 |= parse_attributes(&specifiers->gnu_attributes);
3505 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3506 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3508 switch (token.type) {
3511 #define MATCH_STORAGE_CLASS(token, class) \
3513 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3514 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3516 specifiers->storage_class = class; \
3520 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3521 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3522 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3523 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3524 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3529 add_anchor_token(')');
3530 parse_microsoft_extended_decl_modifier(specifiers);
3531 rem_anchor_token(')');
3536 switch (specifiers->storage_class) {
3537 case STORAGE_CLASS_NONE:
3538 specifiers->storage_class = STORAGE_CLASS_THREAD;
3541 case STORAGE_CLASS_EXTERN:
3542 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3545 case STORAGE_CLASS_STATIC:
3546 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3550 errorf(HERE, "multiple storage classes in declaration specifiers");
3556 /* type qualifiers */
3557 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3559 qualifiers |= qualifier; \
3563 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3564 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3565 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3566 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3567 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3568 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3569 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3570 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3572 case T___extension__:
3574 in_gcc_extension = true;
3577 /* type specifiers */
3578 #define MATCH_SPECIFIER(token, specifier, name) \
3581 if (type_specifiers & specifier) { \
3582 errorf(HERE, "multiple " name " type specifiers given"); \
3584 type_specifiers |= specifier; \
3588 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3589 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3590 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3591 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3592 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3593 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3594 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3595 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3596 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3597 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3598 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3599 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3600 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3601 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3602 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3603 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3604 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3606 case T__forceinline:
3607 /* only in microsoft mode */
3608 specifiers->modifiers |= DM_FORCEINLINE;
3613 specifiers->is_inline = true;
3618 if (type_specifiers & SPECIFIER_LONG_LONG) {
3619 errorf(HERE, "multiple type specifiers given");
3620 } else if (type_specifiers & SPECIFIER_LONG) {
3621 type_specifiers |= SPECIFIER_LONG_LONG;
3623 type_specifiers |= SPECIFIER_LONG;
3628 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3630 type->compound.compound = parse_compound_type_specifier(true);
3631 finish_struct_type(&type->compound);
3635 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3636 type->compound.compound = parse_compound_type_specifier(false);
3637 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3638 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3639 finish_union_type(&type->compound);
3643 type = parse_enum_specifier();
3646 type = parse_typeof();
3648 case T___builtin_va_list:
3649 type = duplicate_type(type_valist);
3653 case T_IDENTIFIER: {
3654 /* only parse identifier if we haven't found a type yet */
3655 if (type != NULL || type_specifiers != 0) {
3656 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3657 * declaration, so it doesn't generate errors about expecting '(' or
3659 switch (look_ahead(1)->type) {
3666 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3669 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3674 goto finish_specifiers;
3678 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3679 if (typedef_type == NULL) {
3680 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3681 * declaration, so it doesn't generate 'implicit int' followed by more
3682 * errors later on. */
3683 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3688 errorf(HERE, "%K does not name a type", &token);
3691 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3693 type = allocate_type_zero(TYPE_TYPEDEF);
3694 type->typedeft.typedefe = &entity->typedefe;
3698 if (la1_type == '*')
3699 goto finish_specifiers;
3704 goto finish_specifiers;
3709 type = typedef_type;
3713 /* function specifier */
3715 goto finish_specifiers;
3720 in_gcc_extension = old_gcc_extension;
3722 if (type == NULL || (saw_error && type_specifiers != 0)) {
3723 atomic_type_kind_t atomic_type;
3725 /* match valid basic types */
3726 switch (type_specifiers) {
3727 case SPECIFIER_VOID:
3728 atomic_type = ATOMIC_TYPE_VOID;
3730 case SPECIFIER_CHAR:
3731 atomic_type = ATOMIC_TYPE_CHAR;
3733 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3734 atomic_type = ATOMIC_TYPE_SCHAR;
3736 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3737 atomic_type = ATOMIC_TYPE_UCHAR;
3739 case SPECIFIER_SHORT:
3740 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3741 case SPECIFIER_SHORT | SPECIFIER_INT:
3742 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3743 atomic_type = ATOMIC_TYPE_SHORT;
3745 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3746 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3747 atomic_type = ATOMIC_TYPE_USHORT;
3750 case SPECIFIER_SIGNED:
3751 case SPECIFIER_SIGNED | SPECIFIER_INT:
3752 atomic_type = ATOMIC_TYPE_INT;
3754 case SPECIFIER_UNSIGNED:
3755 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3756 atomic_type = ATOMIC_TYPE_UINT;
3758 case SPECIFIER_LONG:
3759 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3760 case SPECIFIER_LONG | SPECIFIER_INT:
3761 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3762 atomic_type = ATOMIC_TYPE_LONG;
3764 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3765 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3766 atomic_type = ATOMIC_TYPE_ULONG;
3769 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3770 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3771 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3772 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3774 atomic_type = ATOMIC_TYPE_LONGLONG;
3775 goto warn_about_long_long;
3777 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3778 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3780 atomic_type = ATOMIC_TYPE_ULONGLONG;
3781 warn_about_long_long:
3782 if (warning.long_long) {
3783 warningf(&specifiers->source_position,
3784 "ISO C90 does not support 'long long'");
3788 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3789 atomic_type = unsigned_int8_type_kind;
3792 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3793 atomic_type = unsigned_int16_type_kind;
3796 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3797 atomic_type = unsigned_int32_type_kind;
3800 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3801 atomic_type = unsigned_int64_type_kind;
3804 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3805 atomic_type = unsigned_int128_type_kind;
3808 case SPECIFIER_INT8:
3809 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3810 atomic_type = int8_type_kind;
3813 case SPECIFIER_INT16:
3814 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3815 atomic_type = int16_type_kind;
3818 case SPECIFIER_INT32:
3819 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3820 atomic_type = int32_type_kind;
3823 case SPECIFIER_INT64:
3824 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3825 atomic_type = int64_type_kind;
3828 case SPECIFIER_INT128:
3829 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3830 atomic_type = int128_type_kind;
3833 case SPECIFIER_FLOAT:
3834 atomic_type = ATOMIC_TYPE_FLOAT;
3836 case SPECIFIER_DOUBLE:
3837 atomic_type = ATOMIC_TYPE_DOUBLE;
3839 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3840 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3842 case SPECIFIER_BOOL:
3843 atomic_type = ATOMIC_TYPE_BOOL;
3845 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3846 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3847 atomic_type = ATOMIC_TYPE_FLOAT;
3849 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3850 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3851 atomic_type = ATOMIC_TYPE_DOUBLE;
3853 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3854 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3855 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3858 /* invalid specifier combination, give an error message */
3859 if (type_specifiers == 0) {
3863 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3864 if (!(c_mode & _CXX) && !strict_mode) {
3865 if (warning.implicit_int) {
3866 warningf(HERE, "no type specifiers in declaration, using 'int'");
3868 atomic_type = ATOMIC_TYPE_INT;
3871 errorf(HERE, "no type specifiers given in declaration");
3873 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3874 (type_specifiers & SPECIFIER_UNSIGNED)) {
3875 errorf(HERE, "signed and unsigned specifiers given");
3876 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3877 errorf(HERE, "only integer types can be signed or unsigned");
3879 errorf(HERE, "multiple datatypes in declaration");
3884 if (type_specifiers & SPECIFIER_COMPLEX) {
3885 type = allocate_type_zero(TYPE_COMPLEX);
3886 type->complex.akind = atomic_type;
3887 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3888 type = allocate_type_zero(TYPE_IMAGINARY);
3889 type->imaginary.akind = atomic_type;
3891 type = allocate_type_zero(TYPE_ATOMIC);
3892 type->atomic.akind = atomic_type;
3895 } else if (type_specifiers != 0) {
3896 errorf(HERE, "multiple datatypes in declaration");
3899 /* FIXME: check type qualifiers here */
3901 type->base.qualifiers = qualifiers;
3902 type->base.modifiers = modifiers;
3904 type_t *result = typehash_insert(type);
3905 if (newtype && result != type) {
3909 specifiers->type = result;
3913 specifiers->type = type_error_type;
3917 static type_qualifiers_t parse_type_qualifiers(void)
3919 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3922 switch (token.type) {
3923 /* type qualifiers */
3924 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3925 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3926 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3927 /* microsoft extended type modifiers */
3928 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3929 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3930 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3931 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3932 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3941 * Parses an K&R identifier list
3943 static void parse_identifier_list(scope_t *scope)
3946 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
3947 entity->base.source_position = token.source_position;
3948 entity->base.namespc = NAMESPACE_NORMAL;
3949 entity->base.symbol = token.v.symbol;
3950 /* a K&R parameter has no type, yet */
3953 append_entity(scope, entity);
3955 if (token.type != ',') {
3959 } while (token.type == T_IDENTIFIER);
3962 static type_t *automatic_type_conversion(type_t *orig_type);
3964 static void semantic_parameter(declaration_t *declaration)
3966 /* TODO: improve error messages */
3967 source_position_t const* const pos = &declaration->base.source_position;
3970 switch (declaration->declared_storage_class) {
3971 /* Allowed storage classes */
3972 case STORAGE_CLASS_NONE:
3973 case STORAGE_CLASS_REGISTER:
3977 errorf(pos, "parameter may only have none or register storage class");
3981 type_t *const orig_type = declaration->type;
3982 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3983 * sugar. Turn it into a pointer.
3984 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3985 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3987 type_t *const type = automatic_type_conversion(orig_type);
3988 declaration->type = type;
3990 if (is_type_incomplete(skip_typeref(type))) {
3991 errorf(pos, "parameter '%#T' is of incomplete type",
3992 orig_type, declaration->base.symbol);
3996 static entity_t *parse_parameter(void)
3998 declaration_specifiers_t specifiers;
3999 memset(&specifiers, 0, sizeof(specifiers));
4001 parse_declaration_specifiers(&specifiers);
4003 entity_t *entity = parse_declarator(&specifiers, true, false);
4008 * Parses function type parameters (and optionally creates variable_t entities
4009 * for them in a scope)
4011 static void parse_parameters(function_type_t *type, scope_t *scope)
4014 add_anchor_token(')');
4015 int saved_comma_state = save_and_reset_anchor_state(',');
4017 if (token.type == T_IDENTIFIER &&
4018 !is_typedef_symbol(token.v.symbol)) {
4019 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4020 if (la1_type == ',' || la1_type == ')') {
4021 type->kr_style_parameters = true;
4022 parse_identifier_list(scope);
4023 goto parameters_finished;
4027 if (token.type == ')') {
4028 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4029 if (!(c_mode & _CXX))
4030 type->unspecified_parameters = true;
4031 goto parameters_finished;
4034 function_parameter_t *parameter;
4035 function_parameter_t *last_parameter = NULL;
4038 switch (token.type) {
4041 type->variadic = true;
4042 goto parameters_finished;
4045 case T___extension__:
4048 entity_t *entity = parse_parameter();
4049 if (entity->kind == ENTITY_TYPEDEF) {
4050 errorf(&entity->base.source_position,
4051 "typedef not allowed as function parameter");
4054 assert(is_declaration(entity));
4056 /* func(void) is not a parameter */
4057 if (last_parameter == NULL
4058 && token.type == ')'
4059 && entity->base.symbol == NULL
4060 && skip_typeref(entity->declaration.type) == type_void) {
4061 goto parameters_finished;
4063 semantic_parameter(&entity->declaration);
4065 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4066 memset(parameter, 0, sizeof(parameter[0]));
4067 parameter->type = entity->declaration.type;
4069 if (scope != NULL) {
4070 append_entity(scope, entity);
4073 if (last_parameter != NULL) {
4074 last_parameter->next = parameter;
4076 type->parameters = parameter;
4078 last_parameter = parameter;
4083 goto parameters_finished;
4085 if (token.type != ',') {
4086 goto parameters_finished;
4092 parameters_finished:
4093 rem_anchor_token(')');
4097 restore_anchor_state(',', saved_comma_state);
4100 typedef enum construct_type_kind_t {
4105 } construct_type_kind_t;
4107 typedef struct construct_type_t construct_type_t;
4108 struct construct_type_t {
4109 construct_type_kind_t kind;
4110 construct_type_t *next;
4113 typedef struct parsed_pointer_t parsed_pointer_t;
4114 struct parsed_pointer_t {
4115 construct_type_t construct_type;
4116 type_qualifiers_t type_qualifiers;
4119 typedef struct construct_function_type_t construct_function_type_t;
4120 struct construct_function_type_t {
4121 construct_type_t construct_type;
4122 type_t *function_type;
4125 typedef struct parsed_array_t parsed_array_t;
4126 struct parsed_array_t {
4127 construct_type_t construct_type;
4128 type_qualifiers_t type_qualifiers;
4134 typedef struct construct_base_type_t construct_base_type_t;
4135 struct construct_base_type_t {
4136 construct_type_t construct_type;
4140 static construct_type_t *parse_pointer_declarator(void)
4144 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4145 memset(pointer, 0, sizeof(pointer[0]));
4146 pointer->construct_type.kind = CONSTRUCT_POINTER;
4147 pointer->type_qualifiers = parse_type_qualifiers();
4149 return (construct_type_t*) pointer;
4152 static construct_type_t *parse_array_declarator(void)
4155 add_anchor_token(']');
4157 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4158 memset(array, 0, sizeof(array[0]));
4159 array->construct_type.kind = CONSTRUCT_ARRAY;
4161 if (token.type == T_static) {
4162 array->is_static = true;
4166 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4167 if (type_qualifiers != 0) {
4168 if (token.type == T_static) {
4169 array->is_static = true;
4173 array->type_qualifiers = type_qualifiers;
4175 if (token.type == '*' && look_ahead(1)->type == ']') {
4176 array->is_variable = true;
4178 } else if (token.type != ']') {
4179 array->size = parse_assignment_expression();
4182 rem_anchor_token(']');
4186 return (construct_type_t*) array;
4189 static construct_type_t *parse_function_declarator(scope_t *scope)
4191 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4193 /* TODO: revive this... once we know exactly how to do it */
4195 decl_modifiers_t modifiers = entity->declaration.modifiers;
4197 unsigned mask = modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
4199 if (mask & (mask-1)) {
4200 const char *first = NULL, *second = NULL;
4202 /* more than one calling convention set */
4203 if (modifiers & DM_CDECL) {
4204 if (first == NULL) first = "cdecl";
4205 else if (second == NULL) second = "cdecl";
4207 if (modifiers & DM_STDCALL) {
4208 if (first == NULL) first = "stdcall";
4209 else if (second == NULL) second = "stdcall";
4211 if (modifiers & DM_FASTCALL) {
4212 if (first == NULL) first = "fastcall";
4213 else if (second == NULL) second = "fastcall";
4215 if (modifiers & DM_THISCALL) {
4216 if (first == NULL) first = "thiscall";
4217 else if (second == NULL) second = "thiscall";
4219 errorf(&entity->base.source_position,
4220 "%s and %s attributes are not compatible", first, second);
4223 if (modifiers & DM_CDECL)
4224 type->function.calling_convention = CC_CDECL;
4225 else if (modifiers & DM_STDCALL)
4226 type->function.calling_convention = CC_STDCALL;
4227 else if (modifiers & DM_FASTCALL)
4228 type->function.calling_convention = CC_FASTCALL;
4229 else if (modifiers & DM_THISCALL)
4230 type->function.calling_convention = CC_THISCALL;
4233 parse_parameters(&type->function, scope);
4235 construct_function_type_t *construct_function_type =
4236 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4237 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4238 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4239 construct_function_type->function_type = type;
4241 return &construct_function_type->construct_type;
4244 typedef struct parse_declarator_env_t {
4245 decl_modifiers_t modifiers;
4247 source_position_t source_position;
4249 } parse_declarator_env_t;
4251 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4252 bool may_be_abstract)
4254 /* construct a single linked list of construct_type_t's which describe
4255 * how to construct the final declarator type */
4256 construct_type_t *first = NULL;
4257 construct_type_t *last = NULL;
4258 gnu_attribute_t *attributes = NULL;
4260 decl_modifiers_t modifiers = parse_attributes(&attributes);
4263 while (token.type == '*') {
4264 construct_type_t *type = parse_pointer_declarator();
4274 /* TODO: find out if this is correct */
4275 modifiers |= parse_attributes(&attributes);
4279 env->modifiers |= modifiers;
4281 construct_type_t *inner_types = NULL;
4283 switch (token.type) {
4286 errorf(HERE, "no identifier expected in typename");
4288 env->symbol = token.v.symbol;
4289 env->source_position = token.source_position;
4295 add_anchor_token(')');
4296 inner_types = parse_inner_declarator(env, may_be_abstract);
4297 if (inner_types != NULL) {
4298 /* All later declarators only modify the return type */
4301 rem_anchor_token(')');
4305 if (may_be_abstract)
4307 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4312 construct_type_t *p = last;
4315 construct_type_t *type;
4316 switch (token.type) {
4318 scope_t *scope = NULL;
4320 scope = &env->parameters;
4322 type = parse_function_declarator(scope);
4326 type = parse_array_declarator();
4329 goto declarator_finished;
4332 /* insert in the middle of the list (behind p) */
4334 type->next = p->next;
4345 declarator_finished:
4346 /* append inner_types at the end of the list, we don't to set last anymore
4347 * as it's not needed anymore */
4349 assert(first == NULL);
4350 first = inner_types;
4352 last->next = inner_types;
4360 static void parse_declaration_attributes(entity_t *entity)
4362 gnu_attribute_t *attributes = NULL;
4363 decl_modifiers_t modifiers = parse_attributes(&attributes);
4369 if (entity->kind == ENTITY_TYPEDEF) {
4370 modifiers |= entity->typedefe.modifiers;
4371 type = entity->typedefe.type;
4373 assert(is_declaration(entity));
4374 modifiers |= entity->declaration.modifiers;
4375 type = entity->declaration.type;
4380 /* handle these strange/stupid mode attributes */
4381 gnu_attribute_t *attribute = attributes;
4382 for ( ; attribute != NULL; attribute = attribute->next) {
4383 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4386 atomic_type_kind_t akind = attribute->u.akind;
4387 if (!is_type_signed(type)) {
4389 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4390 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4391 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4392 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4394 panic("invalid akind in mode attribute");
4398 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4399 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4400 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4401 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4403 panic("invalid akind in mode attribute");
4407 type = make_atomic_type(akind, type->base.qualifiers);
4410 type_modifiers_t type_modifiers = type->base.modifiers;
4411 if (modifiers & DM_TRANSPARENT_UNION)
4412 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4414 if (type->base.modifiers != type_modifiers) {
4415 type_t *copy = duplicate_type(type);
4416 copy->base.modifiers = type_modifiers;
4418 type = typehash_insert(copy);
4420 obstack_free(type_obst, copy);
4424 if (entity->kind == ENTITY_TYPEDEF) {
4425 entity->typedefe.type = type;
4426 entity->typedefe.modifiers = modifiers;
4428 entity->declaration.type = type;
4429 entity->declaration.modifiers = modifiers;
4433 static type_t *construct_declarator_type(construct_type_t *construct_list,
4436 construct_type_t *iter = construct_list;
4437 for( ; iter != NULL; iter = iter->next) {
4438 switch (iter->kind) {
4439 case CONSTRUCT_INVALID:
4440 internal_errorf(HERE, "invalid type construction found");
4441 case CONSTRUCT_FUNCTION: {
4442 construct_function_type_t *construct_function_type
4443 = (construct_function_type_t*) iter;
4445 type_t *function_type = construct_function_type->function_type;
4447 function_type->function.return_type = type;
4449 type_t *skipped_return_type = skip_typeref(type);
4451 if (is_type_function(skipped_return_type)) {
4452 errorf(HERE, "function returning function is not allowed");
4453 } else if (is_type_array(skipped_return_type)) {
4454 errorf(HERE, "function returning array is not allowed");
4456 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4458 "type qualifiers in return type of function type are meaningless");
4462 type = function_type;
4466 case CONSTRUCT_POINTER: {
4467 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4468 type = make_pointer_type(type, parsed_pointer->type_qualifiers);
4472 case CONSTRUCT_ARRAY: {
4473 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4474 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4476 expression_t *size_expression = parsed_array->size;
4477 if (size_expression != NULL) {
4479 = create_implicit_cast(size_expression, type_size_t);
4482 array_type->base.qualifiers = parsed_array->type_qualifiers;
4483 array_type->array.element_type = type;
4484 array_type->array.is_static = parsed_array->is_static;
4485 array_type->array.is_variable = parsed_array->is_variable;
4486 array_type->array.size_expression = size_expression;
4488 if (size_expression != NULL) {
4489 if (is_constant_expression(size_expression)) {
4490 array_type->array.size_constant = true;
4491 array_type->array.size
4492 = fold_constant(size_expression);
4494 array_type->array.is_vla = true;
4498 type_t *skipped_type = skip_typeref(type);
4500 if (is_type_incomplete(skipped_type)) {
4501 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4502 } else if (is_type_function(skipped_type)) {
4503 errorf(HERE, "array of functions is not allowed");
4510 type_t *hashed_type = typehash_insert(type);
4511 if (hashed_type != type) {
4512 /* the function type was constructed earlier freeing it here will
4513 * destroy other types... */
4514 if (iter->kind != CONSTRUCT_FUNCTION) {
4524 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4525 bool may_be_abstract,
4526 bool create_compound_member)
4528 parse_declarator_env_t env;
4529 memset(&env, 0, sizeof(env));
4531 construct_type_t *construct_type
4532 = parse_inner_declarator(&env, may_be_abstract);
4533 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4535 if (construct_type != NULL) {
4536 obstack_free(&temp_obst, construct_type);
4540 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4541 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4542 entity->base.symbol = env.symbol;
4543 entity->base.source_position = env.source_position;
4544 entity->typedefe.type = type;
4546 if (create_compound_member) {
4547 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4548 } else if (is_type_function(skip_typeref(type))) {
4549 entity = allocate_entity_zero(ENTITY_FUNCTION);
4551 entity->function.is_inline = specifiers->is_inline;
4552 entity->function.parameters = env.parameters;
4554 entity = allocate_entity_zero(ENTITY_VARIABLE);
4556 entity->variable.get_property_sym = specifiers->get_property_sym;
4557 entity->variable.put_property_sym = specifiers->put_property_sym;
4558 if (specifiers->alignment != 0) {
4559 /* TODO: add checks here */
4560 entity->variable.alignment = specifiers->alignment;
4563 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4564 warningf(&env.source_position,
4565 "variable '%Y' declared 'inline'\n", env.symbol);
4569 entity->base.source_position = env.source_position;
4570 entity->base.symbol = env.symbol;
4571 entity->base.namespc = NAMESPACE_NORMAL;
4572 entity->declaration.type = type;
4573 entity->declaration.modifiers = env.modifiers | specifiers->modifiers;
4574 entity->declaration.deprecated_string = specifiers->deprecated_string;
4576 storage_class_t storage_class = specifiers->storage_class;
4577 entity->declaration.declared_storage_class = storage_class;
4579 if (storage_class == STORAGE_CLASS_NONE && scope != file_scope) {
4580 storage_class = STORAGE_CLASS_AUTO;
4582 entity->declaration.storage_class = storage_class;
4585 parse_declaration_attributes(entity);
4590 static type_t *parse_abstract_declarator(type_t *base_type)
4592 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4594 type_t *result = construct_declarator_type(construct_type, base_type);
4595 if (construct_type != NULL) {
4596 obstack_free(&temp_obst, construct_type);
4603 * Check if the declaration of main is suspicious. main should be a
4604 * function with external linkage, returning int, taking either zero
4605 * arguments, two, or three arguments of appropriate types, ie.
4607 * int main([ int argc, char **argv [, char **env ] ]).
4609 * @param decl the declaration to check
4610 * @param type the function type of the declaration
4612 static void check_type_of_main(const entity_t *entity)
4614 const source_position_t *pos = &entity->base.source_position;
4615 if (entity->kind != ENTITY_FUNCTION) {
4616 warningf(pos, "'main' is not a function");
4620 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4621 warningf(pos, "'main' is normally a non-static function");
4624 type_t *type = skip_typeref(entity->declaration.type);
4625 assert(is_type_function(type));
4627 function_type_t *func_type = &type->function;
4628 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4629 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4630 func_type->return_type);
4632 const function_parameter_t *parm = func_type->parameters;
4634 type_t *const first_type = parm->type;
4635 if (!types_compatible(skip_typeref(first_type), type_int)) {
4637 "first argument of 'main' should be 'int', but is '%T'",
4642 type_t *const second_type = parm->type;
4643 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4644 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4648 type_t *const third_type = parm->type;
4649 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4650 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4654 goto warn_arg_count;
4658 warningf(pos, "'main' takes only zero, two or three arguments");
4664 * Check if a symbol is the equal to "main".
4666 static bool is_sym_main(const symbol_t *const sym)
4668 return strcmp(sym->string, "main") == 0;
4672 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4673 * for various problems that occur for multiple definitions
4675 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4677 const symbol_t *const symbol = entity->base.symbol;
4678 const namespace_t namespc = entity->base.namespc;
4679 const source_position_t *pos = &entity->base.source_position;
4681 assert(symbol != NULL);
4682 entity_t *previous_entity = get_entity(symbol, namespc);
4683 /* pushing the same entity twice will break the stack structure */
4684 assert(previous_entity != entity);
4686 if (entity->kind == ENTITY_FUNCTION) {
4687 type_t *const orig_type = entity->declaration.type;
4688 type_t *const type = skip_typeref(orig_type);
4690 assert(is_type_function(type));
4691 if (type->function.unspecified_parameters &&
4692 warning.strict_prototypes &&
4693 previous_entity == NULL) {
4694 warningf(pos, "function declaration '%#T' is not a prototype",
4698 if (warning.main && scope == file_scope && is_sym_main(symbol)) {
4699 check_type_of_main(entity);
4703 if (is_declaration(entity)) {
4704 if (warning.nested_externs
4705 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4706 && scope != file_scope) {
4707 warningf(pos, "nested extern declaration of '%#T'",
4708 entity->declaration.type, symbol);
4712 if (previous_entity != NULL
4713 && previous_entity->base.parent_scope == ¤t_function->parameters
4714 && scope->depth == previous_entity->base.parent_scope->depth + 1) {
4716 assert(previous_entity->kind == ENTITY_VARIABLE);
4718 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4719 entity->declaration.type, symbol,
4720 previous_entity->declaration.type, symbol,
4721 &previous_entity->base.source_position);
4725 if (previous_entity != NULL
4726 && previous_entity->base.parent_scope == scope) {
4728 if (previous_entity->kind != entity->kind) {
4730 "redeclaration of '%Y' as different kind of symbol (declared %P)",
4731 symbol, &previous_entity->base.source_position);
4734 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4736 "redeclaration of enum entry '%Y' (declared %P)",
4737 symbol, &previous_entity->base.source_position);
4740 if (previous_entity->kind == ENTITY_TYPEDEF) {
4741 /* TODO: C++ allows this for exactly the same type */
4743 "redefinition of typedef '%Y' (declared %P)",
4744 symbol, &previous_entity->base.source_position);
4748 /* at this point we should have only VARIABLES or FUNCTIONS */
4749 assert(is_declaration(previous_entity) && is_declaration(entity));
4751 /* can happen for K&R style declarations */
4752 if (previous_entity->kind == ENTITY_VARIABLE
4753 && previous_entity->declaration.type == NULL
4754 && entity->kind == ENTITY_VARIABLE) {
4755 previous_entity->declaration.type = entity->declaration.type;
4756 previous_entity->declaration.storage_class
4757 = entity->declaration.storage_class;
4758 previous_entity->declaration.declared_storage_class
4759 = entity->declaration.declared_storage_class;
4760 previous_entity->declaration.modifiers
4761 = entity->declaration.modifiers;
4762 previous_entity->declaration.deprecated_string
4763 = entity->declaration.deprecated_string;
4765 assert(entity->declaration.type != NULL);
4767 declaration_t *const previous_declaration
4768 = &previous_entity->declaration;
4769 declaration_t *const declaration = &entity->declaration;
4770 type_t *const orig_type = entity->declaration.type;
4771 type_t *const type = skip_typeref(orig_type);
4773 type_t *prev_type = skip_typeref(previous_declaration->type);
4775 if (!types_compatible(type, prev_type)) {
4777 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4778 orig_type, symbol, previous_declaration->type, symbol,
4779 &previous_entity->base.source_position);
4781 unsigned old_storage_class = previous_declaration->storage_class;
4782 if (warning.redundant_decls && is_definition
4783 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4784 && !(previous_declaration->modifiers & DM_USED)
4785 && !previous_declaration->used) {
4786 warningf(&previous_entity->base.source_position,
4787 "unnecessary static forward declaration for '%#T'",
4788 previous_declaration->type, symbol);
4791 unsigned new_storage_class = declaration->storage_class;
4792 if (is_type_incomplete(prev_type)) {
4793 previous_declaration->type = type;
4797 /* pretend no storage class means extern for function
4798 * declarations (except if the previous declaration is neither
4799 * none nor extern) */
4800 if (entity->kind == ENTITY_FUNCTION) {
4801 if (prev_type->function.unspecified_parameters) {
4802 previous_declaration->type = type;
4806 switch (old_storage_class) {
4807 case STORAGE_CLASS_NONE:
4808 old_storage_class = STORAGE_CLASS_EXTERN;
4811 case STORAGE_CLASS_EXTERN:
4812 if (is_definition) {
4813 if (warning.missing_prototypes &&
4814 prev_type->function.unspecified_parameters &&
4815 !is_sym_main(symbol)) {
4816 warningf(pos, "no previous prototype for '%#T'",
4819 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4820 new_storage_class = STORAGE_CLASS_EXTERN;
4829 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4830 new_storage_class == STORAGE_CLASS_EXTERN) {
4831 warn_redundant_declaration:
4832 if (!is_definition &&
4833 warning.redundant_decls &&
4834 is_type_valid(prev_type) &&
4835 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4837 "redundant declaration for '%Y' (declared %P)",
4838 symbol, &previous_entity->base.source_position);
4840 } else if (current_function == NULL) {
4841 if (old_storage_class != STORAGE_CLASS_STATIC &&
4842 new_storage_class == STORAGE_CLASS_STATIC) {
4844 "static declaration of '%Y' follows non-static declaration (declared %P)",
4845 symbol, &previous_entity->base.source_position);
4846 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4847 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4848 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4850 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4852 goto error_redeclaration;
4853 goto warn_redundant_declaration;
4855 } else if (is_type_valid(prev_type)) {
4856 if (old_storage_class == new_storage_class) {
4857 error_redeclaration:
4858 errorf(pos, "redeclaration of '%Y' (declared %P)",
4859 symbol, &previous_entity->base.source_position);
4862 "redeclaration of '%Y' with different linkage (declared %P)",
4863 symbol, &previous_entity->base.source_position);
4868 previous_declaration->modifiers |= declaration->modifiers;
4869 if (entity->kind == ENTITY_FUNCTION) {
4870 previous_entity->function.is_inline |= entity->function.is_inline;
4872 return previous_entity;
4875 if (entity->kind == ENTITY_FUNCTION) {
4876 if (is_definition &&
4877 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4878 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4879 warningf(pos, "no previous prototype for '%#T'",
4880 entity->declaration.type, symbol);
4881 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4882 warningf(pos, "no previous declaration for '%#T'",
4883 entity->declaration.type, symbol);
4886 } else if (warning.missing_declarations
4887 && entity->kind == ENTITY_VARIABLE
4888 && scope == file_scope) {
4889 declaration_t *declaration = &entity->declaration;
4890 if (declaration->storage_class == STORAGE_CLASS_NONE ||
4891 declaration->storage_class == STORAGE_CLASS_THREAD) {
4892 warningf(pos, "no previous declaration for '%#T'",
4893 declaration->type, symbol);
4898 assert(entity->base.parent_scope == NULL);
4899 assert(scope != NULL);
4901 entity->base.parent_scope = scope;
4902 entity->base.namespc = NAMESPACE_NORMAL;
4903 environment_push(entity);
4904 append_entity(scope, entity);
4909 static void parser_error_multiple_definition(entity_t *entity,
4910 const source_position_t *source_position)
4912 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4913 entity->base.symbol, &entity->base.source_position);
4916 static bool is_declaration_specifier(const token_t *token,
4917 bool only_specifiers_qualifiers)
4919 switch (token->type) {
4924 return is_typedef_symbol(token->v.symbol);
4926 case T___extension__:
4928 return !only_specifiers_qualifiers;
4935 static void parse_init_declarator_rest(entity_t *entity)
4937 assert(is_declaration(entity));
4938 declaration_t *const declaration = &entity->declaration;
4942 type_t *orig_type = declaration->type;
4943 type_t *type = skip_typeref(orig_type);
4945 if (entity->kind == ENTITY_VARIABLE
4946 && entity->variable.initializer != NULL) {
4947 parser_error_multiple_definition(entity, HERE);
4950 bool must_be_constant = false;
4951 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4952 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
4953 entity->base.parent_scope == file_scope) {
4954 must_be_constant = true;
4957 if (is_type_function(type)) {
4958 errorf(&entity->base.source_position,
4959 "function '%#T' is initialized like a variable",
4960 orig_type, entity->base.symbol);
4961 orig_type = type_error_type;
4964 parse_initializer_env_t env;
4965 env.type = orig_type;
4966 env.must_be_constant = must_be_constant;
4967 env.entity = entity;
4968 current_init_decl = entity;
4970 initializer_t *initializer = parse_initializer(&env);
4971 current_init_decl = NULL;
4973 if (entity->kind == ENTITY_VARIABLE) {
4974 /* § 6.7.5 (22) array initializers for arrays with unknown size
4975 * determine the array type size */
4976 declaration->type = env.type;
4977 entity->variable.initializer = initializer;
4981 /* parse rest of a declaration without any declarator */
4982 static void parse_anonymous_declaration_rest(
4983 const declaration_specifiers_t *specifiers)
4987 if (warning.other) {
4988 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
4989 warningf(&specifiers->source_position,
4990 "useless storage class in empty declaration");
4993 type_t *type = specifiers->type;
4994 switch (type->kind) {
4995 case TYPE_COMPOUND_STRUCT:
4996 case TYPE_COMPOUND_UNION: {
4997 if (type->compound.compound->base.symbol == NULL) {
4998 warningf(&specifiers->source_position,
4999 "unnamed struct/union that defines no instances");
5008 warningf(&specifiers->source_position, "empty declaration");
5014 static void parse_declaration_rest(entity_t *ndeclaration,
5015 const declaration_specifiers_t *specifiers,
5016 parsed_declaration_func finished_declaration)
5018 add_anchor_token(';');
5019 add_anchor_token(',');
5021 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5023 if (token.type == '=') {
5024 parse_init_declarator_rest(entity);
5027 if (token.type != ',')
5031 add_anchor_token('=');
5032 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5033 rem_anchor_token('=');
5038 rem_anchor_token(';');
5039 rem_anchor_token(',');
5042 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5044 symbol_t *symbol = entity->base.symbol;
5045 if (symbol == NULL) {
5046 errorf(HERE, "anonymous declaration not valid as function parameter");
5050 assert(entity->base.namespc == NAMESPACE_NORMAL);
5051 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5052 if (previous_entity == NULL
5053 || previous_entity->base.parent_scope != scope) {
5054 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5059 if (is_definition) {
5060 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5063 return record_entity(entity, false);
5066 static void parse_declaration(parsed_declaration_func finished_declaration)
5068 declaration_specifiers_t specifiers;
5069 memset(&specifiers, 0, sizeof(specifiers));
5071 add_anchor_token(';');
5072 parse_declaration_specifiers(&specifiers);
5073 rem_anchor_token(';');
5075 if (token.type == ';') {
5076 parse_anonymous_declaration_rest(&specifiers);
5078 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5079 parse_declaration_rest(entity, &specifiers, finished_declaration);
5083 static type_t *get_default_promoted_type(type_t *orig_type)
5085 type_t *result = orig_type;
5087 type_t *type = skip_typeref(orig_type);
5088 if (is_type_integer(type)) {
5089 result = promote_integer(type);
5090 } else if (type == type_float) {
5091 result = type_double;
5097 static void parse_kr_declaration_list(entity_t *entity)
5099 if (entity->kind != ENTITY_FUNCTION)
5102 type_t *type = skip_typeref(entity->declaration.type);
5103 assert(is_type_function(type));
5104 if (!type->function.kr_style_parameters)
5108 add_anchor_token('{');
5110 /* push function parameters */
5111 size_t const top = environment_top();
5112 scope_push(&entity->function.parameters);
5114 entity_t *parameter = entity->function.parameters.entities;
5115 for ( ; parameter != NULL; parameter = parameter->base.next) {
5116 assert(parameter->base.parent_scope == NULL);
5117 parameter->base.parent_scope = scope;
5118 environment_push(parameter);
5121 /* parse declaration list */
5122 while (is_declaration_specifier(&token, false)) {
5123 parse_declaration(finished_kr_declaration);
5126 /* pop function parameters */
5127 assert(scope == &entity->function.parameters);
5129 environment_pop_to(top);
5131 /* update function type */
5132 type_t *new_type = duplicate_type(type);
5134 function_parameter_t *parameters = NULL;
5135 function_parameter_t *last_parameter = NULL;
5137 entity_t *parameter_declaration = entity->function.parameters.entities;
5138 for( ; parameter_declaration != NULL;
5139 parameter_declaration = parameter_declaration->base.next) {
5140 type_t *parameter_type = parameter_declaration->declaration.type;
5141 if (parameter_type == NULL) {
5143 errorf(HERE, "no type specified for function parameter '%Y'",
5144 parameter_declaration->base.symbol);
5146 if (warning.implicit_int) {
5147 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5148 parameter_declaration->base.symbol);
5150 parameter_type = type_int;
5151 parameter_declaration->declaration.type = parameter_type;
5155 semantic_parameter(¶meter_declaration->declaration);
5156 parameter_type = parameter_declaration->declaration.type;
5159 * we need the default promoted types for the function type
5161 parameter_type = get_default_promoted_type(parameter_type);
5163 function_parameter_t *function_parameter
5164 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5165 memset(function_parameter, 0, sizeof(function_parameter[0]));
5167 function_parameter->type = parameter_type;
5168 if (last_parameter != NULL) {
5169 last_parameter->next = function_parameter;
5171 parameters = function_parameter;
5173 last_parameter = function_parameter;
5176 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5178 new_type->function.parameters = parameters;
5179 new_type->function.unspecified_parameters = true;
5181 type = typehash_insert(new_type);
5182 if (type != new_type) {
5183 obstack_free(type_obst, new_type);
5186 entity->declaration.type = type;
5188 rem_anchor_token('{');
5191 static bool first_err = true;
5194 * When called with first_err set, prints the name of the current function,
5197 static void print_in_function(void)
5201 diagnosticf("%s: In function '%Y':\n",
5202 current_function->base.base.source_position.input_name,
5203 current_function->base.base.symbol);
5208 * Check if all labels are defined in the current function.
5209 * Check if all labels are used in the current function.
5211 static void check_labels(void)
5213 for (const goto_statement_t *goto_statement = goto_first;
5214 goto_statement != NULL;
5215 goto_statement = goto_statement->next) {
5216 /* skip computed gotos */
5217 if (goto_statement->expression != NULL)
5220 label_t *label = goto_statement->label;
5223 if (label->base.source_position.input_name == NULL) {
5224 print_in_function();
5225 errorf(&goto_statement->base.source_position,
5226 "label '%Y' used but not defined", label->base.symbol);
5232 if (warning.unused_label) {
5233 for (const label_statement_t *label_statement = label_first;
5234 label_statement != NULL;
5235 label_statement = label_statement->next) {
5236 label_t *label = label_statement->label;
5238 if (! label->used) {
5239 print_in_function();
5240 warningf(&label_statement->base.source_position,
5241 "label '%Y' defined but not used", label->base.symbol);
5245 label_first = label_last = NULL;
5248 static void warn_unused_decl(entity_t *entity, entity_t *end,
5249 char const *const what)
5251 for (; entity != NULL; entity = entity->base.next) {
5252 if (!is_declaration(entity))
5255 declaration_t *declaration = &entity->declaration;
5256 if (declaration->implicit)
5259 if (!declaration->used) {
5260 print_in_function();
5261 warningf(&entity->base.source_position, "%s '%Y' is unused",
5262 what, entity->base.symbol);
5263 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5264 print_in_function();
5265 warningf(&entity->base.source_position, "%s '%Y' is never read",
5266 what, entity->base.symbol);
5274 static void check_unused_variables(statement_t *const stmt, void *const env)
5278 switch (stmt->kind) {
5279 case STATEMENT_DECLARATION: {
5280 declaration_statement_t const *const decls = &stmt->declaration;
5281 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5287 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5296 * Check declarations of current_function for unused entities.
5298 static void check_declarations(void)
5300 if (warning.unused_parameter) {
5301 const scope_t *scope = ¤t_function->parameters;
5303 /* do not issue unused warnings for main */
5304 if (!is_sym_main(current_function->base.base.symbol)) {
5305 warn_unused_decl(scope->entities, NULL, "parameter");
5308 if (warning.unused_variable) {
5309 walk_statements(current_function->statement, check_unused_variables,
5314 static int determine_truth(expression_t const* const cond)
5317 !is_constant_expression(cond) ? 0 :
5318 fold_constant(cond) != 0 ? 1 :
5322 static bool expression_returns(expression_t const *const expr)
5324 switch (expr->kind) {
5326 expression_t const *const func = expr->call.function;
5327 if (func->kind == EXPR_REFERENCE) {
5328 entity_t *entity = func->reference.entity;
5329 if (entity->kind == ENTITY_FUNCTION
5330 && entity->declaration.modifiers & DM_NORETURN)
5334 if (!expression_returns(func))
5337 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5338 if (!expression_returns(arg->expression))
5345 case EXPR_REFERENCE:
5346 case EXPR_REFERENCE_ENUM_VALUE:
5348 case EXPR_CHARACTER_CONSTANT:
5349 case EXPR_WIDE_CHARACTER_CONSTANT:
5350 case EXPR_STRING_LITERAL:
5351 case EXPR_WIDE_STRING_LITERAL:
5352 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5353 case EXPR_LABEL_ADDRESS:
5354 case EXPR_CLASSIFY_TYPE:
5355 case EXPR_SIZEOF: // TODO handle obscure VLA case
5358 case EXPR_BUILTIN_SYMBOL:
5359 case EXPR_BUILTIN_CONSTANT_P:
5360 case EXPR_BUILTIN_PREFETCH:
5363 case EXPR_STATEMENT: // TODO implement
5366 case EXPR_CONDITIONAL:
5367 // TODO handle constant expression
5369 expression_returns(expr->conditional.condition) && (
5370 expression_returns(expr->conditional.true_expression) ||
5371 expression_returns(expr->conditional.false_expression)
5375 return expression_returns(expr->select.compound);
5377 case EXPR_ARRAY_ACCESS:
5379 expression_returns(expr->array_access.array_ref) &&
5380 expression_returns(expr->array_access.index);
5383 return expression_returns(expr->va_starte.ap);
5386 return expression_returns(expr->va_arge.ap);
5388 EXPR_UNARY_CASES_MANDATORY
5389 return expression_returns(expr->unary.value);
5391 case EXPR_UNARY_THROW:
5395 // TODO handle constant lhs of && and ||
5397 expression_returns(expr->binary.left) &&
5398 expression_returns(expr->binary.right);
5404 panic("unhandled expression");
5407 static bool noreturn_candidate;
5409 static void check_reachable(statement_t *const stmt)
5411 if (stmt->base.reachable)
5413 if (stmt->kind != STATEMENT_DO_WHILE)
5414 stmt->base.reachable = true;
5416 statement_t *last = stmt;
5418 switch (stmt->kind) {
5419 case STATEMENT_INVALID:
5420 case STATEMENT_EMPTY:
5421 case STATEMENT_DECLARATION:
5422 case STATEMENT_LOCAL_LABEL:
5424 next = stmt->base.next;
5427 case STATEMENT_COMPOUND:
5428 next = stmt->compound.statements;
5431 case STATEMENT_RETURN:
5432 noreturn_candidate = false;
5435 case STATEMENT_IF: {
5436 if_statement_t const* const ifs = &stmt->ifs;
5437 int const val = determine_truth(ifs->condition);
5440 check_reachable(ifs->true_statement);
5445 if (ifs->false_statement != NULL) {
5446 check_reachable(ifs->false_statement);
5450 next = stmt->base.next;
5454 case STATEMENT_SWITCH: {
5455 switch_statement_t const *const switchs = &stmt->switchs;
5456 expression_t const *const expr = switchs->expression;
5458 if (is_constant_expression(expr)) {
5459 long const val = fold_constant(expr);
5460 case_label_statement_t * defaults = NULL;
5461 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5462 if (i->expression == NULL) {
5467 if (i->first_case <= val && val <= i->last_case) {
5468 check_reachable((statement_t*)i);
5473 if (defaults != NULL) {
5474 check_reachable((statement_t*)defaults);
5478 bool has_default = false;
5479 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5480 if (i->expression == NULL)
5483 check_reachable((statement_t*)i);
5490 next = stmt->base.next;
5494 case STATEMENT_EXPRESSION: {
5495 /* Check for noreturn function call */
5496 expression_t const *const expr = stmt->expression.expression;
5497 if (!expression_returns(expr))
5500 next = stmt->base.next;
5504 case STATEMENT_CONTINUE: {
5505 statement_t *parent = stmt;
5507 parent = parent->base.parent;
5508 if (parent == NULL) /* continue not within loop */
5512 switch (parent->kind) {
5513 case STATEMENT_WHILE: goto continue_while;
5514 case STATEMENT_DO_WHILE: goto continue_do_while;
5515 case STATEMENT_FOR: goto continue_for;
5522 case STATEMENT_BREAK: {
5523 statement_t *parent = stmt;
5525 parent = parent->base.parent;
5526 if (parent == NULL) /* break not within loop/switch */
5529 switch (parent->kind) {
5530 case STATEMENT_SWITCH:
5531 case STATEMENT_WHILE:
5532 case STATEMENT_DO_WHILE:
5535 next = parent->base.next;
5536 goto found_break_parent;
5545 case STATEMENT_GOTO:
5546 if (stmt->gotos.expression) {
5547 statement_t *parent = stmt->base.parent;
5548 if (parent == NULL) /* top level goto */
5552 next = stmt->gotos.label->statement;
5553 if (next == NULL) /* missing label */
5558 case STATEMENT_LABEL:
5559 next = stmt->label.statement;
5562 case STATEMENT_CASE_LABEL:
5563 next = stmt->case_label.statement;
5566 case STATEMENT_WHILE: {
5567 while_statement_t const *const whiles = &stmt->whiles;
5568 int const val = determine_truth(whiles->condition);
5571 check_reachable(whiles->body);
5576 next = stmt->base.next;
5580 case STATEMENT_DO_WHILE:
5581 next = stmt->do_while.body;
5584 case STATEMENT_FOR: {
5585 for_statement_t *const fors = &stmt->fors;
5587 if (fors->condition_reachable)
5589 fors->condition_reachable = true;
5591 expression_t const *const cond = fors->condition;
5593 cond == NULL ? 1 : determine_truth(cond);
5596 check_reachable(fors->body);
5601 next = stmt->base.next;
5605 case STATEMENT_MS_TRY: {
5606 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5607 check_reachable(ms_try->try_statement);
5608 next = ms_try->final_statement;
5612 case STATEMENT_LEAVE: {
5613 statement_t *parent = stmt;
5615 parent = parent->base.parent;
5616 if (parent == NULL) /* __leave not within __try */
5619 if (parent->kind == STATEMENT_MS_TRY) {
5621 next = parent->ms_try.final_statement;
5629 while (next == NULL) {
5630 next = last->base.parent;
5632 noreturn_candidate = false;
5634 type_t *const type = current_function->base.type;
5635 assert(is_type_function(type));
5636 type_t *const ret = skip_typeref(type->function.return_type);
5637 if (warning.return_type &&
5638 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5639 is_type_valid(ret) &&
5640 !is_sym_main(current_function->base.base.symbol)) {
5641 warningf(&stmt->base.source_position,
5642 "control reaches end of non-void function");
5647 switch (next->kind) {
5648 case STATEMENT_INVALID:
5649 case STATEMENT_EMPTY:
5650 case STATEMENT_DECLARATION:
5651 case STATEMENT_LOCAL_LABEL:
5652 case STATEMENT_EXPRESSION:
5654 case STATEMENT_RETURN:
5655 case STATEMENT_CONTINUE:
5656 case STATEMENT_BREAK:
5657 case STATEMENT_GOTO:
5658 case STATEMENT_LEAVE:
5659 panic("invalid control flow in function");
5661 case STATEMENT_COMPOUND:
5663 case STATEMENT_SWITCH:
5664 case STATEMENT_LABEL:
5665 case STATEMENT_CASE_LABEL:
5667 next = next->base.next;
5670 case STATEMENT_WHILE: {
5672 if (next->base.reachable)
5674 next->base.reachable = true;
5676 while_statement_t const *const whiles = &next->whiles;
5677 int const val = determine_truth(whiles->condition);
5680 check_reachable(whiles->body);
5686 next = next->base.next;
5690 case STATEMENT_DO_WHILE: {
5692 if (next->base.reachable)
5694 next->base.reachable = true;
5696 do_while_statement_t const *const dw = &next->do_while;
5697 int const val = determine_truth(dw->condition);
5700 check_reachable(dw->body);
5706 next = next->base.next;
5710 case STATEMENT_FOR: {
5712 for_statement_t *const fors = &next->fors;
5714 fors->step_reachable = true;
5716 if (fors->condition_reachable)
5718 fors->condition_reachable = true;
5720 expression_t const *const cond = fors->condition;
5722 cond == NULL ? 1 : determine_truth(cond);
5725 check_reachable(fors->body);
5731 next = next->base.next;
5735 case STATEMENT_MS_TRY:
5737 next = next->ms_try.final_statement;
5742 check_reachable(next);
5745 static void check_unreachable(statement_t* const stmt, void *const env)
5749 switch (stmt->kind) {
5750 case STATEMENT_DO_WHILE:
5751 if (!stmt->base.reachable) {
5752 expression_t const *const cond = stmt->do_while.condition;
5753 if (determine_truth(cond) >= 0) {
5754 warningf(&cond->base.source_position,
5755 "condition of do-while-loop is unreachable");
5760 case STATEMENT_FOR: {
5761 for_statement_t const* const fors = &stmt->fors;
5763 // if init and step are unreachable, cond is unreachable, too
5764 if (!stmt->base.reachable && !fors->step_reachable) {
5765 warningf(&stmt->base.source_position, "statement is unreachable");
5767 if (!stmt->base.reachable && fors->initialisation != NULL) {
5768 warningf(&fors->initialisation->base.source_position,
5769 "initialisation of for-statement is unreachable");
5772 if (!fors->condition_reachable && fors->condition != NULL) {
5773 warningf(&fors->condition->base.source_position,
5774 "condition of for-statement is unreachable");
5777 if (!fors->step_reachable && fors->step != NULL) {
5778 warningf(&fors->step->base.source_position,
5779 "step of for-statement is unreachable");
5785 case STATEMENT_COMPOUND:
5786 if (stmt->compound.statements != NULL)
5791 if (!stmt->base.reachable)
5792 warningf(&stmt->base.source_position, "statement is unreachable");
5797 static void parse_external_declaration(void)
5799 /* function-definitions and declarations both start with declaration
5801 declaration_specifiers_t specifiers;
5802 memset(&specifiers, 0, sizeof(specifiers));
5804 add_anchor_token(';');
5805 parse_declaration_specifiers(&specifiers);
5806 rem_anchor_token(';');
5808 /* must be a declaration */
5809 if (token.type == ';') {
5810 parse_anonymous_declaration_rest(&specifiers);
5814 add_anchor_token(',');
5815 add_anchor_token('=');
5816 add_anchor_token(';');
5817 add_anchor_token('{');
5819 /* declarator is common to both function-definitions and declarations */
5820 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5822 rem_anchor_token('{');
5823 rem_anchor_token(';');
5824 rem_anchor_token('=');
5825 rem_anchor_token(',');
5827 /* must be a declaration */
5828 switch (token.type) {
5832 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
5836 /* must be a function definition */
5837 parse_kr_declaration_list(ndeclaration);
5839 if (token.type != '{') {
5840 parse_error_expected("while parsing function definition", '{', NULL);
5841 eat_until_matching_token(';');
5845 assert(is_declaration(ndeclaration));
5846 type_t *type = ndeclaration->declaration.type;
5848 /* note that we don't skip typerefs: the standard doesn't allow them here
5849 * (so we can't use is_type_function here) */
5850 if (type->kind != TYPE_FUNCTION) {
5851 if (is_type_valid(type)) {
5852 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5853 type, ndeclaration->base.symbol);
5859 if (warning.aggregate_return &&
5860 is_type_compound(skip_typeref(type->function.return_type))) {
5861 warningf(HERE, "function '%Y' returns an aggregate",
5862 ndeclaration->base.symbol);
5864 if (warning.traditional && !type->function.unspecified_parameters) {
5865 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5866 ndeclaration->base.symbol);
5868 if (warning.old_style_definition && type->function.unspecified_parameters) {
5869 warningf(HERE, "old-style function definition '%Y'",
5870 ndeclaration->base.symbol);
5873 /* § 6.7.5.3 (14) a function definition with () means no
5874 * parameters (and not unspecified parameters) */
5875 if (type->function.unspecified_parameters
5876 && type->function.parameters == NULL
5877 && !type->function.kr_style_parameters) {
5878 type_t *duplicate = duplicate_type(type);
5879 duplicate->function.unspecified_parameters = false;
5881 type = typehash_insert(duplicate);
5882 if (type != duplicate) {
5883 obstack_free(type_obst, duplicate);
5885 ndeclaration->declaration.type = type;
5888 entity_t *const entity = record_entity(ndeclaration, true);
5889 assert(entity->kind == ENTITY_FUNCTION);
5890 assert(ndeclaration->kind == ENTITY_FUNCTION);
5892 function_t *function = &entity->function;
5893 if (ndeclaration != entity) {
5894 function->parameters = ndeclaration->function.parameters;
5896 assert(is_declaration(entity));
5897 type = skip_typeref(entity->declaration.type);
5899 /* push function parameters and switch scope */
5900 size_t const top = environment_top();
5901 scope_push(&function->parameters);
5903 entity_t *parameter = function->parameters.entities;
5904 for( ; parameter != NULL; parameter = parameter->base.next) {
5905 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5906 parameter->base.parent_scope = scope;
5908 assert(parameter->base.parent_scope == NULL
5909 || parameter->base.parent_scope == scope);
5910 parameter->base.parent_scope = scope;
5911 if (parameter->base.symbol == NULL) {
5912 errorf(¶meter->base.source_position, "parameter name omitted");
5915 environment_push(parameter);
5918 if (function->statement != NULL) {
5919 parser_error_multiple_definition(entity, HERE);
5922 /* parse function body */
5923 int label_stack_top = label_top();
5924 function_t *old_current_function = current_function;
5925 current_function = function;
5926 current_parent = NULL;
5928 statement_t *const body = parse_compound_statement(false);
5929 function->statement = body;
5932 check_declarations();
5933 if (warning.return_type ||
5934 warning.unreachable_code ||
5935 (warning.missing_noreturn
5936 && !(function->base.modifiers & DM_NORETURN))) {
5937 noreturn_candidate = true;
5938 check_reachable(body);
5939 if (warning.unreachable_code)
5940 walk_statements(body, check_unreachable, NULL);
5941 if (warning.missing_noreturn &&
5942 noreturn_candidate &&
5943 !(function->base.modifiers & DM_NORETURN)) {
5944 warningf(&body->base.source_position,
5945 "function '%#T' is candidate for attribute 'noreturn'",
5946 type, entity->base.symbol);
5950 assert(current_parent == NULL);
5951 assert(current_function == function);
5952 current_function = old_current_function;
5953 label_pop_to(label_stack_top);
5956 assert(scope == &function->parameters);
5958 environment_pop_to(top);
5961 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5962 source_position_t *source_position,
5963 const symbol_t *symbol)
5965 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5967 type->bitfield.base_type = base_type;
5968 type->bitfield.size_expression = size;
5971 type_t *skipped_type = skip_typeref(base_type);
5972 if (!is_type_integer(skipped_type)) {
5973 errorf(HERE, "bitfield base type '%T' is not an integer type",
5977 bit_size = skipped_type->base.size * 8;
5980 if (is_constant_expression(size)) {
5981 long v = fold_constant(size);
5984 errorf(source_position, "negative width in bit-field '%Y'",
5986 } else if (v == 0) {
5987 errorf(source_position, "zero width for bit-field '%Y'",
5989 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5990 errorf(source_position, "width of '%Y' exceeds its type",
5993 type->bitfield.bit_size = v;
6000 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6002 entity_t *iter = compound->members.entities;
6003 for( ; iter != NULL; iter = iter->base.next) {
6004 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6007 if (iter->base.symbol == NULL) {
6008 type_t *type = skip_typeref(iter->declaration.type);
6009 if (is_type_compound(type)) {
6011 = find_compound_entry(type->compound.compound, symbol);
6018 if (iter->base.symbol == symbol) {
6026 static void parse_compound_declarators(compound_t *compound,
6027 const declaration_specifiers_t *specifiers)
6032 if (token.type == ':') {
6033 source_position_t source_position = *HERE;
6036 type_t *base_type = specifiers->type;
6037 expression_t *size = parse_constant_expression();
6039 type_t *type = make_bitfield_type(base_type, size,
6040 &source_position, sym_anonymous);
6042 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6043 entity->base.namespc = NAMESPACE_NORMAL;
6044 entity->base.source_position = source_position;
6045 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6046 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6047 entity->declaration.modifiers = specifiers->modifiers;
6048 entity->declaration.type = type;
6050 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6051 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6053 if (token.type == ':') {
6054 source_position_t source_position = *HERE;
6056 expression_t *size = parse_constant_expression();
6058 type_t *type = entity->declaration.type;
6059 type_t *bitfield_type = make_bitfield_type(type, size,
6060 &source_position, entity->base.symbol);
6061 entity->declaration.type = bitfield_type;
6065 /* make sure we don't define a symbol multiple times */
6066 symbol_t *symbol = entity->base.symbol;
6067 if (symbol != NULL) {
6068 entity_t *prev = find_compound_entry(compound, symbol);
6071 assert(prev->base.symbol == symbol);
6072 errorf(&entity->base.source_position,
6073 "multiple declarations of symbol '%Y' (declared %P)",
6074 symbol, &prev->base.source_position);
6078 append_entity(&compound->members, entity);
6080 if (token.type != ',')
6090 static void semantic_compound(compound_t *compound)
6092 entity_t *entity = compound->members.entities;
6093 for ( ; entity != NULL; entity = entity->base.next) {
6094 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6096 type_t *orig_type = entity->declaration.type;
6097 type_t *type = skip_typeref(orig_type);
6099 if (is_type_function(type)) {
6101 "compound member '%Y' must not have function type '%T'",
6102 entity->base.symbol, orig_type);
6103 } else if (is_type_incomplete(type)) {
6104 /* §6.7.2.1 (16) flexible array member */
6105 if (is_type_array(type) && entity->base.next == NULL) {
6106 compound->has_flexible_member = true;
6109 "compound member '%Y' has incomplete type '%T'",
6110 entity->base.symbol, orig_type);
6116 static void parse_compound_type_entries(compound_t *compound)
6119 add_anchor_token('}');
6121 while (token.type != '}') {
6122 if (token.type == T_EOF) {
6123 errorf(HERE, "EOF while parsing struct");
6126 declaration_specifiers_t specifiers;
6127 memset(&specifiers, 0, sizeof(specifiers));
6128 parse_declaration_specifiers(&specifiers);
6130 parse_compound_declarators(compound, &specifiers);
6132 semantic_compound(compound);
6133 rem_anchor_token('}');
6137 static type_t *parse_typename(void)
6139 declaration_specifiers_t specifiers;
6140 memset(&specifiers, 0, sizeof(specifiers));
6141 parse_declaration_specifiers(&specifiers);
6142 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6143 /* TODO: improve error message, user does probably not know what a
6144 * storage class is...
6146 errorf(HERE, "typename may not have a storage class");
6149 type_t *result = parse_abstract_declarator(specifiers.type);
6157 typedef expression_t* (*parse_expression_function)(void);
6158 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6160 typedef struct expression_parser_function_t expression_parser_function_t;
6161 struct expression_parser_function_t {
6162 parse_expression_function parser;
6163 unsigned infix_precedence;
6164 parse_expression_infix_function infix_parser;
6167 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6170 * Prints an error message if an expression was expected but not read
6172 static expression_t *expected_expression_error(void)
6174 /* skip the error message if the error token was read */
6175 if (token.type != T_ERROR) {
6176 errorf(HERE, "expected expression, got token '%K'", &token);
6180 return create_invalid_expression();
6184 * Parse a string constant.
6186 static expression_t *parse_string_const(void)
6189 if (token.type == T_STRING_LITERAL) {
6190 string_t res = token.v.string;
6192 while (token.type == T_STRING_LITERAL) {
6193 res = concat_strings(&res, &token.v.string);
6196 if (token.type != T_WIDE_STRING_LITERAL) {
6197 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6198 /* note: that we use type_char_ptr here, which is already the
6199 * automatic converted type. revert_automatic_type_conversion
6200 * will construct the array type */
6201 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6202 cnst->string.value = res;
6206 wres = concat_string_wide_string(&res, &token.v.wide_string);
6208 wres = token.v.wide_string;
6213 switch (token.type) {
6214 case T_WIDE_STRING_LITERAL:
6215 wres = concat_wide_strings(&wres, &token.v.wide_string);
6218 case T_STRING_LITERAL:
6219 wres = concat_wide_string_string(&wres, &token.v.string);
6223 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6224 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6225 cnst->wide_string.value = wres;
6234 * Parse a boolean constant.
6236 static expression_t *parse_bool_const(bool value)
6238 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6239 cnst->base.type = type_bool;
6240 cnst->conste.v.int_value = value;
6248 * Parse an integer constant.
6250 static expression_t *parse_int_const(void)
6252 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6253 cnst->base.type = token.datatype;
6254 cnst->conste.v.int_value = token.v.intvalue;
6262 * Parse a character constant.
6264 static expression_t *parse_character_constant(void)
6266 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6267 cnst->base.type = token.datatype;
6268 cnst->conste.v.character = token.v.string;
6270 if (cnst->conste.v.character.size != 1) {
6271 if (warning.multichar && GNU_MODE) {
6272 warningf(HERE, "multi-character character constant");
6274 errorf(HERE, "more than 1 characters in character constant");
6283 * Parse a wide character constant.
6285 static expression_t *parse_wide_character_constant(void)
6287 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6288 cnst->base.type = token.datatype;
6289 cnst->conste.v.wide_character = token.v.wide_string;
6291 if (cnst->conste.v.wide_character.size != 1) {
6292 if (warning.multichar && GNU_MODE) {
6293 warningf(HERE, "multi-character character constant");
6295 errorf(HERE, "more than 1 characters in character constant");
6304 * Parse a float constant.
6306 static expression_t *parse_float_const(void)
6308 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6309 cnst->base.type = token.datatype;
6310 cnst->conste.v.float_value = token.v.floatvalue;
6317 static entity_t *create_implicit_function(symbol_t *symbol,
6318 const source_position_t *source_position)
6320 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6321 ntype->function.return_type = type_int;
6322 ntype->function.unspecified_parameters = true;
6324 type_t *type = typehash_insert(ntype);
6325 if (type != ntype) {
6329 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6330 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6331 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6332 entity->declaration.type = type;
6333 entity->declaration.implicit = true;
6334 entity->base.symbol = symbol;
6335 entity->base.source_position = *source_position;
6337 bool strict_prototypes_old = warning.strict_prototypes;
6338 warning.strict_prototypes = false;
6339 record_entity(entity, false);
6340 warning.strict_prototypes = strict_prototypes_old;
6346 * Creates a return_type (func)(argument_type) function type if not
6349 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6350 type_t *argument_type2)
6352 function_parameter_t *parameter2
6353 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6354 memset(parameter2, 0, sizeof(parameter2[0]));
6355 parameter2->type = argument_type2;
6357 function_parameter_t *parameter1
6358 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6359 memset(parameter1, 0, sizeof(parameter1[0]));
6360 parameter1->type = argument_type1;
6361 parameter1->next = parameter2;
6363 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6364 type->function.return_type = return_type;
6365 type->function.parameters = parameter1;
6367 type_t *result = typehash_insert(type);
6368 if (result != type) {
6376 * Creates a return_type (func)(argument_type) function type if not
6379 * @param return_type the return type
6380 * @param argument_type the argument type
6382 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6384 function_parameter_t *parameter
6385 = obstack_alloc(type_obst, sizeof(parameter[0]));
6386 memset(parameter, 0, sizeof(parameter[0]));
6387 parameter->type = argument_type;
6389 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6390 type->function.return_type = return_type;
6391 type->function.parameters = parameter;
6393 type_t *result = typehash_insert(type);
6394 if (result != type) {
6401 static type_t *make_function_0_type(type_t *return_type)
6403 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6404 type->function.return_type = return_type;
6405 type->function.parameters = NULL;
6407 type_t *result = typehash_insert(type);
6408 if (result != type) {
6416 * Creates a function type for some function like builtins.
6418 * @param symbol the symbol describing the builtin
6420 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6422 switch (symbol->ID) {
6423 case T___builtin_alloca:
6424 return make_function_1_type(type_void_ptr, type_size_t);
6425 case T___builtin_huge_val:
6426 return make_function_0_type(type_double);
6427 case T___builtin_inf:
6428 return make_function_0_type(type_double);
6429 case T___builtin_inff:
6430 return make_function_0_type(type_float);
6431 case T___builtin_infl:
6432 return make_function_0_type(type_long_double);
6433 case T___builtin_nan:
6434 return make_function_1_type(type_double, type_char_ptr);
6435 case T___builtin_nanf:
6436 return make_function_1_type(type_float, type_char_ptr);
6437 case T___builtin_nanl:
6438 return make_function_1_type(type_long_double, type_char_ptr);
6439 case T___builtin_va_end:
6440 return make_function_1_type(type_void, type_valist);
6441 case T___builtin_expect:
6442 return make_function_2_type(type_long, type_long, type_long);
6444 internal_errorf(HERE, "not implemented builtin symbol found");
6449 * Performs automatic type cast as described in § 6.3.2.1.
6451 * @param orig_type the original type
6453 static type_t *automatic_type_conversion(type_t *orig_type)
6455 type_t *type = skip_typeref(orig_type);
6456 if (is_type_array(type)) {
6457 array_type_t *array_type = &type->array;
6458 type_t *element_type = array_type->element_type;
6459 unsigned qualifiers = array_type->base.qualifiers;
6461 return make_pointer_type(element_type, qualifiers);
6464 if (is_type_function(type)) {
6465 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6472 * reverts the automatic casts of array to pointer types and function
6473 * to function-pointer types as defined § 6.3.2.1
6475 type_t *revert_automatic_type_conversion(const expression_t *expression)
6477 switch (expression->kind) {
6478 case EXPR_REFERENCE: {
6479 entity_t *entity = expression->reference.entity;
6480 if (is_declaration(entity)) {
6481 return entity->declaration.type;
6482 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6483 return entity->enum_value.enum_type;
6485 panic("no declaration or enum in reference");
6490 entity_t *entity = expression->select.compound_entry;
6491 assert(is_declaration(entity));
6492 type_t *type = entity->declaration.type;
6493 return get_qualified_type(type,
6494 expression->base.type->base.qualifiers);
6497 case EXPR_UNARY_DEREFERENCE: {
6498 const expression_t *const value = expression->unary.value;
6499 type_t *const type = skip_typeref(value->base.type);
6500 assert(is_type_pointer(type));
6501 return type->pointer.points_to;
6504 case EXPR_BUILTIN_SYMBOL:
6505 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6507 case EXPR_ARRAY_ACCESS: {
6508 const expression_t *array_ref = expression->array_access.array_ref;
6509 type_t *type_left = skip_typeref(array_ref->base.type);
6510 if (!is_type_valid(type_left))
6512 assert(is_type_pointer(type_left));
6513 return type_left->pointer.points_to;
6516 case EXPR_STRING_LITERAL: {
6517 size_t size = expression->string.value.size;
6518 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6521 case EXPR_WIDE_STRING_LITERAL: {
6522 size_t size = expression->wide_string.value.size;
6523 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6526 case EXPR_COMPOUND_LITERAL:
6527 return expression->compound_literal.type;
6532 return expression->base.type;
6535 static expression_t *parse_reference(void)
6537 symbol_t *const symbol = token.v.symbol;
6539 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6541 if (entity == NULL) {
6542 if (!strict_mode && look_ahead(1)->type == '(') {
6543 /* an implicitly declared function */
6544 if (warning.implicit_function_declaration) {
6545 warningf(HERE, "implicit declaration of function '%Y'",
6549 entity = create_implicit_function(symbol, HERE);
6551 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6552 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6558 if (is_declaration(entity)) {
6559 orig_type = entity->declaration.type;
6560 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6561 orig_type = entity->enum_value.enum_type;
6562 } else if (entity->kind == ENTITY_TYPEDEF) {
6563 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6566 return create_invalid_expression();
6568 panic("expected declaration or enum value in reference");
6571 /* we always do the auto-type conversions; the & and sizeof parser contains
6572 * code to revert this! */
6573 type_t *type = automatic_type_conversion(orig_type);
6575 expression_kind_t kind = EXPR_REFERENCE;
6576 if (entity->kind == ENTITY_ENUM_VALUE)
6577 kind = EXPR_REFERENCE_ENUM_VALUE;
6579 expression_t *expression = allocate_expression_zero(kind);
6580 expression->reference.entity = entity;
6581 expression->base.type = type;
6583 /* this declaration is used */
6584 if (is_declaration(entity)) {
6585 entity->declaration.used = true;
6588 if (entity->base.parent_scope != file_scope
6589 && entity->base.parent_scope->depth < current_function->parameters.depth
6590 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6591 if (entity->kind == ENTITY_VARIABLE) {
6592 /* access of a variable from an outer function */
6593 entity->variable.address_taken = true;
6595 current_function->need_closure = true;
6598 /* check for deprecated functions */
6599 if (warning.deprecated_declarations
6600 && is_declaration(entity)
6601 && entity->declaration.modifiers & DM_DEPRECATED) {
6602 declaration_t *declaration = &entity->declaration;
6604 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6605 "function" : "variable";
6607 if (declaration->deprecated_string != NULL) {
6608 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6609 prefix, entity->base.symbol, &entity->base.source_position,
6610 declaration->deprecated_string);
6612 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6613 entity->base.symbol, &entity->base.source_position);
6617 if (warning.init_self && entity == current_init_decl && !in_type_prop
6618 && entity->kind == ENTITY_VARIABLE) {
6619 current_init_decl = NULL;
6620 warningf(HERE, "variable '%#T' is initialized by itself",
6621 entity->declaration.type, entity->base.symbol);
6628 static bool semantic_cast(expression_t *cast)
6630 expression_t *expression = cast->unary.value;
6631 type_t *orig_dest_type = cast->base.type;
6632 type_t *orig_type_right = expression->base.type;
6633 type_t const *dst_type = skip_typeref(orig_dest_type);
6634 type_t const *src_type = skip_typeref(orig_type_right);
6635 source_position_t const *pos = &cast->base.source_position;
6637 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6638 if (dst_type == type_void)
6641 /* only integer and pointer can be casted to pointer */
6642 if (is_type_pointer(dst_type) &&
6643 !is_type_pointer(src_type) &&
6644 !is_type_integer(src_type) &&
6645 is_type_valid(src_type)) {
6646 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6650 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6651 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6655 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6656 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6660 if (warning.cast_qual &&
6661 is_type_pointer(src_type) &&
6662 is_type_pointer(dst_type)) {
6663 type_t *src = skip_typeref(src_type->pointer.points_to);
6664 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6665 unsigned missing_qualifiers =
6666 src->base.qualifiers & ~dst->base.qualifiers;
6667 if (missing_qualifiers != 0) {
6669 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6670 missing_qualifiers, orig_type_right);
6676 static expression_t *parse_compound_literal(type_t *type)
6678 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6680 parse_initializer_env_t env;
6683 env.must_be_constant = false;
6684 initializer_t *initializer = parse_initializer(&env);
6687 expression->compound_literal.initializer = initializer;
6688 expression->compound_literal.type = type;
6689 expression->base.type = automatic_type_conversion(type);
6695 * Parse a cast expression.
6697 static expression_t *parse_cast(void)
6699 add_anchor_token(')');
6701 source_position_t source_position = token.source_position;
6703 type_t *type = parse_typename();
6705 rem_anchor_token(')');
6708 if (token.type == '{') {
6709 return parse_compound_literal(type);
6712 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6713 cast->base.source_position = source_position;
6715 expression_t *value = parse_sub_expression(PREC_CAST);
6716 cast->base.type = type;
6717 cast->unary.value = value;
6719 if (! semantic_cast(cast)) {
6720 /* TODO: record the error in the AST. else it is impossible to detect it */
6725 return create_invalid_expression();
6729 * Parse a statement expression.
6731 static expression_t *parse_statement_expression(void)
6733 add_anchor_token(')');
6735 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6737 statement_t *statement = parse_compound_statement(true);
6738 expression->statement.statement = statement;
6740 /* find last statement and use its type */
6741 type_t *type = type_void;
6742 const statement_t *stmt = statement->compound.statements;
6744 while (stmt->base.next != NULL)
6745 stmt = stmt->base.next;
6747 if (stmt->kind == STATEMENT_EXPRESSION) {
6748 type = stmt->expression.expression->base.type;
6750 } else if (warning.other) {
6751 warningf(&expression->base.source_position, "empty statement expression ({})");
6753 expression->base.type = type;
6755 rem_anchor_token(')');
6763 * Parse a parenthesized expression.
6765 static expression_t *parse_parenthesized_expression(void)
6769 switch (token.type) {
6771 /* gcc extension: a statement expression */
6772 return parse_statement_expression();
6776 return parse_cast();
6778 if (is_typedef_symbol(token.v.symbol)) {
6779 return parse_cast();
6783 add_anchor_token(')');
6784 expression_t *result = parse_expression();
6785 rem_anchor_token(')');
6792 static expression_t *parse_function_keyword(void)
6796 if (current_function == NULL) {
6797 errorf(HERE, "'__func__' used outside of a function");
6800 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6801 expression->base.type = type_char_ptr;
6802 expression->funcname.kind = FUNCNAME_FUNCTION;
6809 static expression_t *parse_pretty_function_keyword(void)
6811 if (current_function == NULL) {
6812 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6815 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6816 expression->base.type = type_char_ptr;
6817 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6819 eat(T___PRETTY_FUNCTION__);
6824 static expression_t *parse_funcsig_keyword(void)
6826 if (current_function == NULL) {
6827 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6830 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6831 expression->base.type = type_char_ptr;
6832 expression->funcname.kind = FUNCNAME_FUNCSIG;
6839 static expression_t *parse_funcdname_keyword(void)
6841 if (current_function == NULL) {
6842 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6845 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6846 expression->base.type = type_char_ptr;
6847 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6849 eat(T___FUNCDNAME__);
6854 static designator_t *parse_designator(void)
6856 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6857 result->source_position = *HERE;
6859 if (token.type != T_IDENTIFIER) {
6860 parse_error_expected("while parsing member designator",
6861 T_IDENTIFIER, NULL);
6864 result->symbol = token.v.symbol;
6867 designator_t *last_designator = result;
6869 if (token.type == '.') {
6871 if (token.type != T_IDENTIFIER) {
6872 parse_error_expected("while parsing member designator",
6873 T_IDENTIFIER, NULL);
6876 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6877 designator->source_position = *HERE;
6878 designator->symbol = token.v.symbol;
6881 last_designator->next = designator;
6882 last_designator = designator;
6885 if (token.type == '[') {
6887 add_anchor_token(']');
6888 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6889 designator->source_position = *HERE;
6890 designator->array_index = parse_expression();
6891 rem_anchor_token(']');
6893 if (designator->array_index == NULL) {
6897 last_designator->next = designator;
6898 last_designator = designator;
6910 * Parse the __builtin_offsetof() expression.
6912 static expression_t *parse_offsetof(void)
6914 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6915 expression->base.type = type_size_t;
6917 eat(T___builtin_offsetof);
6920 add_anchor_token(',');
6921 type_t *type = parse_typename();
6922 rem_anchor_token(',');
6924 add_anchor_token(')');
6925 designator_t *designator = parse_designator();
6926 rem_anchor_token(')');
6929 expression->offsetofe.type = type;
6930 expression->offsetofe.designator = designator;
6933 memset(&path, 0, sizeof(path));
6934 path.top_type = type;
6935 path.path = NEW_ARR_F(type_path_entry_t, 0);
6937 descend_into_subtype(&path);
6939 if (!walk_designator(&path, designator, true)) {
6940 return create_invalid_expression();
6943 DEL_ARR_F(path.path);
6947 return create_invalid_expression();
6951 * Parses a _builtin_va_start() expression.
6953 static expression_t *parse_va_start(void)
6955 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6957 eat(T___builtin_va_start);
6960 add_anchor_token(',');
6961 expression->va_starte.ap = parse_assignment_expression();
6962 rem_anchor_token(',');
6964 expression_t *const expr = parse_assignment_expression();
6965 if (expr->kind == EXPR_REFERENCE) {
6966 entity_t *const entity = expr->reference.entity;
6967 if (entity->base.parent_scope != ¤t_function->parameters
6968 || entity->base.next != NULL
6969 || entity->kind != ENTITY_VARIABLE) {
6970 errorf(&expr->base.source_position,
6971 "second argument of 'va_start' must be last parameter of the current function");
6973 expression->va_starte.parameter = &entity->variable;
6980 return create_invalid_expression();
6984 * Parses a _builtin_va_arg() expression.
6986 static expression_t *parse_va_arg(void)
6988 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6990 eat(T___builtin_va_arg);
6993 expression->va_arge.ap = parse_assignment_expression();
6995 expression->base.type = parse_typename();
7000 return create_invalid_expression();
7003 static expression_t *parse_builtin_symbol(void)
7005 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7007 symbol_t *symbol = token.v.symbol;
7009 expression->builtin_symbol.symbol = symbol;
7012 type_t *type = get_builtin_symbol_type(symbol);
7013 type = automatic_type_conversion(type);
7015 expression->base.type = type;
7020 * Parses a __builtin_constant() expression.
7022 static expression_t *parse_builtin_constant(void)
7024 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7026 eat(T___builtin_constant_p);
7029 add_anchor_token(')');
7030 expression->builtin_constant.value = parse_assignment_expression();
7031 rem_anchor_token(')');
7033 expression->base.type = type_int;
7037 return create_invalid_expression();
7041 * Parses a __builtin_prefetch() expression.
7043 static expression_t *parse_builtin_prefetch(void)
7045 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7047 eat(T___builtin_prefetch);
7050 add_anchor_token(')');
7051 expression->builtin_prefetch.adr = parse_assignment_expression();
7052 if (token.type == ',') {
7054 expression->builtin_prefetch.rw = parse_assignment_expression();
7056 if (token.type == ',') {
7058 expression->builtin_prefetch.locality = parse_assignment_expression();
7060 rem_anchor_token(')');
7062 expression->base.type = type_void;
7066 return create_invalid_expression();
7070 * Parses a __builtin_is_*() compare expression.
7072 static expression_t *parse_compare_builtin(void)
7074 expression_t *expression;
7076 switch (token.type) {
7077 case T___builtin_isgreater:
7078 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7080 case T___builtin_isgreaterequal:
7081 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7083 case T___builtin_isless:
7084 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7086 case T___builtin_islessequal:
7087 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7089 case T___builtin_islessgreater:
7090 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7092 case T___builtin_isunordered:
7093 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7096 internal_errorf(HERE, "invalid compare builtin found");
7098 expression->base.source_position = *HERE;
7102 expression->binary.left = parse_assignment_expression();
7104 expression->binary.right = parse_assignment_expression();
7107 type_t *const orig_type_left = expression->binary.left->base.type;
7108 type_t *const orig_type_right = expression->binary.right->base.type;
7110 type_t *const type_left = skip_typeref(orig_type_left);
7111 type_t *const type_right = skip_typeref(orig_type_right);
7112 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7113 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7114 type_error_incompatible("invalid operands in comparison",
7115 &expression->base.source_position, orig_type_left, orig_type_right);
7118 semantic_comparison(&expression->binary);
7123 return create_invalid_expression();
7128 * Parses a __builtin_expect() expression.
7130 static expression_t *parse_builtin_expect(void)
7132 expression_t *expression
7133 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7135 eat(T___builtin_expect);
7138 expression->binary.left = parse_assignment_expression();
7140 expression->binary.right = parse_constant_expression();
7143 expression->base.type = expression->binary.left->base.type;
7147 return create_invalid_expression();
7152 * Parses a MS assume() expression.
7154 static expression_t *parse_assume(void)
7156 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7161 add_anchor_token(')');
7162 expression->unary.value = parse_assignment_expression();
7163 rem_anchor_token(')');
7166 expression->base.type = type_void;
7169 return create_invalid_expression();
7173 * Return the declaration for a given label symbol or create a new one.
7175 * @param symbol the symbol of the label
7177 static label_t *get_label(symbol_t *symbol)
7180 assert(current_function != NULL);
7182 label = get_entity(symbol, NAMESPACE_LABEL);
7183 /* if we found a local label, we already created the declaration */
7184 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7185 if (label->base.parent_scope != scope) {
7186 assert(label->base.parent_scope->depth < scope->depth);
7187 current_function->goto_to_outer = true;
7189 return &label->label;
7192 label = get_entity(symbol, NAMESPACE_LABEL);
7193 /* if we found a label in the same function, then we already created the
7196 && label->base.parent_scope == ¤t_function->parameters) {
7197 return &label->label;
7200 /* otherwise we need to create a new one */
7201 label = allocate_entity_zero(ENTITY_LABEL);
7202 label->base.namespc = NAMESPACE_LABEL;
7203 label->base.symbol = symbol;
7207 return &label->label;
7211 * Parses a GNU && label address expression.
7213 static expression_t *parse_label_address(void)
7215 source_position_t source_position = token.source_position;
7217 if (token.type != T_IDENTIFIER) {
7218 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7221 symbol_t *symbol = token.v.symbol;
7224 label_t *label = get_label(symbol);
7226 label->address_taken = true;
7228 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7229 expression->base.source_position = source_position;
7231 /* label address is threaten as a void pointer */
7232 expression->base.type = type_void_ptr;
7233 expression->label_address.label = label;
7236 return create_invalid_expression();
7240 * Parse a microsoft __noop expression.
7242 static expression_t *parse_noop_expression(void)
7244 /* the result is a (int)0 */
7245 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7246 cnst->base.type = type_int;
7247 cnst->conste.v.int_value = 0;
7248 cnst->conste.is_ms_noop = true;
7252 if (token.type == '(') {
7253 /* parse arguments */
7255 add_anchor_token(')');
7256 add_anchor_token(',');
7258 if (token.type != ')') {
7260 (void)parse_assignment_expression();
7261 if (token.type != ',')
7267 rem_anchor_token(',');
7268 rem_anchor_token(')');
7276 * Parses a primary expression.
7278 static expression_t *parse_primary_expression(void)
7280 switch (token.type) {
7281 case T_false: return parse_bool_const(false);
7282 case T_true: return parse_bool_const(true);
7283 case T_INTEGER: return parse_int_const();
7284 case T_CHARACTER_CONSTANT: return parse_character_constant();
7285 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7286 case T_FLOATINGPOINT: return parse_float_const();
7287 case T_STRING_LITERAL:
7288 case T_WIDE_STRING_LITERAL: return parse_string_const();
7289 case T_IDENTIFIER: return parse_reference();
7290 case T___FUNCTION__:
7291 case T___func__: return parse_function_keyword();
7292 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7293 case T___FUNCSIG__: return parse_funcsig_keyword();
7294 case T___FUNCDNAME__: return parse_funcdname_keyword();
7295 case T___builtin_offsetof: return parse_offsetof();
7296 case T___builtin_va_start: return parse_va_start();
7297 case T___builtin_va_arg: return parse_va_arg();
7298 case T___builtin_expect:
7299 case T___builtin_alloca:
7300 case T___builtin_inf:
7301 case T___builtin_inff:
7302 case T___builtin_infl:
7303 case T___builtin_nan:
7304 case T___builtin_nanf:
7305 case T___builtin_nanl:
7306 case T___builtin_huge_val:
7307 case T___builtin_va_end: return parse_builtin_symbol();
7308 case T___builtin_isgreater:
7309 case T___builtin_isgreaterequal:
7310 case T___builtin_isless:
7311 case T___builtin_islessequal:
7312 case T___builtin_islessgreater:
7313 case T___builtin_isunordered: return parse_compare_builtin();
7314 case T___builtin_constant_p: return parse_builtin_constant();
7315 case T___builtin_prefetch: return parse_builtin_prefetch();
7316 case T__assume: return parse_assume();
7319 return parse_label_address();
7322 case '(': return parse_parenthesized_expression();
7323 case T___noop: return parse_noop_expression();
7326 errorf(HERE, "unexpected token %K, expected an expression", &token);
7327 return create_invalid_expression();
7331 * Check if the expression has the character type and issue a warning then.
7333 static void check_for_char_index_type(const expression_t *expression)
7335 type_t *const type = expression->base.type;
7336 const type_t *const base_type = skip_typeref(type);
7338 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7339 warning.char_subscripts) {
7340 warningf(&expression->base.source_position,
7341 "array subscript has type '%T'", type);
7345 static expression_t *parse_array_expression(expression_t *left)
7347 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7350 add_anchor_token(']');
7352 expression_t *inside = parse_expression();
7354 type_t *const orig_type_left = left->base.type;
7355 type_t *const orig_type_inside = inside->base.type;
7357 type_t *const type_left = skip_typeref(orig_type_left);
7358 type_t *const type_inside = skip_typeref(orig_type_inside);
7360 type_t *return_type;
7361 array_access_expression_t *array_access = &expression->array_access;
7362 if (is_type_pointer(type_left)) {
7363 return_type = type_left->pointer.points_to;
7364 array_access->array_ref = left;
7365 array_access->index = inside;
7366 check_for_char_index_type(inside);
7367 } else if (is_type_pointer(type_inside)) {
7368 return_type = type_inside->pointer.points_to;
7369 array_access->array_ref = inside;
7370 array_access->index = left;
7371 array_access->flipped = true;
7372 check_for_char_index_type(left);
7374 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7376 "array access on object with non-pointer types '%T', '%T'",
7377 orig_type_left, orig_type_inside);
7379 return_type = type_error_type;
7380 array_access->array_ref = left;
7381 array_access->index = inside;
7384 expression->base.type = automatic_type_conversion(return_type);
7386 rem_anchor_token(']');
7392 static expression_t *parse_typeprop(expression_kind_t const kind)
7394 expression_t *tp_expression = allocate_expression_zero(kind);
7395 tp_expression->base.type = type_size_t;
7397 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7399 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7401 /* we only refer to a type property, mark this case */
7402 bool old = in_type_prop;
7403 in_type_prop = true;
7406 expression_t *expression;
7407 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7409 add_anchor_token(')');
7410 orig_type = parse_typename();
7411 rem_anchor_token(')');
7414 if (token.type == '{') {
7415 /* It was not sizeof(type) after all. It is sizeof of an expression
7416 * starting with a compound literal */
7417 expression = parse_compound_literal(orig_type);
7418 goto typeprop_expression;
7421 expression = parse_sub_expression(PREC_UNARY);
7423 typeprop_expression:
7424 tp_expression->typeprop.tp_expression = expression;
7426 orig_type = revert_automatic_type_conversion(expression);
7427 expression->base.type = orig_type;
7430 tp_expression->typeprop.type = orig_type;
7431 type_t const* const type = skip_typeref(orig_type);
7432 char const* const wrong_type =
7433 is_type_incomplete(type) ? "incomplete" :
7434 type->kind == TYPE_FUNCTION ? "function designator" :
7435 type->kind == TYPE_BITFIELD ? "bitfield" :
7437 if (wrong_type != NULL) {
7438 errorf(&tp_expression->base.source_position,
7439 "operand of %s expression must not be of %s type '%T'",
7440 what, wrong_type, orig_type);
7445 return tp_expression;
7448 static expression_t *parse_sizeof(void)
7450 return parse_typeprop(EXPR_SIZEOF);
7453 static expression_t *parse_alignof(void)
7455 return parse_typeprop(EXPR_ALIGNOF);
7458 static expression_t *parse_select_expression(expression_t *compound)
7460 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7461 select->select.compound = compound;
7463 assert(token.type == '.' || token.type == T_MINUSGREATER);
7464 bool is_pointer = (token.type == T_MINUSGREATER);
7467 if (token.type != T_IDENTIFIER) {
7468 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7471 symbol_t *symbol = token.v.symbol;
7474 type_t *const orig_type = compound->base.type;
7475 type_t *const type = skip_typeref(orig_type);
7478 bool saw_error = false;
7479 if (is_type_pointer(type)) {
7482 "request for member '%Y' in something not a struct or union, but '%T'",
7486 type_left = skip_typeref(type->pointer.points_to);
7488 if (is_pointer && is_type_valid(type)) {
7489 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7496 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7497 type_left->kind == TYPE_COMPOUND_UNION) {
7498 compound_t *compound = type_left->compound.compound;
7500 if (!compound->complete) {
7501 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7503 goto create_error_entry;
7506 entry = find_compound_entry(compound, symbol);
7507 if (entry == NULL) {
7508 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7509 goto create_error_entry;
7512 if (is_type_valid(type_left) && !saw_error) {
7514 "request for member '%Y' in something not a struct or union, but '%T'",
7518 return create_invalid_expression();
7521 assert(is_declaration(entry));
7522 select->select.compound_entry = entry;
7524 type_t *entry_type = entry->declaration.type;
7526 = get_qualified_type(entry_type, type_left->base.qualifiers);
7528 /* we always do the auto-type conversions; the & and sizeof parser contains
7529 * code to revert this! */
7530 select->base.type = automatic_type_conversion(res_type);
7532 type_t *skipped = skip_typeref(res_type);
7533 if (skipped->kind == TYPE_BITFIELD) {
7534 select->base.type = skipped->bitfield.base_type;
7540 static void check_call_argument(const function_parameter_t *parameter,
7541 call_argument_t *argument, unsigned pos)
7543 type_t *expected_type = parameter->type;
7544 type_t *expected_type_skip = skip_typeref(expected_type);
7545 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7546 expression_t *arg_expr = argument->expression;
7547 type_t *arg_type = skip_typeref(arg_expr->base.type);
7549 /* handle transparent union gnu extension */
7550 if (is_type_union(expected_type_skip)
7551 && (expected_type_skip->base.modifiers
7552 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7553 compound_t *union_decl = expected_type_skip->compound.compound;
7554 type_t *best_type = NULL;
7555 entity_t *entry = union_decl->members.entities;
7556 for ( ; entry != NULL; entry = entry->base.next) {
7557 assert(is_declaration(entry));
7558 type_t *decl_type = entry->declaration.type;
7559 error = semantic_assign(decl_type, arg_expr);
7560 if (error == ASSIGN_ERROR_INCOMPATIBLE
7561 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7564 if (error == ASSIGN_SUCCESS) {
7565 best_type = decl_type;
7566 } else if (best_type == NULL) {
7567 best_type = decl_type;
7571 if (best_type != NULL) {
7572 expected_type = best_type;
7576 error = semantic_assign(expected_type, arg_expr);
7577 argument->expression = create_implicit_cast(argument->expression,
7580 if (error != ASSIGN_SUCCESS) {
7581 /* report exact scope in error messages (like "in argument 3") */
7583 snprintf(buf, sizeof(buf), "call argument %u", pos);
7584 report_assign_error(error, expected_type, arg_expr, buf,
7585 &arg_expr->base.source_position);
7586 } else if (warning.traditional || warning.conversion) {
7587 type_t *const promoted_type = get_default_promoted_type(arg_type);
7588 if (!types_compatible(expected_type_skip, promoted_type) &&
7589 !types_compatible(expected_type_skip, type_void_ptr) &&
7590 !types_compatible(type_void_ptr, promoted_type)) {
7591 /* Deliberately show the skipped types in this warning */
7592 warningf(&arg_expr->base.source_position,
7593 "passing call argument %u as '%T' rather than '%T' due to prototype",
7594 pos, expected_type_skip, promoted_type);
7600 * Parse a call expression, ie. expression '( ... )'.
7602 * @param expression the function address
7604 static expression_t *parse_call_expression(expression_t *expression)
7606 expression_t *result = allocate_expression_zero(EXPR_CALL);
7607 call_expression_t *call = &result->call;
7608 call->function = expression;
7610 type_t *const orig_type = expression->base.type;
7611 type_t *const type = skip_typeref(orig_type);
7613 function_type_t *function_type = NULL;
7614 if (is_type_pointer(type)) {
7615 type_t *const to_type = skip_typeref(type->pointer.points_to);
7617 if (is_type_function(to_type)) {
7618 function_type = &to_type->function;
7619 call->base.type = function_type->return_type;
7623 if (function_type == NULL && is_type_valid(type)) {
7624 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7627 /* parse arguments */
7629 add_anchor_token(')');
7630 add_anchor_token(',');
7632 if (token.type != ')') {
7633 call_argument_t *last_argument = NULL;
7636 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7638 argument->expression = parse_assignment_expression();
7639 if (last_argument == NULL) {
7640 call->arguments = argument;
7642 last_argument->next = argument;
7644 last_argument = argument;
7646 if (token.type != ',')
7651 rem_anchor_token(',');
7652 rem_anchor_token(')');
7655 if (function_type == NULL)
7658 function_parameter_t *parameter = function_type->parameters;
7659 call_argument_t *argument = call->arguments;
7660 if (!function_type->unspecified_parameters) {
7661 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7662 parameter = parameter->next, argument = argument->next) {
7663 check_call_argument(parameter, argument, ++pos);
7666 if (parameter != NULL) {
7667 errorf(HERE, "too few arguments to function '%E'", expression);
7668 } else if (argument != NULL && !function_type->variadic) {
7669 errorf(HERE, "too many arguments to function '%E'", expression);
7673 /* do default promotion */
7674 for( ; argument != NULL; argument = argument->next) {
7675 type_t *type = argument->expression->base.type;
7677 type = get_default_promoted_type(type);
7679 argument->expression
7680 = create_implicit_cast(argument->expression, type);
7683 check_format(&result->call);
7685 if (warning.aggregate_return &&
7686 is_type_compound(skip_typeref(function_type->return_type))) {
7687 warningf(&result->base.source_position,
7688 "function call has aggregate value");
7695 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7697 static bool same_compound_type(const type_t *type1, const type_t *type2)
7700 is_type_compound(type1) &&
7701 type1->kind == type2->kind &&
7702 type1->compound.compound == type2->compound.compound;
7706 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7708 * @param expression the conditional expression
7710 static expression_t *parse_conditional_expression(expression_t *expression)
7712 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7714 conditional_expression_t *conditional = &result->conditional;
7715 conditional->condition = expression;
7718 add_anchor_token(':');
7721 type_t *const condition_type_orig = expression->base.type;
7722 type_t *const condition_type = skip_typeref(condition_type_orig);
7723 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7724 type_error("expected a scalar type in conditional condition",
7725 &expression->base.source_position, condition_type_orig);
7728 expression_t *true_expression = expression;
7729 bool gnu_cond = false;
7730 if (GNU_MODE && token.type == ':') {
7733 true_expression = parse_expression();
7735 rem_anchor_token(':');
7737 expression_t *false_expression =
7738 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7740 type_t *const orig_true_type = true_expression->base.type;
7741 type_t *const orig_false_type = false_expression->base.type;
7742 type_t *const true_type = skip_typeref(orig_true_type);
7743 type_t *const false_type = skip_typeref(orig_false_type);
7746 type_t *result_type;
7747 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7748 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7749 /* ISO/IEC 14882:1998(E) §5.16:2 */
7750 if (true_expression->kind == EXPR_UNARY_THROW) {
7751 result_type = false_type;
7752 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7753 result_type = true_type;
7755 if (warning.other && (
7756 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7757 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7759 warningf(&conditional->base.source_position,
7760 "ISO C forbids conditional expression with only one void side");
7762 result_type = type_void;
7764 } else if (is_type_arithmetic(true_type)
7765 && is_type_arithmetic(false_type)) {
7766 result_type = semantic_arithmetic(true_type, false_type);
7768 true_expression = create_implicit_cast(true_expression, result_type);
7769 false_expression = create_implicit_cast(false_expression, result_type);
7771 conditional->true_expression = true_expression;
7772 conditional->false_expression = false_expression;
7773 conditional->base.type = result_type;
7774 } else if (same_compound_type(true_type, false_type)) {
7775 /* just take 1 of the 2 types */
7776 result_type = true_type;
7777 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7778 type_t *pointer_type;
7780 expression_t *other_expression;
7781 if (is_type_pointer(true_type) &&
7782 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7783 pointer_type = true_type;
7784 other_type = false_type;
7785 other_expression = false_expression;
7787 pointer_type = false_type;
7788 other_type = true_type;
7789 other_expression = true_expression;
7792 if (is_null_pointer_constant(other_expression)) {
7793 result_type = pointer_type;
7794 } else if (is_type_pointer(other_type)) {
7795 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7796 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7799 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7800 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7802 } else if (types_compatible(get_unqualified_type(to1),
7803 get_unqualified_type(to2))) {
7806 if (warning.other) {
7807 warningf(&conditional->base.source_position,
7808 "pointer types '%T' and '%T' in conditional expression are incompatible",
7809 true_type, false_type);
7814 type_t *const type =
7815 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7816 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7817 } else if (is_type_integer(other_type)) {
7818 if (warning.other) {
7819 warningf(&conditional->base.source_position,
7820 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7822 result_type = pointer_type;
7824 if (is_type_valid(other_type)) {
7825 type_error_incompatible("while parsing conditional",
7826 &expression->base.source_position, true_type, false_type);
7828 result_type = type_error_type;
7831 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7832 type_error_incompatible("while parsing conditional",
7833 &conditional->base.source_position, true_type,
7836 result_type = type_error_type;
7839 conditional->true_expression
7840 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7841 conditional->false_expression
7842 = create_implicit_cast(false_expression, result_type);
7843 conditional->base.type = result_type;
7846 return create_invalid_expression();
7850 * Parse an extension expression.
7852 static expression_t *parse_extension(void)
7854 eat(T___extension__);
7856 bool old_gcc_extension = in_gcc_extension;
7857 in_gcc_extension = true;
7858 expression_t *expression = parse_sub_expression(PREC_UNARY);
7859 in_gcc_extension = old_gcc_extension;
7864 * Parse a __builtin_classify_type() expression.
7866 static expression_t *parse_builtin_classify_type(void)
7868 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7869 result->base.type = type_int;
7871 eat(T___builtin_classify_type);
7874 add_anchor_token(')');
7875 expression_t *expression = parse_expression();
7876 rem_anchor_token(')');
7878 result->classify_type.type_expression = expression;
7882 return create_invalid_expression();
7886 * Parse a delete expression
7887 * ISO/IEC 14882:1998(E) §5.3.5
7889 static expression_t *parse_delete(void)
7891 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7892 result->base.type = type_void;
7896 if (token.type == '[') {
7898 result->kind = EXPR_UNARY_DELETE_ARRAY;
7903 expression_t *const value = parse_sub_expression(PREC_CAST);
7904 result->unary.value = value;
7906 type_t *const type = skip_typeref(value->base.type);
7907 if (!is_type_pointer(type)) {
7908 errorf(&value->base.source_position,
7909 "operand of delete must have pointer type");
7910 } else if (warning.other &&
7911 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7912 warningf(&value->base.source_position,
7913 "deleting 'void*' is undefined");
7920 * Parse a throw expression
7921 * ISO/IEC 14882:1998(E) §15:1
7923 static expression_t *parse_throw(void)
7925 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7926 result->base.type = type_void;
7930 expression_t *value = NULL;
7931 switch (token.type) {
7933 value = parse_assignment_expression();
7934 /* ISO/IEC 14882:1998(E) §15.1:3 */
7935 type_t *const orig_type = value->base.type;
7936 type_t *const type = skip_typeref(orig_type);
7937 if (is_type_incomplete(type)) {
7938 errorf(&value->base.source_position,
7939 "cannot throw object of incomplete type '%T'", orig_type);
7940 } else if (is_type_pointer(type)) {
7941 type_t *const points_to = skip_typeref(type->pointer.points_to);
7942 if (is_type_incomplete(points_to) &&
7943 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7944 errorf(&value->base.source_position,
7945 "cannot throw pointer to incomplete type '%T'", orig_type);
7953 result->unary.value = value;
7958 static bool check_pointer_arithmetic(const source_position_t *source_position,
7959 type_t *pointer_type,
7960 type_t *orig_pointer_type)
7962 type_t *points_to = pointer_type->pointer.points_to;
7963 points_to = skip_typeref(points_to);
7965 if (is_type_incomplete(points_to)) {
7966 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7967 errorf(source_position,
7968 "arithmetic with pointer to incomplete type '%T' not allowed",
7971 } else if (warning.pointer_arith) {
7972 warningf(source_position,
7973 "pointer of type '%T' used in arithmetic",
7976 } else if (is_type_function(points_to)) {
7978 errorf(source_position,
7979 "arithmetic with pointer to function type '%T' not allowed",
7982 } else if (warning.pointer_arith) {
7983 warningf(source_position,
7984 "pointer to a function '%T' used in arithmetic",
7991 static bool is_lvalue(const expression_t *expression)
7993 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
7994 switch (expression->kind) {
7995 case EXPR_REFERENCE:
7996 case EXPR_ARRAY_ACCESS:
7998 case EXPR_UNARY_DEREFERENCE:
8002 /* Claim it is an lvalue, if the type is invalid. There was a parse
8003 * error before, which maybe prevented properly recognizing it as
8005 return !is_type_valid(skip_typeref(expression->base.type));
8009 static void semantic_incdec(unary_expression_t *expression)
8011 type_t *const orig_type = expression->value->base.type;
8012 type_t *const type = skip_typeref(orig_type);
8013 if (is_type_pointer(type)) {
8014 if (!check_pointer_arithmetic(&expression->base.source_position,
8018 } else if (!is_type_real(type) && is_type_valid(type)) {
8019 /* TODO: improve error message */
8020 errorf(&expression->base.source_position,
8021 "operation needs an arithmetic or pointer type");
8024 if (!is_lvalue(expression->value)) {
8025 /* TODO: improve error message */
8026 errorf(&expression->base.source_position, "lvalue required as operand");
8028 expression->base.type = orig_type;
8031 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8033 type_t *const orig_type = expression->value->base.type;
8034 type_t *const type = skip_typeref(orig_type);
8035 if (!is_type_arithmetic(type)) {
8036 if (is_type_valid(type)) {
8037 /* TODO: improve error message */
8038 errorf(&expression->base.source_position,
8039 "operation needs an arithmetic type");
8044 expression->base.type = orig_type;
8047 static void semantic_unexpr_plus(unary_expression_t *expression)
8049 semantic_unexpr_arithmetic(expression);
8050 if (warning.traditional)
8051 warningf(&expression->base.source_position,
8052 "traditional C rejects the unary plus operator");
8055 static expression_t const *get_reference_address(expression_t const *expr)
8057 bool regular_take_address = true;
8059 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8060 expr = expr->unary.value;
8062 regular_take_address = false;
8065 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8068 expr = expr->unary.value;
8071 /* special case for functions which are automatically converted to a
8072 * pointer to function without an extra TAKE_ADDRESS operation */
8073 if (!regular_take_address && expr->kind == EXPR_REFERENCE
8074 && expr->reference.entity->kind == ENTITY_FUNCTION) {
8081 static void warn_function_address_as_bool(expression_t const* expr)
8083 if (!warning.address)
8086 expr = get_reference_address(expr);
8088 warningf(&expr->base.source_position,
8089 "the address of '%Y' will always evaluate as 'true'",
8090 expr->reference.entity->base.symbol);
8094 static void semantic_not(unary_expression_t *expression)
8096 type_t *const orig_type = expression->value->base.type;
8097 type_t *const type = skip_typeref(orig_type);
8098 if (!is_type_scalar(type) && is_type_valid(type)) {
8099 errorf(&expression->base.source_position,
8100 "operand of ! must be of scalar type");
8103 warn_function_address_as_bool(expression->value);
8105 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8108 static void semantic_unexpr_integer(unary_expression_t *expression)
8110 type_t *const orig_type = expression->value->base.type;
8111 type_t *const type = skip_typeref(orig_type);
8112 if (!is_type_integer(type)) {
8113 if (is_type_valid(type)) {
8114 errorf(&expression->base.source_position,
8115 "operand of ~ must be of integer type");
8120 expression->base.type = orig_type;
8123 static void semantic_dereference(unary_expression_t *expression)
8125 type_t *const orig_type = expression->value->base.type;
8126 type_t *const type = skip_typeref(orig_type);
8127 if (!is_type_pointer(type)) {
8128 if (is_type_valid(type)) {
8129 errorf(&expression->base.source_position,
8130 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8135 type_t *result_type = type->pointer.points_to;
8136 result_type = automatic_type_conversion(result_type);
8137 expression->base.type = result_type;
8141 * Record that an address is taken (expression represents an lvalue).
8143 * @param expression the expression
8144 * @param may_be_register if true, the expression might be an register
8146 static void set_address_taken(expression_t *expression, bool may_be_register)
8148 if (expression->kind != EXPR_REFERENCE)
8151 entity_t *const entity = expression->reference.entity;
8153 if (entity->kind != ENTITY_VARIABLE)
8156 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8157 && !may_be_register) {
8158 errorf(&expression->base.source_position,
8159 "address of register variable '%Y' requested",
8160 entity->base.symbol);
8163 entity->variable.address_taken = true;
8167 * Check the semantic of the address taken expression.
8169 static void semantic_take_addr(unary_expression_t *expression)
8171 expression_t *value = expression->value;
8172 value->base.type = revert_automatic_type_conversion(value);
8174 type_t *orig_type = value->base.type;
8175 type_t *type = skip_typeref(orig_type);
8176 if (!is_type_valid(type))
8180 if (value->kind != EXPR_ARRAY_ACCESS
8181 && value->kind != EXPR_UNARY_DEREFERENCE
8182 && !is_lvalue(value)) {
8183 errorf(&expression->base.source_position,
8184 "'&' requires an lvalue");
8186 if (type->kind == TYPE_BITFIELD) {
8187 errorf(&expression->base.source_position,
8188 "'&' not allowed on object with bitfield type '%T'",
8192 set_address_taken(value, false);
8194 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8197 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8198 static expression_t *parse_##unexpression_type(void) \
8200 expression_t *unary_expression \
8201 = allocate_expression_zero(unexpression_type); \
8203 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8205 sfunc(&unary_expression->unary); \
8207 return unary_expression; \
8210 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8211 semantic_unexpr_arithmetic)
8212 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8213 semantic_unexpr_plus)
8214 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8216 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8217 semantic_dereference)
8218 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8220 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8221 semantic_unexpr_integer)
8222 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8224 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8227 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8229 static expression_t *parse_##unexpression_type(expression_t *left) \
8231 expression_t *unary_expression \
8232 = allocate_expression_zero(unexpression_type); \
8234 unary_expression->unary.value = left; \
8236 sfunc(&unary_expression->unary); \
8238 return unary_expression; \
8241 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8242 EXPR_UNARY_POSTFIX_INCREMENT,
8244 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8245 EXPR_UNARY_POSTFIX_DECREMENT,
8248 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8250 /* TODO: handle complex + imaginary types */
8252 type_left = get_unqualified_type(type_left);
8253 type_right = get_unqualified_type(type_right);
8255 /* § 6.3.1.8 Usual arithmetic conversions */
8256 if (type_left == type_long_double || type_right == type_long_double) {
8257 return type_long_double;
8258 } else if (type_left == type_double || type_right == type_double) {
8260 } else if (type_left == type_float || type_right == type_float) {
8264 type_left = promote_integer(type_left);
8265 type_right = promote_integer(type_right);
8267 if (type_left == type_right)
8270 bool const signed_left = is_type_signed(type_left);
8271 bool const signed_right = is_type_signed(type_right);
8272 int const rank_left = get_rank(type_left);
8273 int const rank_right = get_rank(type_right);
8275 if (signed_left == signed_right)
8276 return rank_left >= rank_right ? type_left : type_right;
8285 u_rank = rank_right;
8286 u_type = type_right;
8288 s_rank = rank_right;
8289 s_type = type_right;
8294 if (u_rank >= s_rank)
8297 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8299 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8300 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8304 case ATOMIC_TYPE_INT: return type_unsigned_int;
8305 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8306 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8308 default: panic("invalid atomic type");
8313 * Check the semantic restrictions for a binary expression.
8315 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8317 expression_t *const left = expression->left;
8318 expression_t *const right = expression->right;
8319 type_t *const orig_type_left = left->base.type;
8320 type_t *const orig_type_right = right->base.type;
8321 type_t *const type_left = skip_typeref(orig_type_left);
8322 type_t *const type_right = skip_typeref(orig_type_right);
8324 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8325 /* TODO: improve error message */
8326 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8327 errorf(&expression->base.source_position,
8328 "operation needs arithmetic types");
8333 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8334 expression->left = create_implicit_cast(left, arithmetic_type);
8335 expression->right = create_implicit_cast(right, arithmetic_type);
8336 expression->base.type = arithmetic_type;
8339 static void warn_div_by_zero(binary_expression_t const *const expression)
8341 if (!warning.div_by_zero ||
8342 !is_type_integer(expression->base.type))
8345 expression_t const *const right = expression->right;
8346 /* The type of the right operand can be different for /= */
8347 if (is_type_integer(right->base.type) &&
8348 is_constant_expression(right) &&
8349 fold_constant(right) == 0) {
8350 warningf(&expression->base.source_position, "division by zero");
8355 * Check the semantic restrictions for a div/mod expression.
8357 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8358 semantic_binexpr_arithmetic(expression);
8359 warn_div_by_zero(expression);
8362 static void semantic_shift_op(binary_expression_t *expression)
8364 expression_t *const left = expression->left;
8365 expression_t *const right = expression->right;
8366 type_t *const orig_type_left = left->base.type;
8367 type_t *const orig_type_right = right->base.type;
8368 type_t * type_left = skip_typeref(orig_type_left);
8369 type_t * type_right = skip_typeref(orig_type_right);
8371 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8372 /* TODO: improve error message */
8373 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8374 errorf(&expression->base.source_position,
8375 "operands of shift operation must have integer types");
8380 type_left = promote_integer(type_left);
8381 type_right = promote_integer(type_right);
8383 expression->left = create_implicit_cast(left, type_left);
8384 expression->right = create_implicit_cast(right, type_right);
8385 expression->base.type = type_left;
8388 static void semantic_add(binary_expression_t *expression)
8390 expression_t *const left = expression->left;
8391 expression_t *const right = expression->right;
8392 type_t *const orig_type_left = left->base.type;
8393 type_t *const orig_type_right = right->base.type;
8394 type_t *const type_left = skip_typeref(orig_type_left);
8395 type_t *const type_right = skip_typeref(orig_type_right);
8398 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8399 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8400 expression->left = create_implicit_cast(left, arithmetic_type);
8401 expression->right = create_implicit_cast(right, arithmetic_type);
8402 expression->base.type = arithmetic_type;
8404 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8405 check_pointer_arithmetic(&expression->base.source_position,
8406 type_left, orig_type_left);
8407 expression->base.type = type_left;
8408 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8409 check_pointer_arithmetic(&expression->base.source_position,
8410 type_right, orig_type_right);
8411 expression->base.type = type_right;
8412 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8413 errorf(&expression->base.source_position,
8414 "invalid operands to binary + ('%T', '%T')",
8415 orig_type_left, orig_type_right);
8419 static void semantic_sub(binary_expression_t *expression)
8421 expression_t *const left = expression->left;
8422 expression_t *const right = expression->right;
8423 type_t *const orig_type_left = left->base.type;
8424 type_t *const orig_type_right = right->base.type;
8425 type_t *const type_left = skip_typeref(orig_type_left);
8426 type_t *const type_right = skip_typeref(orig_type_right);
8427 source_position_t const *const pos = &expression->base.source_position;
8430 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8431 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8432 expression->left = create_implicit_cast(left, arithmetic_type);
8433 expression->right = create_implicit_cast(right, arithmetic_type);
8434 expression->base.type = arithmetic_type;
8436 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8437 check_pointer_arithmetic(&expression->base.source_position,
8438 type_left, orig_type_left);
8439 expression->base.type = type_left;
8440 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8441 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8442 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8443 if (!types_compatible(unqual_left, unqual_right)) {
8445 "subtracting pointers to incompatible types '%T' and '%T'",
8446 orig_type_left, orig_type_right);
8447 } else if (!is_type_object(unqual_left)) {
8448 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8449 errorf(pos, "subtracting pointers to non-object types '%T'",
8451 } else if (warning.other) {
8452 warningf(pos, "subtracting pointers to void");
8455 expression->base.type = type_ptrdiff_t;
8456 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8457 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8458 orig_type_left, orig_type_right);
8462 static void warn_string_literal_address(expression_t const* expr)
8464 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8465 expr = expr->unary.value;
8466 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8468 expr = expr->unary.value;
8471 if (expr->kind == EXPR_STRING_LITERAL ||
8472 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8473 warningf(&expr->base.source_position,
8474 "comparison with string literal results in unspecified behaviour");
8479 * Check the semantics of comparison expressions.
8481 * @param expression The expression to check.
8483 static void semantic_comparison(binary_expression_t *expression)
8485 expression_t *left = expression->left;
8486 expression_t *right = expression->right;
8488 if (warning.address) {
8489 warn_string_literal_address(left);
8490 warn_string_literal_address(right);
8492 expression_t const* const func_left = get_reference_address(left);
8493 if (func_left != NULL && is_null_pointer_constant(right)) {
8494 warningf(&expression->base.source_position,
8495 "the address of '%Y' will never be NULL",
8496 func_left->reference.entity->base.symbol);
8499 expression_t const* const func_right = get_reference_address(right);
8500 if (func_right != NULL && is_null_pointer_constant(right)) {
8501 warningf(&expression->base.source_position,
8502 "the address of '%Y' will never be NULL",
8503 func_right->reference.entity->base.symbol);
8507 type_t *orig_type_left = left->base.type;
8508 type_t *orig_type_right = right->base.type;
8509 type_t *type_left = skip_typeref(orig_type_left);
8510 type_t *type_right = skip_typeref(orig_type_right);
8512 /* TODO non-arithmetic types */
8513 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8514 /* test for signed vs unsigned compares */
8515 if (warning.sign_compare &&
8516 (expression->base.kind != EXPR_BINARY_EQUAL &&
8517 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8518 (is_type_signed(type_left) != is_type_signed(type_right))) {
8520 /* check if 1 of the operands is a constant, in this case we just
8521 * check wether we can safely represent the resulting constant in
8522 * the type of the other operand. */
8523 expression_t *const_expr = NULL;
8524 expression_t *other_expr = NULL;
8526 if (is_constant_expression(left)) {
8529 } else if (is_constant_expression(right)) {
8534 if (const_expr != NULL) {
8535 type_t *other_type = skip_typeref(other_expr->base.type);
8536 long val = fold_constant(const_expr);
8537 /* TODO: check if val can be represented by other_type */
8541 warningf(&expression->base.source_position,
8542 "comparison between signed and unsigned");
8544 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8545 expression->left = create_implicit_cast(left, arithmetic_type);
8546 expression->right = create_implicit_cast(right, arithmetic_type);
8547 expression->base.type = arithmetic_type;
8548 if (warning.float_equal &&
8549 (expression->base.kind == EXPR_BINARY_EQUAL ||
8550 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8551 is_type_float(arithmetic_type)) {
8552 warningf(&expression->base.source_position,
8553 "comparing floating point with == or != is unsafe");
8555 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8556 /* TODO check compatibility */
8557 } else if (is_type_pointer(type_left)) {
8558 expression->right = create_implicit_cast(right, type_left);
8559 } else if (is_type_pointer(type_right)) {
8560 expression->left = create_implicit_cast(left, type_right);
8561 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8562 type_error_incompatible("invalid operands in comparison",
8563 &expression->base.source_position,
8564 type_left, type_right);
8566 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8570 * Checks if a compound type has constant fields.
8572 static bool has_const_fields(const compound_type_t *type)
8574 compound_t *compound = type->compound;
8575 entity_t *entry = compound->members.entities;
8577 for (; entry != NULL; entry = entry->base.next) {
8578 if (!is_declaration(entry))
8581 const type_t *decl_type = skip_typeref(entry->declaration.type);
8582 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8589 static bool is_valid_assignment_lhs(expression_t const* const left)
8591 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8592 type_t *const type_left = skip_typeref(orig_type_left);
8594 if (!is_lvalue(left)) {
8595 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8600 if (is_type_array(type_left)) {
8601 errorf(HERE, "cannot assign to arrays ('%E')", left);
8604 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8605 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8609 if (is_type_incomplete(type_left)) {
8610 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8611 left, orig_type_left);
8614 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8615 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8616 left, orig_type_left);
8623 static void semantic_arithmetic_assign(binary_expression_t *expression)
8625 expression_t *left = expression->left;
8626 expression_t *right = expression->right;
8627 type_t *orig_type_left = left->base.type;
8628 type_t *orig_type_right = right->base.type;
8630 if (!is_valid_assignment_lhs(left))
8633 type_t *type_left = skip_typeref(orig_type_left);
8634 type_t *type_right = skip_typeref(orig_type_right);
8636 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8637 /* TODO: improve error message */
8638 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8639 errorf(&expression->base.source_position,
8640 "operation needs arithmetic types");
8645 /* combined instructions are tricky. We can't create an implicit cast on
8646 * the left side, because we need the uncasted form for the store.
8647 * The ast2firm pass has to know that left_type must be right_type
8648 * for the arithmetic operation and create a cast by itself */
8649 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8650 expression->right = create_implicit_cast(right, arithmetic_type);
8651 expression->base.type = type_left;
8654 static void semantic_divmod_assign(binary_expression_t *expression)
8656 semantic_arithmetic_assign(expression);
8657 warn_div_by_zero(expression);
8660 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8662 expression_t *const left = expression->left;
8663 expression_t *const right = expression->right;
8664 type_t *const orig_type_left = left->base.type;
8665 type_t *const orig_type_right = right->base.type;
8666 type_t *const type_left = skip_typeref(orig_type_left);
8667 type_t *const type_right = skip_typeref(orig_type_right);
8669 if (!is_valid_assignment_lhs(left))
8672 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8673 /* combined instructions are tricky. We can't create an implicit cast on
8674 * the left side, because we need the uncasted form for the store.
8675 * The ast2firm pass has to know that left_type must be right_type
8676 * for the arithmetic operation and create a cast by itself */
8677 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8678 expression->right = create_implicit_cast(right, arithmetic_type);
8679 expression->base.type = type_left;
8680 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8681 check_pointer_arithmetic(&expression->base.source_position,
8682 type_left, orig_type_left);
8683 expression->base.type = type_left;
8684 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8685 errorf(&expression->base.source_position,
8686 "incompatible types '%T' and '%T' in assignment",
8687 orig_type_left, orig_type_right);
8692 * Check the semantic restrictions of a logical expression.
8694 static void semantic_logical_op(binary_expression_t *expression)
8696 expression_t *const left = expression->left;
8697 expression_t *const right = expression->right;
8698 type_t *const orig_type_left = left->base.type;
8699 type_t *const orig_type_right = right->base.type;
8700 type_t *const type_left = skip_typeref(orig_type_left);
8701 type_t *const type_right = skip_typeref(orig_type_right);
8703 warn_function_address_as_bool(left);
8704 warn_function_address_as_bool(right);
8706 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8707 /* TODO: improve error message */
8708 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8709 errorf(&expression->base.source_position,
8710 "operation needs scalar types");
8715 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8719 * Check the semantic restrictions of a binary assign expression.
8721 static void semantic_binexpr_assign(binary_expression_t *expression)
8723 expression_t *left = expression->left;
8724 type_t *orig_type_left = left->base.type;
8726 if (!is_valid_assignment_lhs(left))
8729 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8730 report_assign_error(error, orig_type_left, expression->right,
8731 "assignment", &left->base.source_position);
8732 expression->right = create_implicit_cast(expression->right, orig_type_left);
8733 expression->base.type = orig_type_left;
8737 * Determine if the outermost operation (or parts thereof) of the given
8738 * expression has no effect in order to generate a warning about this fact.
8739 * Therefore in some cases this only examines some of the operands of the
8740 * expression (see comments in the function and examples below).
8742 * f() + 23; // warning, because + has no effect
8743 * x || f(); // no warning, because x controls execution of f()
8744 * x ? y : f(); // warning, because y has no effect
8745 * (void)x; // no warning to be able to suppress the warning
8746 * This function can NOT be used for an "expression has definitely no effect"-
8748 static bool expression_has_effect(const expression_t *const expr)
8750 switch (expr->kind) {
8751 case EXPR_UNKNOWN: break;
8752 case EXPR_INVALID: return true; /* do NOT warn */
8753 case EXPR_REFERENCE: return false;
8754 case EXPR_REFERENCE_ENUM_VALUE: return false;
8755 /* suppress the warning for microsoft __noop operations */
8756 case EXPR_CONST: return expr->conste.is_ms_noop;
8757 case EXPR_CHARACTER_CONSTANT: return false;
8758 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8759 case EXPR_STRING_LITERAL: return false;
8760 case EXPR_WIDE_STRING_LITERAL: return false;
8761 case EXPR_LABEL_ADDRESS: return false;
8764 const call_expression_t *const call = &expr->call;
8765 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8768 switch (call->function->builtin_symbol.symbol->ID) {
8769 case T___builtin_va_end: return true;
8770 default: return false;
8774 /* Generate the warning if either the left or right hand side of a
8775 * conditional expression has no effect */
8776 case EXPR_CONDITIONAL: {
8777 const conditional_expression_t *const cond = &expr->conditional;
8779 expression_has_effect(cond->true_expression) &&
8780 expression_has_effect(cond->false_expression);
8783 case EXPR_SELECT: return false;
8784 case EXPR_ARRAY_ACCESS: return false;
8785 case EXPR_SIZEOF: return false;
8786 case EXPR_CLASSIFY_TYPE: return false;
8787 case EXPR_ALIGNOF: return false;
8789 case EXPR_FUNCNAME: return false;
8790 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8791 case EXPR_BUILTIN_CONSTANT_P: return false;
8792 case EXPR_BUILTIN_PREFETCH: return true;
8793 case EXPR_OFFSETOF: return false;
8794 case EXPR_VA_START: return true;
8795 case EXPR_VA_ARG: return true;
8796 case EXPR_STATEMENT: return true; // TODO
8797 case EXPR_COMPOUND_LITERAL: return false;
8799 case EXPR_UNARY_NEGATE: return false;
8800 case EXPR_UNARY_PLUS: return false;
8801 case EXPR_UNARY_BITWISE_NEGATE: return false;
8802 case EXPR_UNARY_NOT: return false;
8803 case EXPR_UNARY_DEREFERENCE: return false;
8804 case EXPR_UNARY_TAKE_ADDRESS: return false;
8805 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8806 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8807 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8808 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8810 /* Treat void casts as if they have an effect in order to being able to
8811 * suppress the warning */
8812 case EXPR_UNARY_CAST: {
8813 type_t *const type = skip_typeref(expr->base.type);
8814 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8817 case EXPR_UNARY_CAST_IMPLICIT: return true;
8818 case EXPR_UNARY_ASSUME: return true;
8819 case EXPR_UNARY_DELETE: return true;
8820 case EXPR_UNARY_DELETE_ARRAY: return true;
8821 case EXPR_UNARY_THROW: return true;
8823 case EXPR_BINARY_ADD: return false;
8824 case EXPR_BINARY_SUB: return false;
8825 case EXPR_BINARY_MUL: return false;
8826 case EXPR_BINARY_DIV: return false;
8827 case EXPR_BINARY_MOD: return false;
8828 case EXPR_BINARY_EQUAL: return false;
8829 case EXPR_BINARY_NOTEQUAL: return false;
8830 case EXPR_BINARY_LESS: return false;
8831 case EXPR_BINARY_LESSEQUAL: return false;
8832 case EXPR_BINARY_GREATER: return false;
8833 case EXPR_BINARY_GREATEREQUAL: return false;
8834 case EXPR_BINARY_BITWISE_AND: return false;
8835 case EXPR_BINARY_BITWISE_OR: return false;
8836 case EXPR_BINARY_BITWISE_XOR: return false;
8837 case EXPR_BINARY_SHIFTLEFT: return false;
8838 case EXPR_BINARY_SHIFTRIGHT: return false;
8839 case EXPR_BINARY_ASSIGN: return true;
8840 case EXPR_BINARY_MUL_ASSIGN: return true;
8841 case EXPR_BINARY_DIV_ASSIGN: return true;
8842 case EXPR_BINARY_MOD_ASSIGN: return true;
8843 case EXPR_BINARY_ADD_ASSIGN: return true;
8844 case EXPR_BINARY_SUB_ASSIGN: return true;
8845 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8846 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8847 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8848 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8849 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8851 /* Only examine the right hand side of && and ||, because the left hand
8852 * side already has the effect of controlling the execution of the right
8854 case EXPR_BINARY_LOGICAL_AND:
8855 case EXPR_BINARY_LOGICAL_OR:
8856 /* Only examine the right hand side of a comma expression, because the left
8857 * hand side has a separate warning */
8858 case EXPR_BINARY_COMMA:
8859 return expression_has_effect(expr->binary.right);
8861 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8862 case EXPR_BINARY_ISGREATER: return false;
8863 case EXPR_BINARY_ISGREATEREQUAL: return false;
8864 case EXPR_BINARY_ISLESS: return false;
8865 case EXPR_BINARY_ISLESSEQUAL: return false;
8866 case EXPR_BINARY_ISLESSGREATER: return false;
8867 case EXPR_BINARY_ISUNORDERED: return false;
8870 internal_errorf(HERE, "unexpected expression");
8873 static void semantic_comma(binary_expression_t *expression)
8875 if (warning.unused_value) {
8876 const expression_t *const left = expression->left;
8877 if (!expression_has_effect(left)) {
8878 warningf(&left->base.source_position,
8879 "left-hand operand of comma expression has no effect");
8882 expression->base.type = expression->right->base.type;
8886 * @param prec_r precedence of the right operand
8888 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8889 static expression_t *parse_##binexpression_type(expression_t *left) \
8891 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8892 binexpr->binary.left = left; \
8895 expression_t *right = parse_sub_expression(prec_r); \
8897 binexpr->binary.right = right; \
8898 sfunc(&binexpr->binary); \
8903 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8904 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8905 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8906 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8907 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8908 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8909 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8910 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8911 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8912 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8913 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8914 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8915 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8916 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8917 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8918 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8919 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8920 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8921 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8922 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8923 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8924 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8925 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8926 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8927 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8928 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8929 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8930 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8931 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8932 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8935 static expression_t *parse_sub_expression(precedence_t precedence)
8937 if (token.type < 0) {
8938 return expected_expression_error();
8941 expression_parser_function_t *parser
8942 = &expression_parsers[token.type];
8943 source_position_t source_position = token.source_position;
8946 if (parser->parser != NULL) {
8947 left = parser->parser();
8949 left = parse_primary_expression();
8951 assert(left != NULL);
8952 left->base.source_position = source_position;
8955 if (token.type < 0) {
8956 return expected_expression_error();
8959 parser = &expression_parsers[token.type];
8960 if (parser->infix_parser == NULL)
8962 if (parser->infix_precedence < precedence)
8965 left = parser->infix_parser(left);
8967 assert(left != NULL);
8968 assert(left->kind != EXPR_UNKNOWN);
8969 left->base.source_position = source_position;
8976 * Parse an expression.
8978 static expression_t *parse_expression(void)
8980 return parse_sub_expression(PREC_EXPRESSION);
8984 * Register a parser for a prefix-like operator.
8986 * @param parser the parser function
8987 * @param token_type the token type of the prefix token
8989 static void register_expression_parser(parse_expression_function parser,
8992 expression_parser_function_t *entry = &expression_parsers[token_type];
8994 if (entry->parser != NULL) {
8995 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8996 panic("trying to register multiple expression parsers for a token");
8998 entry->parser = parser;
9002 * Register a parser for an infix operator with given precedence.
9004 * @param parser the parser function
9005 * @param token_type the token type of the infix operator
9006 * @param precedence the precedence of the operator
9008 static void register_infix_parser(parse_expression_infix_function parser,
9009 int token_type, unsigned precedence)
9011 expression_parser_function_t *entry = &expression_parsers[token_type];
9013 if (entry->infix_parser != NULL) {
9014 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9015 panic("trying to register multiple infix expression parsers for a "
9018 entry->infix_parser = parser;
9019 entry->infix_precedence = precedence;
9023 * Initialize the expression parsers.
9025 static void init_expression_parsers(void)
9027 memset(&expression_parsers, 0, sizeof(expression_parsers));
9029 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9030 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9031 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9032 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9033 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9034 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9035 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9036 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9037 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9038 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9039 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9040 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9041 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9042 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9043 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9044 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9045 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9046 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9047 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9048 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9049 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9050 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9051 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9052 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9053 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9054 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9055 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9056 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9057 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9058 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9059 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9060 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9061 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9062 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9063 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9064 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9065 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9067 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9068 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9069 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9070 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9071 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9072 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9073 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9074 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9075 register_expression_parser(parse_sizeof, T_sizeof);
9076 register_expression_parser(parse_alignof, T___alignof__);
9077 register_expression_parser(parse_extension, T___extension__);
9078 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9079 register_expression_parser(parse_delete, T_delete);
9080 register_expression_parser(parse_throw, T_throw);
9084 * Parse a asm statement arguments specification.
9086 static asm_argument_t *parse_asm_arguments(bool is_out)
9088 asm_argument_t *result = NULL;
9089 asm_argument_t *last = NULL;
9091 while (token.type == T_STRING_LITERAL || token.type == '[') {
9092 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9093 memset(argument, 0, sizeof(argument[0]));
9095 if (token.type == '[') {
9097 if (token.type != T_IDENTIFIER) {
9098 parse_error_expected("while parsing asm argument",
9099 T_IDENTIFIER, NULL);
9102 argument->symbol = token.v.symbol;
9107 argument->constraints = parse_string_literals();
9109 add_anchor_token(')');
9110 expression_t *expression = parse_expression();
9111 rem_anchor_token(')');
9113 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9114 * change size or type representation (e.g. int -> long is ok, but
9115 * int -> float is not) */
9116 if (expression->kind == EXPR_UNARY_CAST) {
9117 type_t *const type = expression->base.type;
9118 type_kind_t const kind = type->kind;
9119 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9122 if (kind == TYPE_ATOMIC) {
9123 atomic_type_kind_t const akind = type->atomic.akind;
9124 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9125 size = get_atomic_type_size(akind);
9127 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9128 size = get_atomic_type_size(get_intptr_kind());
9132 expression_t *const value = expression->unary.value;
9133 type_t *const value_type = value->base.type;
9134 type_kind_t const value_kind = value_type->kind;
9136 unsigned value_flags;
9137 unsigned value_size;
9138 if (value_kind == TYPE_ATOMIC) {
9139 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9140 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9141 value_size = get_atomic_type_size(value_akind);
9142 } else if (value_kind == TYPE_POINTER) {
9143 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9144 value_size = get_atomic_type_size(get_intptr_kind());
9149 if (value_flags != flags || value_size != size)
9153 } while (expression->kind == EXPR_UNARY_CAST);
9157 if (!is_lvalue(expression)) {
9158 errorf(&expression->base.source_position,
9159 "asm output argument is not an lvalue");
9162 if (argument->constraints.begin[0] == '+')
9163 mark_vars_read(expression, NULL);
9165 mark_vars_read(expression, NULL);
9167 argument->expression = expression;
9170 set_address_taken(expression, true);
9173 last->next = argument;
9179 if (token.type != ',')
9190 * Parse a asm statement clobber specification.
9192 static asm_clobber_t *parse_asm_clobbers(void)
9194 asm_clobber_t *result = NULL;
9195 asm_clobber_t *last = NULL;
9197 while(token.type == T_STRING_LITERAL) {
9198 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9199 clobber->clobber = parse_string_literals();
9202 last->next = clobber;
9208 if (token.type != ',')
9217 * Parse an asm statement.
9219 static statement_t *parse_asm_statement(void)
9221 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9222 asm_statement_t *asm_statement = &statement->asms;
9226 if (token.type == T_volatile) {
9228 asm_statement->is_volatile = true;
9232 add_anchor_token(')');
9233 add_anchor_token(':');
9234 asm_statement->asm_text = parse_string_literals();
9236 if (token.type != ':') {
9237 rem_anchor_token(':');
9242 asm_statement->outputs = parse_asm_arguments(true);
9243 if (token.type != ':') {
9244 rem_anchor_token(':');
9249 asm_statement->inputs = parse_asm_arguments(false);
9250 if (token.type != ':') {
9251 rem_anchor_token(':');
9254 rem_anchor_token(':');
9257 asm_statement->clobbers = parse_asm_clobbers();
9260 rem_anchor_token(')');
9264 if (asm_statement->outputs == NULL) {
9265 /* GCC: An 'asm' instruction without any output operands will be treated
9266 * identically to a volatile 'asm' instruction. */
9267 asm_statement->is_volatile = true;
9272 return create_invalid_statement();
9276 * Parse a case statement.
9278 static statement_t *parse_case_statement(void)
9280 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9281 source_position_t *const pos = &statement->base.source_position;
9285 expression_t *const expression = parse_expression();
9286 statement->case_label.expression = expression;
9287 if (!is_constant_expression(expression)) {
9288 /* This check does not prevent the error message in all cases of an
9289 * prior error while parsing the expression. At least it catches the
9290 * common case of a mistyped enum entry. */
9291 if (is_type_valid(skip_typeref(expression->base.type))) {
9292 errorf(pos, "case label does not reduce to an integer constant");
9294 statement->case_label.is_bad = true;
9296 long const val = fold_constant(expression);
9297 statement->case_label.first_case = val;
9298 statement->case_label.last_case = val;
9302 if (token.type == T_DOTDOTDOT) {
9304 expression_t *const end_range = parse_expression();
9305 statement->case_label.end_range = end_range;
9306 if (!is_constant_expression(end_range)) {
9307 /* This check does not prevent the error message in all cases of an
9308 * prior error while parsing the expression. At least it catches the
9309 * common case of a mistyped enum entry. */
9310 if (is_type_valid(skip_typeref(end_range->base.type))) {
9311 errorf(pos, "case range does not reduce to an integer constant");
9313 statement->case_label.is_bad = true;
9315 long const val = fold_constant(end_range);
9316 statement->case_label.last_case = val;
9318 if (warning.other && val < statement->case_label.first_case) {
9319 statement->case_label.is_empty_range = true;
9320 warningf(pos, "empty range specified");
9326 PUSH_PARENT(statement);
9330 if (current_switch != NULL) {
9331 if (! statement->case_label.is_bad) {
9332 /* Check for duplicate case values */
9333 case_label_statement_t *c = &statement->case_label;
9334 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9335 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9338 if (c->last_case < l->first_case || c->first_case > l->last_case)
9341 errorf(pos, "duplicate case value (previously used %P)",
9342 &l->base.source_position);
9346 /* link all cases into the switch statement */
9347 if (current_switch->last_case == NULL) {
9348 current_switch->first_case = &statement->case_label;
9350 current_switch->last_case->next = &statement->case_label;
9352 current_switch->last_case = &statement->case_label;
9354 errorf(pos, "case label not within a switch statement");
9357 statement_t *const inner_stmt = parse_statement();
9358 statement->case_label.statement = inner_stmt;
9359 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9360 errorf(&inner_stmt->base.source_position, "declaration after case label");
9367 return create_invalid_statement();
9371 * Parse a default statement.
9373 static statement_t *parse_default_statement(void)
9375 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9379 PUSH_PARENT(statement);
9382 if (current_switch != NULL) {
9383 const case_label_statement_t *def_label = current_switch->default_label;
9384 if (def_label != NULL) {
9385 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9386 &def_label->base.source_position);
9388 current_switch->default_label = &statement->case_label;
9390 /* link all cases into the switch statement */
9391 if (current_switch->last_case == NULL) {
9392 current_switch->first_case = &statement->case_label;
9394 current_switch->last_case->next = &statement->case_label;
9396 current_switch->last_case = &statement->case_label;
9399 errorf(&statement->base.source_position,
9400 "'default' label not within a switch statement");
9403 statement_t *const inner_stmt = parse_statement();
9404 statement->case_label.statement = inner_stmt;
9405 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9406 errorf(&inner_stmt->base.source_position, "declaration after default label");
9413 return create_invalid_statement();
9417 * Parse a label statement.
9419 static statement_t *parse_label_statement(void)
9421 assert(token.type == T_IDENTIFIER);
9422 symbol_t *symbol = token.v.symbol;
9423 label_t *label = get_label(symbol);
9425 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9426 statement->label.label = label;
9430 PUSH_PARENT(statement);
9432 /* if statement is already set then the label is defined twice,
9433 * otherwise it was just mentioned in a goto/local label declaration so far
9435 if (label->statement != NULL) {
9436 errorf(HERE, "duplicate label '%Y' (declared %P)",
9437 symbol, &label->base.source_position);
9439 label->base.source_position = token.source_position;
9440 label->statement = statement;
9445 if (token.type == '}') {
9446 /* TODO only warn? */
9447 if (warning.other && false) {
9448 warningf(HERE, "label at end of compound statement");
9449 statement->label.statement = create_empty_statement();
9451 errorf(HERE, "label at end of compound statement");
9452 statement->label.statement = create_invalid_statement();
9454 } else if (token.type == ';') {
9455 /* Eat an empty statement here, to avoid the warning about an empty
9456 * statement after a label. label:; is commonly used to have a label
9457 * before a closing brace. */
9458 statement->label.statement = create_empty_statement();
9461 statement_t *const inner_stmt = parse_statement();
9462 statement->label.statement = inner_stmt;
9463 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9464 errorf(&inner_stmt->base.source_position, "declaration after label");
9468 /* remember the labels in a list for later checking */
9469 if (label_last == NULL) {
9470 label_first = &statement->label;
9472 label_last->next = &statement->label;
9474 label_last = &statement->label;
9481 * Parse an if statement.
9483 static statement_t *parse_if(void)
9485 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9489 PUSH_PARENT(statement);
9491 add_anchor_token('{');
9494 add_anchor_token(')');
9495 expression_t *const expr = parse_expression();
9496 statement->ifs.condition = expr;
9497 mark_vars_read(expr, NULL);
9498 rem_anchor_token(')');
9502 rem_anchor_token('{');
9504 add_anchor_token(T_else);
9505 statement->ifs.true_statement = parse_statement();
9506 rem_anchor_token(T_else);
9508 if (token.type == T_else) {
9510 statement->ifs.false_statement = parse_statement();
9518 * Check that all enums are handled in a switch.
9520 * @param statement the switch statement to check
9522 static void check_enum_cases(const switch_statement_t *statement) {
9523 const type_t *type = skip_typeref(statement->expression->base.type);
9524 if (! is_type_enum(type))
9526 const enum_type_t *enumt = &type->enumt;
9528 /* if we have a default, no warnings */
9529 if (statement->default_label != NULL)
9532 /* FIXME: calculation of value should be done while parsing */
9533 /* TODO: quadratic algorithm here. Change to an n log n one */
9534 long last_value = -1;
9535 const entity_t *entry = enumt->enume->base.next;
9536 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9537 entry = entry->base.next) {
9538 const expression_t *expression = entry->enum_value.value;
9539 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9541 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9542 if (l->expression == NULL)
9544 if (l->first_case <= value && value <= l->last_case) {
9550 warningf(&statement->base.source_position,
9551 "enumeration value '%Y' not handled in switch",
9552 entry->base.symbol);
9559 * Parse a switch statement.
9561 static statement_t *parse_switch(void)
9563 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9567 PUSH_PARENT(statement);
9570 add_anchor_token(')');
9571 expression_t *const expr = parse_expression();
9572 mark_vars_read(expr, NULL);
9573 type_t * type = skip_typeref(expr->base.type);
9574 if (is_type_integer(type)) {
9575 type = promote_integer(type);
9576 if (warning.traditional) {
9577 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9578 warningf(&expr->base.source_position,
9579 "'%T' switch expression not converted to '%T' in ISO C",
9583 } else if (is_type_valid(type)) {
9584 errorf(&expr->base.source_position,
9585 "switch quantity is not an integer, but '%T'", type);
9586 type = type_error_type;
9588 statement->switchs.expression = create_implicit_cast(expr, type);
9590 rem_anchor_token(')');
9592 switch_statement_t *rem = current_switch;
9593 current_switch = &statement->switchs;
9594 statement->switchs.body = parse_statement();
9595 current_switch = rem;
9597 if (warning.switch_default &&
9598 statement->switchs.default_label == NULL) {
9599 warningf(&statement->base.source_position, "switch has no default case");
9601 if (warning.switch_enum)
9602 check_enum_cases(&statement->switchs);
9608 return create_invalid_statement();
9611 static statement_t *parse_loop_body(statement_t *const loop)
9613 statement_t *const rem = current_loop;
9614 current_loop = loop;
9616 statement_t *const body = parse_statement();
9623 * Parse a while statement.
9625 static statement_t *parse_while(void)
9627 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9631 PUSH_PARENT(statement);
9634 add_anchor_token(')');
9635 expression_t *const cond = parse_expression();
9636 statement->whiles.condition = cond;
9637 mark_vars_read(cond, NULL);
9638 rem_anchor_token(')');
9641 statement->whiles.body = parse_loop_body(statement);
9647 return create_invalid_statement();
9651 * Parse a do statement.
9653 static statement_t *parse_do(void)
9655 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9659 PUSH_PARENT(statement);
9661 add_anchor_token(T_while);
9662 statement->do_while.body = parse_loop_body(statement);
9663 rem_anchor_token(T_while);
9667 add_anchor_token(')');
9668 expression_t *const cond = parse_expression();
9669 statement->do_while.condition = cond;
9670 mark_vars_read(cond, NULL);
9671 rem_anchor_token(')');
9679 return create_invalid_statement();
9683 * Parse a for statement.
9685 static statement_t *parse_for(void)
9687 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9691 PUSH_PARENT(statement);
9693 size_t const top = environment_top();
9694 scope_push(&statement->fors.scope);
9697 add_anchor_token(')');
9699 if (token.type != ';') {
9700 if (is_declaration_specifier(&token, false)) {
9701 parse_declaration(record_entity);
9703 add_anchor_token(';');
9704 expression_t *const init = parse_expression();
9705 statement->fors.initialisation = init;
9706 mark_vars_read(init, VAR_ANY);
9707 if (warning.unused_value && !expression_has_effect(init)) {
9708 warningf(&init->base.source_position,
9709 "initialisation of 'for'-statement has no effect");
9711 rem_anchor_token(';');
9718 if (token.type != ';') {
9719 add_anchor_token(';');
9720 expression_t *const cond = parse_expression();
9721 statement->fors.condition = cond;
9722 mark_vars_read(cond, NULL);
9723 rem_anchor_token(';');
9726 if (token.type != ')') {
9727 expression_t *const step = parse_expression();
9728 statement->fors.step = step;
9729 mark_vars_read(step, VAR_ANY);
9730 if (warning.unused_value && !expression_has_effect(step)) {
9731 warningf(&step->base.source_position,
9732 "step of 'for'-statement has no effect");
9736 rem_anchor_token(')');
9737 statement->fors.body = parse_loop_body(statement);
9739 assert(scope == &statement->fors.scope);
9741 environment_pop_to(top);
9748 rem_anchor_token(')');
9749 assert(scope == &statement->fors.scope);
9751 environment_pop_to(top);
9753 return create_invalid_statement();
9757 * Parse a goto statement.
9759 static statement_t *parse_goto(void)
9761 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9764 if (GNU_MODE && token.type == '*') {
9766 expression_t *expression = parse_expression();
9767 mark_vars_read(expression, NULL);
9769 /* Argh: although documentation say the expression must be of type void *,
9770 * gcc excepts anything that can be casted into void * without error */
9771 type_t *type = expression->base.type;
9773 if (type != type_error_type) {
9774 if (!is_type_pointer(type) && !is_type_integer(type)) {
9775 errorf(&expression->base.source_position,
9776 "cannot convert to a pointer type");
9777 } else if (warning.other && type != type_void_ptr) {
9778 warningf(&expression->base.source_position,
9779 "type of computed goto expression should be 'void*' not '%T'", type);
9781 expression = create_implicit_cast(expression, type_void_ptr);
9784 statement->gotos.expression = expression;
9786 if (token.type != T_IDENTIFIER) {
9788 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9790 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9794 symbol_t *symbol = token.v.symbol;
9797 statement->gotos.label = get_label(symbol);
9800 /* remember the goto's in a list for later checking */
9801 if (goto_last == NULL) {
9802 goto_first = &statement->gotos;
9804 goto_last->next = &statement->gotos;
9806 goto_last = &statement->gotos;
9812 return create_invalid_statement();
9816 * Parse a continue statement.
9818 static statement_t *parse_continue(void)
9820 if (current_loop == NULL) {
9821 errorf(HERE, "continue statement not within loop");
9824 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9834 * Parse a break statement.
9836 static statement_t *parse_break(void)
9838 if (current_switch == NULL && current_loop == NULL) {
9839 errorf(HERE, "break statement not within loop or switch");
9842 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9852 * Parse a __leave statement.
9854 static statement_t *parse_leave_statement(void)
9856 if (current_try == NULL) {
9857 errorf(HERE, "__leave statement not within __try");
9860 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9870 * Check if a given entity represents a local variable.
9872 static bool is_local_variable(const entity_t *entity)
9874 if (entity->kind != ENTITY_VARIABLE)
9877 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9878 case STORAGE_CLASS_AUTO:
9879 case STORAGE_CLASS_REGISTER: {
9880 const type_t *type = skip_typeref(entity->declaration.type);
9881 if (is_type_function(type)) {
9893 * Check if a given expression represents a local variable.
9895 static bool expression_is_local_variable(const expression_t *expression)
9897 if (expression->base.kind != EXPR_REFERENCE) {
9900 const entity_t *entity = expression->reference.entity;
9901 return is_local_variable(entity);
9905 * Check if a given expression represents a local variable and
9906 * return its declaration then, else return NULL.
9908 entity_t *expression_is_variable(const expression_t *expression)
9910 if (expression->base.kind != EXPR_REFERENCE) {
9913 entity_t *entity = expression->reference.entity;
9914 if (entity->kind != ENTITY_VARIABLE)
9921 * Parse a return statement.
9923 static statement_t *parse_return(void)
9927 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9929 expression_t *return_value = NULL;
9930 if (token.type != ';') {
9931 return_value = parse_expression();
9932 mark_vars_read(return_value, NULL);
9935 const type_t *const func_type = current_function->base.type;
9936 assert(is_type_function(func_type));
9937 type_t *const return_type = skip_typeref(func_type->function.return_type);
9939 if (return_value != NULL) {
9940 type_t *return_value_type = skip_typeref(return_value->base.type);
9942 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
9943 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9944 if (warning.other) {
9945 warningf(&statement->base.source_position,
9946 "'return' with a value, in function returning void");
9948 return_value = NULL;
9950 assign_error_t error = semantic_assign(return_type, return_value);
9951 report_assign_error(error, return_type, return_value, "'return'",
9952 &statement->base.source_position);
9953 return_value = create_implicit_cast(return_value, return_type);
9955 /* check for returning address of a local var */
9956 if (warning.other && return_value != NULL
9957 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9958 const expression_t *expression = return_value->unary.value;
9959 if (expression_is_local_variable(expression)) {
9960 warningf(&statement->base.source_position,
9961 "function returns address of local variable");
9964 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9965 warningf(&statement->base.source_position,
9966 "'return' without value, in function returning non-void");
9968 statement->returns.value = return_value;
9977 * Parse a declaration statement.
9979 static statement_t *parse_declaration_statement(void)
9981 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9983 entity_t *before = scope->last_entity;
9985 parse_external_declaration();
9987 parse_declaration(record_entity);
9989 if (before == NULL) {
9990 statement->declaration.declarations_begin = scope->entities;
9992 statement->declaration.declarations_begin = before->base.next;
9994 statement->declaration.declarations_end = scope->last_entity;
10000 * Parse an expression statement, ie. expr ';'.
10002 static statement_t *parse_expression_statement(void)
10004 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10006 expression_t *const expr = parse_expression();
10007 statement->expression.expression = expr;
10008 mark_vars_read(expr, VAR_ANY);
10017 * Parse a microsoft __try { } __finally { } or
10018 * __try{ } __except() { }
10020 static statement_t *parse_ms_try_statment(void)
10022 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10025 PUSH_PARENT(statement);
10027 ms_try_statement_t *rem = current_try;
10028 current_try = &statement->ms_try;
10029 statement->ms_try.try_statement = parse_compound_statement(false);
10034 if (token.type == T___except) {
10037 add_anchor_token(')');
10038 expression_t *const expr = parse_expression();
10039 mark_vars_read(expr, NULL);
10040 type_t * type = skip_typeref(expr->base.type);
10041 if (is_type_integer(type)) {
10042 type = promote_integer(type);
10043 } else if (is_type_valid(type)) {
10044 errorf(&expr->base.source_position,
10045 "__expect expression is not an integer, but '%T'", type);
10046 type = type_error_type;
10048 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10049 rem_anchor_token(')');
10051 statement->ms_try.final_statement = parse_compound_statement(false);
10052 } else if (token.type == T__finally) {
10054 statement->ms_try.final_statement = parse_compound_statement(false);
10056 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10057 return create_invalid_statement();
10061 return create_invalid_statement();
10064 static statement_t *parse_empty_statement(void)
10066 if (warning.empty_statement) {
10067 warningf(HERE, "statement is empty");
10069 statement_t *const statement = create_empty_statement();
10074 static statement_t *parse_local_label_declaration(void)
10076 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10080 entity_t *begin = NULL, *end = NULL;
10083 if (token.type != T_IDENTIFIER) {
10084 parse_error_expected("while parsing local label declaration",
10085 T_IDENTIFIER, NULL);
10088 symbol_t *symbol = token.v.symbol;
10089 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10090 if (entity != NULL && entity->base.parent_scope == scope) {
10091 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10092 symbol, &entity->base.source_position);
10094 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10096 entity->base.parent_scope = scope;
10097 entity->base.namespc = NAMESPACE_LABEL;
10098 entity->base.source_position = token.source_position;
10099 entity->base.symbol = symbol;
10102 end->base.next = entity;
10107 environment_push(entity);
10111 if (token.type != ',')
10117 statement->declaration.declarations_begin = begin;
10118 statement->declaration.declarations_end = end;
10123 * Parse a statement.
10124 * There's also parse_statement() which additionally checks for
10125 * "statement has no effect" warnings
10127 static statement_t *intern_parse_statement(void)
10129 statement_t *statement = NULL;
10131 /* declaration or statement */
10132 add_anchor_token(';');
10133 switch (token.type) {
10134 case T_IDENTIFIER: {
10135 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10136 if (la1_type == ':') {
10137 statement = parse_label_statement();
10138 } else if (is_typedef_symbol(token.v.symbol)) {
10139 statement = parse_declaration_statement();
10141 /* it's an identifier, the grammar says this must be an
10142 * expression statement. However it is common that users mistype
10143 * declaration types, so we guess a bit here to improve robustness
10144 * for incorrect programs */
10145 switch (la1_type) {
10147 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10148 goto expression_statment;
10153 statement = parse_declaration_statement();
10157 expression_statment:
10158 statement = parse_expression_statement();
10165 case T___extension__:
10166 /* This can be a prefix to a declaration or an expression statement.
10167 * We simply eat it now and parse the rest with tail recursion. */
10170 } while (token.type == T___extension__);
10171 bool old_gcc_extension = in_gcc_extension;
10172 in_gcc_extension = true;
10173 statement = parse_statement();
10174 in_gcc_extension = old_gcc_extension;
10178 statement = parse_declaration_statement();
10182 statement = parse_local_label_declaration();
10185 case ';': statement = parse_empty_statement(); break;
10186 case '{': statement = parse_compound_statement(false); break;
10187 case T___leave: statement = parse_leave_statement(); break;
10188 case T___try: statement = parse_ms_try_statment(); break;
10189 case T_asm: statement = parse_asm_statement(); break;
10190 case T_break: statement = parse_break(); break;
10191 case T_case: statement = parse_case_statement(); break;
10192 case T_continue: statement = parse_continue(); break;
10193 case T_default: statement = parse_default_statement(); break;
10194 case T_do: statement = parse_do(); break;
10195 case T_for: statement = parse_for(); break;
10196 case T_goto: statement = parse_goto(); break;
10197 case T_if: statement = parse_if(); break;
10198 case T_return: statement = parse_return(); break;
10199 case T_switch: statement = parse_switch(); break;
10200 case T_while: statement = parse_while(); break;
10203 statement = parse_expression_statement();
10207 errorf(HERE, "unexpected token %K while parsing statement", &token);
10208 statement = create_invalid_statement();
10213 rem_anchor_token(';');
10215 assert(statement != NULL
10216 && statement->base.source_position.input_name != NULL);
10222 * parse a statement and emits "statement has no effect" warning if needed
10223 * (This is really a wrapper around intern_parse_statement with check for 1
10224 * single warning. It is needed, because for statement expressions we have
10225 * to avoid the warning on the last statement)
10227 static statement_t *parse_statement(void)
10229 statement_t *statement = intern_parse_statement();
10231 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10232 expression_t *expression = statement->expression.expression;
10233 if (!expression_has_effect(expression)) {
10234 warningf(&expression->base.source_position,
10235 "statement has no effect");
10243 * Parse a compound statement.
10245 static statement_t *parse_compound_statement(bool inside_expression_statement)
10247 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10249 PUSH_PARENT(statement);
10252 add_anchor_token('}');
10254 size_t const top = environment_top();
10255 scope_push(&statement->compound.scope);
10257 statement_t **anchor = &statement->compound.statements;
10258 bool only_decls_so_far = true;
10259 while (token.type != '}') {
10260 if (token.type == T_EOF) {
10261 errorf(&statement->base.source_position,
10262 "EOF while parsing compound statement");
10265 statement_t *sub_statement = intern_parse_statement();
10266 if (is_invalid_statement(sub_statement)) {
10267 /* an error occurred. if we are at an anchor, return */
10273 if (warning.declaration_after_statement) {
10274 if (sub_statement->kind != STATEMENT_DECLARATION) {
10275 only_decls_so_far = false;
10276 } else if (!only_decls_so_far) {
10277 warningf(&sub_statement->base.source_position,
10278 "ISO C90 forbids mixed declarations and code");
10282 *anchor = sub_statement;
10284 while (sub_statement->base.next != NULL)
10285 sub_statement = sub_statement->base.next;
10287 anchor = &sub_statement->base.next;
10291 /* look over all statements again to produce no effect warnings */
10292 if (warning.unused_value) {
10293 statement_t *sub_statement = statement->compound.statements;
10294 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10295 if (sub_statement->kind != STATEMENT_EXPRESSION)
10297 /* don't emit a warning for the last expression in an expression
10298 * statement as it has always an effect */
10299 if (inside_expression_statement && sub_statement->base.next == NULL)
10302 expression_t *expression = sub_statement->expression.expression;
10303 if (!expression_has_effect(expression)) {
10304 warningf(&expression->base.source_position,
10305 "statement has no effect");
10311 rem_anchor_token('}');
10312 assert(scope == &statement->compound.scope);
10314 environment_pop_to(top);
10321 * Check for unused global static functions and variables
10323 static void check_unused_globals(void)
10325 if (!warning.unused_function && !warning.unused_variable)
10328 for (const entity_t *entity = file_scope->entities; entity != NULL;
10329 entity = entity->base.next) {
10330 if (!is_declaration(entity))
10333 const declaration_t *declaration = &entity->declaration;
10334 if (declaration->used ||
10335 declaration->modifiers & DM_UNUSED ||
10336 declaration->modifiers & DM_USED ||
10337 declaration->storage_class != STORAGE_CLASS_STATIC)
10340 type_t *const type = declaration->type;
10342 if (entity->kind == ENTITY_FUNCTION) {
10343 /* inhibit warning for static inline functions */
10344 if (entity->function.is_inline)
10347 s = entity->function.statement != NULL ? "defined" : "declared";
10352 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10353 type, declaration->base.symbol, s);
10357 static void parse_global_asm(void)
10359 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10364 statement->asms.asm_text = parse_string_literals();
10365 statement->base.next = unit->global_asm;
10366 unit->global_asm = statement;
10375 * Parse a translation unit.
10377 static void parse_translation_unit(void)
10379 add_anchor_token(T_EOF);
10382 unsigned char token_anchor_copy[T_LAST_TOKEN];
10383 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10387 bool anchor_leak = false;
10388 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10389 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10391 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10392 anchor_leak = true;
10395 if (in_gcc_extension) {
10396 errorf(HERE, "Leaked __extension__");
10397 anchor_leak = true;
10404 switch (token.type) {
10407 case T___extension__:
10408 case '(': /* for function declarations with implicit return type and
10409 * parenthesized declarator, i.e. (f)(void); */
10410 parse_external_declaration();
10414 parse_global_asm();
10418 rem_anchor_token(T_EOF);
10422 if (!strict_mode) {
10424 warningf(HERE, "stray ';' outside of function");
10431 errorf(HERE, "stray %K outside of function", &token);
10432 if (token.type == '(' || token.type == '{' || token.type == '[')
10433 eat_until_matching_token(token.type);
10443 * @return the translation unit or NULL if errors occurred.
10445 void start_parsing(void)
10447 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10448 label_stack = NEW_ARR_F(stack_entry_t, 0);
10449 diagnostic_count = 0;
10453 type_set_output(stderr);
10454 ast_set_output(stderr);
10456 assert(unit == NULL);
10457 unit = allocate_ast_zero(sizeof(unit[0]));
10459 assert(file_scope == NULL);
10460 file_scope = &unit->scope;
10462 assert(scope == NULL);
10463 scope_push(&unit->scope);
10466 translation_unit_t *finish_parsing(void)
10468 /* do NOT use scope_pop() here, this will crash, will it by hand */
10469 assert(scope == &unit->scope);
10472 assert(file_scope == &unit->scope);
10473 check_unused_globals();
10476 DEL_ARR_F(environment_stack);
10477 DEL_ARR_F(label_stack);
10479 translation_unit_t *result = unit;
10486 lookahead_bufpos = 0;
10487 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10490 parse_translation_unit();
10494 * Initialize the parser.
10496 void init_parser(void)
10498 sym_anonymous = symbol_table_insert("<anonymous>");
10500 if (c_mode & _MS) {
10501 /* add predefined symbols for extended-decl-modifier */
10502 sym_align = symbol_table_insert("align");
10503 sym_allocate = symbol_table_insert("allocate");
10504 sym_dllimport = symbol_table_insert("dllimport");
10505 sym_dllexport = symbol_table_insert("dllexport");
10506 sym_naked = symbol_table_insert("naked");
10507 sym_noinline = symbol_table_insert("noinline");
10508 sym_noreturn = symbol_table_insert("noreturn");
10509 sym_nothrow = symbol_table_insert("nothrow");
10510 sym_novtable = symbol_table_insert("novtable");
10511 sym_property = symbol_table_insert("property");
10512 sym_get = symbol_table_insert("get");
10513 sym_put = symbol_table_insert("put");
10514 sym_selectany = symbol_table_insert("selectany");
10515 sym_thread = symbol_table_insert("thread");
10516 sym_uuid = symbol_table_insert("uuid");
10517 sym_deprecated = symbol_table_insert("deprecated");
10518 sym_restrict = symbol_table_insert("restrict");
10519 sym_noalias = symbol_table_insert("noalias");
10521 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10523 init_expression_parsers();
10524 obstack_init(&temp_obst);
10526 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10527 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10531 * Terminate the parser.
10533 void exit_parser(void)
10535 obstack_free(&temp_obst, NULL);