2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 2
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool have_arguments; /**< True, if this attribute has arguments. */
68 atomic_type_kind_t akind;
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
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;
101 * Capture a MS __base extension.
103 typedef struct based_spec_t {
104 source_position_t source_position;
105 variable_t *base_variable;
108 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
110 /** The current token. */
111 static token_t token;
112 /** The lookahead ring-buffer. */
113 static token_t lookahead_buffer[MAX_LOOKAHEAD];
114 /** Position of the next token in the lookahead buffer. */
115 static int lookahead_bufpos;
116 static stack_entry_t *environment_stack = NULL;
117 static stack_entry_t *label_stack = NULL;
118 static scope_t *file_scope = NULL;
119 static scope_t *current_scope = NULL;
120 /** Point to the current function declaration if inside a function. */
121 static function_t *current_function = NULL;
122 static entity_t *current_init_decl = NULL;
123 static switch_statement_t *current_switch = NULL;
124 static statement_t *current_loop = NULL;
125 static statement_t *current_parent = NULL;
126 static ms_try_statement_t *current_try = NULL;
127 static linkage_kind_t current_linkage = LINKAGE_INVALID;
128 static goto_statement_t *goto_first = NULL;
129 static goto_statement_t **goto_anchor = NULL;
130 static label_statement_t *label_first = NULL;
131 static label_statement_t **label_anchor = NULL;
132 /** current translation unit. */
133 static translation_unit_t *unit = NULL;
134 /** true if we are in a type property context (evaluation only for type. */
135 static bool in_type_prop = false;
136 /** true in we are in a __extension__ context. */
137 static bool in_gcc_extension = false;
138 static struct obstack temp_obst;
139 static entity_t *anonymous_entity;
142 #define PUSH_PARENT(stmt) \
143 statement_t *const prev_parent = current_parent; \
144 ((void)(current_parent = (stmt)))
145 #define POP_PARENT ((void)(current_parent = prev_parent))
147 /** special symbol used for anonymous entities. */
148 static const symbol_t *sym_anonymous = NULL;
150 /* symbols for Microsoft extended-decl-modifier */
151 static const symbol_t *sym_align = NULL;
152 static const symbol_t *sym_allocate = NULL;
153 static const symbol_t *sym_dllimport = NULL;
154 static const symbol_t *sym_dllexport = NULL;
155 static const symbol_t *sym_naked = NULL;
156 static const symbol_t *sym_noinline = NULL;
157 static const symbol_t *sym_noreturn = NULL;
158 static const symbol_t *sym_nothrow = NULL;
159 static const symbol_t *sym_novtable = NULL;
160 static const symbol_t *sym_property = NULL;
161 static const symbol_t *sym_get = NULL;
162 static const symbol_t *sym_put = NULL;
163 static const symbol_t *sym_selectany = NULL;
164 static const symbol_t *sym_thread = NULL;
165 static const symbol_t *sym_uuid = NULL;
166 static const symbol_t *sym_deprecated = NULL;
167 static const symbol_t *sym_restrict = NULL;
168 static const symbol_t *sym_noalias = NULL;
170 /** The token anchor set */
171 static unsigned char token_anchor_set[T_LAST_TOKEN];
173 /** The current source position. */
174 #define HERE (&token.source_position)
176 /** true if we are in GCC mode. */
177 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
179 static type_t *type_valist;
181 static statement_t *parse_compound_statement(bool inside_expression_statement);
182 static statement_t *parse_statement(void);
184 static expression_t *parse_sub_expression(precedence_t);
185 static expression_t *parse_expression(void);
186 static type_t *parse_typename(void);
187 static void parse_externals(void);
188 static void parse_external(void);
190 static void parse_compound_type_entries(compound_t *compound_declaration);
191 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
192 bool may_be_abstract,
193 bool create_compound_member);
194 static entity_t *record_entity(entity_t *entity, bool is_definition);
196 static void semantic_comparison(binary_expression_t *expression);
198 #define STORAGE_CLASSES \
199 STORAGE_CLASSES_NO_EXTERN \
202 #define STORAGE_CLASSES_NO_EXTERN \
209 #define TYPE_QUALIFIERS \
214 case T__forceinline: \
215 case T___attribute__:
217 #define COMPLEX_SPECIFIERS \
219 #define IMAGINARY_SPECIFIERS \
222 #define TYPE_SPECIFIERS \
224 case T___builtin_va_list: \
243 #define DECLARATION_START \
248 #define DECLARATION_START_NO_EXTERN \
249 STORAGE_CLASSES_NO_EXTERN \
253 #define TYPENAME_START \
257 #define EXPRESSION_START \
266 case T_CHARACTER_CONSTANT: \
267 case T_FLOATINGPOINT: \
271 case T_STRING_LITERAL: \
272 case T_WIDE_CHARACTER_CONSTANT: \
273 case T_WIDE_STRING_LITERAL: \
274 case T___FUNCDNAME__: \
275 case T___FUNCSIG__: \
276 case T___FUNCTION__: \
277 case T___PRETTY_FUNCTION__: \
278 case T___alignof__: \
279 case T___builtin_alloca: \
280 case T___builtin_classify_type: \
281 case T___builtin_constant_p: \
282 case T___builtin_expect: \
283 case T___builtin_huge_val: \
284 case T___builtin_inf: \
285 case T___builtin_inff: \
286 case T___builtin_infl: \
287 case T___builtin_isgreater: \
288 case T___builtin_isgreaterequal: \
289 case T___builtin_isless: \
290 case T___builtin_islessequal: \
291 case T___builtin_islessgreater: \
292 case T___builtin_isunordered: \
293 case T___builtin_nan: \
294 case T___builtin_nanf: \
295 case T___builtin_nanl: \
296 case T___builtin_offsetof: \
297 case T___builtin_prefetch: \
298 case T___builtin_va_arg: \
299 case T___builtin_va_end: \
300 case T___builtin_va_start: \
311 * Allocate an AST node with given size and
312 * initialize all fields with zero.
314 static void *allocate_ast_zero(size_t size)
316 void *res = allocate_ast(size);
317 memset(res, 0, size);
321 static size_t get_entity_struct_size(entity_kind_t kind)
323 static const size_t sizes[] = {
324 [ENTITY_VARIABLE] = sizeof(variable_t),
325 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
326 [ENTITY_FUNCTION] = sizeof(function_t),
327 [ENTITY_TYPEDEF] = sizeof(typedef_t),
328 [ENTITY_STRUCT] = sizeof(compound_t),
329 [ENTITY_UNION] = sizeof(compound_t),
330 [ENTITY_ENUM] = sizeof(enum_t),
331 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
332 [ENTITY_LABEL] = sizeof(label_t),
333 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
334 [ENTITY_NAMESPACE] = sizeof(namespace_t)
336 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
337 assert(sizes[kind] != 0);
341 static entity_t *allocate_entity_zero(entity_kind_t kind)
343 size_t size = get_entity_struct_size(kind);
344 entity_t *entity = allocate_ast_zero(size);
350 * Returns the size of a statement node.
352 * @param kind the statement kind
354 static size_t get_statement_struct_size(statement_kind_t kind)
356 static const size_t sizes[] = {
357 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
358 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
359 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
360 [STATEMENT_RETURN] = sizeof(return_statement_t),
361 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
362 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
363 [STATEMENT_IF] = sizeof(if_statement_t),
364 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
365 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
366 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
367 [STATEMENT_BREAK] = sizeof(statement_base_t),
368 [STATEMENT_GOTO] = sizeof(goto_statement_t),
369 [STATEMENT_LABEL] = sizeof(label_statement_t),
370 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
371 [STATEMENT_WHILE] = sizeof(while_statement_t),
372 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
373 [STATEMENT_FOR] = sizeof(for_statement_t),
374 [STATEMENT_ASM] = sizeof(asm_statement_t),
375 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
376 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
378 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
379 assert(sizes[kind] != 0);
384 * Returns the size of an expression node.
386 * @param kind the expression kind
388 static size_t get_expression_struct_size(expression_kind_t kind)
390 static const size_t sizes[] = {
391 [EXPR_INVALID] = sizeof(expression_base_t),
392 [EXPR_REFERENCE] = sizeof(reference_expression_t),
393 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
394 [EXPR_CONST] = sizeof(const_expression_t),
395 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
396 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
397 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
398 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
399 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
400 [EXPR_CALL] = sizeof(call_expression_t),
401 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
402 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
403 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
404 [EXPR_SELECT] = sizeof(select_expression_t),
405 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
406 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
407 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
408 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
409 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
410 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
411 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
412 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
413 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
414 [EXPR_VA_START] = sizeof(va_start_expression_t),
415 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
416 [EXPR_STATEMENT] = sizeof(statement_expression_t),
417 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
419 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
420 return sizes[EXPR_UNARY_FIRST];
422 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
423 return sizes[EXPR_BINARY_FIRST];
425 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
426 assert(sizes[kind] != 0);
431 * Allocate a statement node of given kind and initialize all
434 static statement_t *allocate_statement_zero(statement_kind_t kind)
436 size_t size = get_statement_struct_size(kind);
437 statement_t *res = allocate_ast_zero(size);
439 res->base.kind = kind;
440 res->base.parent = current_parent;
441 res->base.source_position = token.source_position;
446 * Allocate an expression node of given kind and initialize all
449 static expression_t *allocate_expression_zero(expression_kind_t kind)
451 size_t size = get_expression_struct_size(kind);
452 expression_t *res = allocate_ast_zero(size);
454 res->base.kind = kind;
455 res->base.type = type_error_type;
456 res->base.source_position = token.source_position;
461 * Creates a new invalid expression.
463 static expression_t *create_invalid_expression(void)
465 return allocate_expression_zero(EXPR_INVALID);
469 * Creates a new invalid statement.
471 static statement_t *create_invalid_statement(void)
473 return allocate_statement_zero(STATEMENT_INVALID);
477 * Allocate a new empty statement.
479 static statement_t *create_empty_statement(void)
481 return allocate_statement_zero(STATEMENT_EMPTY);
485 * Returns the size of a type node.
487 * @param kind the type kind
489 static size_t get_type_struct_size(type_kind_t kind)
491 static const size_t sizes[] = {
492 [TYPE_ATOMIC] = sizeof(atomic_type_t),
493 [TYPE_COMPLEX] = sizeof(complex_type_t),
494 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
495 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
496 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
497 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
498 [TYPE_ENUM] = sizeof(enum_type_t),
499 [TYPE_FUNCTION] = sizeof(function_type_t),
500 [TYPE_POINTER] = sizeof(pointer_type_t),
501 [TYPE_ARRAY] = sizeof(array_type_t),
502 [TYPE_BUILTIN] = sizeof(builtin_type_t),
503 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
504 [TYPE_TYPEOF] = sizeof(typeof_type_t),
506 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
507 assert(kind <= TYPE_TYPEOF);
508 assert(sizes[kind] != 0);
513 * Allocate a type node of given kind and initialize all
516 * @param kind type kind to allocate
518 static type_t *allocate_type_zero(type_kind_t kind)
520 size_t size = get_type_struct_size(kind);
521 type_t *res = obstack_alloc(type_obst, size);
522 memset(res, 0, size);
523 res->base.kind = kind;
529 * Returns the size of an initializer node.
531 * @param kind the initializer kind
533 static size_t get_initializer_size(initializer_kind_t kind)
535 static const size_t sizes[] = {
536 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
537 [INITIALIZER_STRING] = sizeof(initializer_string_t),
538 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
539 [INITIALIZER_LIST] = sizeof(initializer_list_t),
540 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
542 assert(kind < sizeof(sizes) / sizeof(*sizes));
543 assert(sizes[kind] != 0);
548 * Allocate an initializer node of given kind and initialize all
551 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
553 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
560 * Free a type from the type obstack.
562 static void free_type(void *type)
564 obstack_free(type_obst, type);
568 * Returns the index of the top element of the environment stack.
570 static size_t environment_top(void)
572 return ARR_LEN(environment_stack);
576 * Returns the index of the top element of the global label stack.
578 static size_t label_top(void)
580 return ARR_LEN(label_stack);
584 * Return the next token.
586 static inline void next_token(void)
588 token = lookahead_buffer[lookahead_bufpos];
589 lookahead_buffer[lookahead_bufpos] = lexer_token;
592 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
595 print_token(stderr, &token);
596 fprintf(stderr, "\n");
601 * Return the next token with a given lookahead.
603 static inline const token_t *look_ahead(int num)
605 assert(num > 0 && num <= MAX_LOOKAHEAD);
606 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
607 return &lookahead_buffer[pos];
611 * Adds a token to the token anchor set (a multi-set).
613 static void add_anchor_token(int token_type)
615 assert(0 <= token_type && token_type < T_LAST_TOKEN);
616 ++token_anchor_set[token_type];
619 static int save_and_reset_anchor_state(int token_type)
621 assert(0 <= token_type && token_type < T_LAST_TOKEN);
622 int count = token_anchor_set[token_type];
623 token_anchor_set[token_type] = 0;
627 static void restore_anchor_state(int token_type, int count)
629 assert(0 <= token_type && token_type < T_LAST_TOKEN);
630 token_anchor_set[token_type] = count;
634 * Remove a token from the token anchor set (a multi-set).
636 static void rem_anchor_token(int token_type)
638 assert(0 <= token_type && token_type < T_LAST_TOKEN);
639 assert(token_anchor_set[token_type] != 0);
640 --token_anchor_set[token_type];
643 static bool at_anchor(void)
647 return token_anchor_set[token.type];
651 * Eat tokens until a matching token is found.
653 static void eat_until_matching_token(int type)
657 case '(': end_token = ')'; break;
658 case '{': end_token = '}'; break;
659 case '[': end_token = ']'; break;
660 default: end_token = type; break;
663 unsigned parenthesis_count = 0;
664 unsigned brace_count = 0;
665 unsigned bracket_count = 0;
666 while (token.type != end_token ||
667 parenthesis_count != 0 ||
669 bracket_count != 0) {
670 switch (token.type) {
672 case '(': ++parenthesis_count; break;
673 case '{': ++brace_count; break;
674 case '[': ++bracket_count; break;
677 if (parenthesis_count > 0)
687 if (bracket_count > 0)
690 if (token.type == end_token &&
691 parenthesis_count == 0 &&
705 * Eat input tokens until an anchor is found.
707 static void eat_until_anchor(void)
709 while (token_anchor_set[token.type] == 0) {
710 if (token.type == '(' || token.type == '{' || token.type == '[')
711 eat_until_matching_token(token.type);
716 static void eat_block(void)
718 eat_until_matching_token('{');
719 if (token.type == '}')
723 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
726 * Report a parse error because an expected token was not found.
729 #if defined __GNUC__ && __GNUC__ >= 4
730 __attribute__((sentinel))
732 void parse_error_expected(const char *message, ...)
734 if (message != NULL) {
735 errorf(HERE, "%s", message);
738 va_start(ap, message);
739 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
744 * Report an incompatible type.
746 static void type_error_incompatible(const char *msg,
747 const source_position_t *source_position, type_t *type1, type_t *type2)
749 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
754 * Expect the the current token is the expected token.
755 * If not, generate an error, eat the current statement,
756 * and goto the end_error label.
758 #define expect(expected) \
760 if (UNLIKELY(token.type != (expected))) { \
761 parse_error_expected(NULL, (expected), NULL); \
762 add_anchor_token(expected); \
763 eat_until_anchor(); \
764 if (token.type == expected) \
766 rem_anchor_token(expected); \
772 static void scope_push(scope_t *new_scope)
774 if (current_scope != NULL) {
775 new_scope->depth = current_scope->depth + 1;
777 new_scope->parent = current_scope;
778 current_scope = new_scope;
781 static void scope_pop(void)
783 current_scope = current_scope->parent;
787 * Search an entity by its symbol in a given namespace.
789 static entity_t *get_entity(const symbol_t *const symbol,
790 namespace_tag_t namespc)
792 entity_t *entity = symbol->entity;
793 for (; entity != NULL; entity = entity->base.symbol_next) {
794 if (entity->base.namespc == namespc)
802 * pushs an entity on the environment stack and links the corresponding symbol
805 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
807 symbol_t *symbol = entity->base.symbol;
808 entity_namespace_t namespc = entity->base.namespc;
809 assert(namespc != NAMESPACE_INVALID);
811 /* replace/add entity into entity list of the symbol */
814 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
819 /* replace an entry? */
820 if (iter->base.namespc == namespc) {
821 entity->base.symbol_next = iter->base.symbol_next;
827 /* remember old declaration */
829 entry.symbol = symbol;
830 entry.old_entity = iter;
831 entry.namespc = namespc;
832 ARR_APP1(stack_entry_t, *stack_ptr, entry);
836 * Push an entity on the environment stack.
838 static void environment_push(entity_t *entity)
840 assert(entity->base.source_position.input_name != NULL);
841 assert(entity->base.parent_scope != NULL);
842 stack_push(&environment_stack, entity);
846 * Push a declaration on the global label stack.
848 * @param declaration the declaration
850 static void label_push(entity_t *label)
852 /* we abuse the parameters scope as parent for the labels */
853 label->base.parent_scope = ¤t_function->parameters;
854 stack_push(&label_stack, label);
858 * pops symbols from the environment stack until @p new_top is the top element
860 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
862 stack_entry_t *stack = *stack_ptr;
863 size_t top = ARR_LEN(stack);
866 assert(new_top <= top);
870 for (i = top; i > new_top; --i) {
871 stack_entry_t *entry = &stack[i - 1];
873 entity_t *old_entity = entry->old_entity;
874 symbol_t *symbol = entry->symbol;
875 entity_namespace_t namespc = entry->namespc;
877 /* replace with old_entity/remove */
880 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
882 assert(iter != NULL);
883 /* replace an entry? */
884 if (iter->base.namespc == namespc)
888 /* restore definition from outer scopes (if there was one) */
889 if (old_entity != NULL) {
890 old_entity->base.symbol_next = iter->base.symbol_next;
891 *anchor = old_entity;
893 /* remove entry from list */
894 *anchor = iter->base.symbol_next;
898 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
902 * Pop all entries from the environment stack until the new_top
905 * @param new_top the new stack top
907 static void environment_pop_to(size_t new_top)
909 stack_pop_to(&environment_stack, new_top);
913 * Pop all entries from the global label stack until the new_top
916 * @param new_top the new stack top
918 static void label_pop_to(size_t new_top)
920 stack_pop_to(&label_stack, new_top);
923 static int get_akind_rank(atomic_type_kind_t akind)
928 static int get_rank(const type_t *type)
930 assert(!is_typeref(type));
931 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
932 * and esp. footnote 108). However we can't fold constants (yet), so we
933 * can't decide whether unsigned int is possible, while int always works.
934 * (unsigned int would be preferable when possible... for stuff like
935 * struct { enum { ... } bla : 4; } ) */
936 if (type->kind == TYPE_ENUM)
937 return get_akind_rank(ATOMIC_TYPE_INT);
939 assert(type->kind == TYPE_ATOMIC);
940 return get_akind_rank(type->atomic.akind);
943 static type_t *promote_integer(type_t *type)
945 if (type->kind == TYPE_BITFIELD)
946 type = type->bitfield.base_type;
948 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
955 * Create a cast expression.
957 * @param expression the expression to cast
958 * @param dest_type the destination type
960 static expression_t *create_cast_expression(expression_t *expression,
963 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
965 cast->unary.value = expression;
966 cast->base.type = dest_type;
972 * Check if a given expression represents the 0 pointer constant.
974 static bool is_null_pointer_constant(const expression_t *expression)
976 /* skip void* cast */
977 if (expression->kind == EXPR_UNARY_CAST
978 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
979 expression = expression->unary.value;
982 /* TODO: not correct yet, should be any constant integer expression
983 * which evaluates to 0 */
984 if (expression->kind != EXPR_CONST)
987 type_t *const type = skip_typeref(expression->base.type);
988 if (!is_type_integer(type))
991 return expression->conste.v.int_value == 0;
995 * Create an implicit cast expression.
997 * @param expression the expression to cast
998 * @param dest_type the destination type
1000 static expression_t *create_implicit_cast(expression_t *expression,
1003 type_t *const source_type = expression->base.type;
1005 if (source_type == dest_type)
1008 return create_cast_expression(expression, dest_type);
1011 typedef enum assign_error_t {
1013 ASSIGN_ERROR_INCOMPATIBLE,
1014 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1015 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1016 ASSIGN_WARNING_POINTER_FROM_INT,
1017 ASSIGN_WARNING_INT_FROM_POINTER
1020 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1021 const expression_t *const right,
1022 const char *context,
1023 const source_position_t *source_position)
1025 type_t *const orig_type_right = right->base.type;
1026 type_t *const type_left = skip_typeref(orig_type_left);
1027 type_t *const type_right = skip_typeref(orig_type_right);
1030 case ASSIGN_SUCCESS:
1032 case ASSIGN_ERROR_INCOMPATIBLE:
1033 errorf(source_position,
1034 "destination type '%T' in %s is incompatible with type '%T'",
1035 orig_type_left, context, orig_type_right);
1038 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1039 if (warning.other) {
1040 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1041 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1043 /* the left type has all qualifiers from the right type */
1044 unsigned missing_qualifiers
1045 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1046 warningf(source_position,
1047 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1048 orig_type_left, context, orig_type_right, missing_qualifiers);
1053 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1054 if (warning.other) {
1055 warningf(source_position,
1056 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1057 orig_type_left, context, right, orig_type_right);
1061 case ASSIGN_WARNING_POINTER_FROM_INT:
1062 if (warning.other) {
1063 warningf(source_position,
1064 "%s makes pointer '%T' from integer '%T' without a cast",
1065 context, orig_type_left, orig_type_right);
1069 case ASSIGN_WARNING_INT_FROM_POINTER:
1070 if (warning.other) {
1071 warningf(source_position,
1072 "%s makes integer '%T' from pointer '%T' without a cast",
1073 context, orig_type_left, orig_type_right);
1078 panic("invalid error value");
1082 /** Implements the rules from § 6.5.16.1 */
1083 static assign_error_t semantic_assign(type_t *orig_type_left,
1084 const expression_t *const right)
1086 type_t *const orig_type_right = right->base.type;
1087 type_t *const type_left = skip_typeref(orig_type_left);
1088 type_t *const type_right = skip_typeref(orig_type_right);
1090 if (is_type_pointer(type_left)) {
1091 if (is_null_pointer_constant(right)) {
1092 return ASSIGN_SUCCESS;
1093 } else if (is_type_pointer(type_right)) {
1094 type_t *points_to_left
1095 = skip_typeref(type_left->pointer.points_to);
1096 type_t *points_to_right
1097 = skip_typeref(type_right->pointer.points_to);
1098 assign_error_t res = ASSIGN_SUCCESS;
1100 /* the left type has all qualifiers from the right type */
1101 unsigned missing_qualifiers
1102 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1103 if (missing_qualifiers != 0) {
1104 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1107 points_to_left = get_unqualified_type(points_to_left);
1108 points_to_right = get_unqualified_type(points_to_right);
1110 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1113 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1114 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1115 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1118 if (!types_compatible(points_to_left, points_to_right)) {
1119 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1123 } else if (is_type_integer(type_right)) {
1124 return ASSIGN_WARNING_POINTER_FROM_INT;
1126 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1127 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1128 && is_type_pointer(type_right))) {
1129 return ASSIGN_SUCCESS;
1130 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1131 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1132 type_t *const unqual_type_left = get_unqualified_type(type_left);
1133 type_t *const unqual_type_right = get_unqualified_type(type_right);
1134 if (types_compatible(unqual_type_left, unqual_type_right)) {
1135 return ASSIGN_SUCCESS;
1137 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1138 return ASSIGN_WARNING_INT_FROM_POINTER;
1141 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1142 return ASSIGN_SUCCESS;
1144 return ASSIGN_ERROR_INCOMPATIBLE;
1147 static expression_t *parse_constant_expression(void)
1149 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1151 if (!is_constant_expression(result)) {
1152 errorf(&result->base.source_position,
1153 "expression '%E' is not constant\n", result);
1159 static expression_t *parse_assignment_expression(void)
1161 return parse_sub_expression(PREC_ASSIGNMENT);
1164 static string_t parse_string_literals(void)
1166 assert(token.type == T_STRING_LITERAL);
1167 string_t result = token.v.string;
1171 while (token.type == T_STRING_LITERAL) {
1172 result = concat_strings(&result, &token.v.string);
1179 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1180 [GNU_AK_CONST] = "const",
1181 [GNU_AK_VOLATILE] = "volatile",
1182 [GNU_AK_CDECL] = "cdecl",
1183 [GNU_AK_STDCALL] = "stdcall",
1184 [GNU_AK_FASTCALL] = "fastcall",
1185 [GNU_AK_DEPRECATED] = "deprecated",
1186 [GNU_AK_NOINLINE] = "noinline",
1187 [GNU_AK_NORETURN] = "noreturn",
1188 [GNU_AK_NAKED] = "naked",
1189 [GNU_AK_PURE] = "pure",
1190 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1191 [GNU_AK_MALLOC] = "malloc",
1192 [GNU_AK_WEAK] = "weak",
1193 [GNU_AK_CONSTRUCTOR] = "constructor",
1194 [GNU_AK_DESTRUCTOR] = "destructor",
1195 [GNU_AK_NOTHROW] = "nothrow",
1196 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1197 [GNU_AK_COMMON] = "common",
1198 [GNU_AK_NOCOMMON] = "nocommon",
1199 [GNU_AK_PACKED] = "packed",
1200 [GNU_AK_SHARED] = "shared",
1201 [GNU_AK_NOTSHARED] = "notshared",
1202 [GNU_AK_USED] = "used",
1203 [GNU_AK_UNUSED] = "unused",
1204 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1205 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1206 [GNU_AK_LONGCALL] = "longcall",
1207 [GNU_AK_SHORTCALL] = "shortcall",
1208 [GNU_AK_LONG_CALL] = "long_call",
1209 [GNU_AK_SHORT_CALL] = "short_call",
1210 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1211 [GNU_AK_INTERRUPT] = "interrupt",
1212 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1213 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1214 [GNU_AK_NESTING] = "nesting",
1215 [GNU_AK_NEAR] = "near",
1216 [GNU_AK_FAR] = "far",
1217 [GNU_AK_SIGNAL] = "signal",
1218 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1219 [GNU_AK_TINY_DATA] = "tiny_data",
1220 [GNU_AK_SAVEALL] = "saveall",
1221 [GNU_AK_FLATTEN] = "flatten",
1222 [GNU_AK_SSEREGPARM] = "sseregparm",
1223 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1224 [GNU_AK_RETURN_TWICE] = "return_twice",
1225 [GNU_AK_MAY_ALIAS] = "may_alias",
1226 [GNU_AK_MS_STRUCT] = "ms_struct",
1227 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1228 [GNU_AK_DLLIMPORT] = "dllimport",
1229 [GNU_AK_DLLEXPORT] = "dllexport",
1230 [GNU_AK_ALIGNED] = "aligned",
1231 [GNU_AK_ALIAS] = "alias",
1232 [GNU_AK_SECTION] = "section",
1233 [GNU_AK_FORMAT] = "format",
1234 [GNU_AK_FORMAT_ARG] = "format_arg",
1235 [GNU_AK_WEAKREF] = "weakref",
1236 [GNU_AK_NONNULL] = "nonnull",
1237 [GNU_AK_TLS_MODEL] = "tls_model",
1238 [GNU_AK_VISIBILITY] = "visibility",
1239 [GNU_AK_REGPARM] = "regparm",
1240 [GNU_AK_MODE] = "mode",
1241 [GNU_AK_MODEL] = "model",
1242 [GNU_AK_TRAP_EXIT] = "trap_exit",
1243 [GNU_AK_SP_SWITCH] = "sp_switch",
1244 [GNU_AK_SENTINEL] = "sentinel"
1248 * compare two string, ignoring double underscores on the second.
1250 static int strcmp_underscore(const char *s1, const char *s2)
1252 if (s2[0] == '_' && s2[1] == '_') {
1253 size_t len2 = strlen(s2);
1254 size_t len1 = strlen(s1);
1255 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1256 return strncmp(s1, s2+2, len2-4);
1260 return strcmp(s1, s2);
1264 * Allocate a new gnu temporal attribute.
1266 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1268 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1269 attribute->kind = kind;
1270 attribute->next = NULL;
1271 attribute->invalid = false;
1272 attribute->have_arguments = false;
1278 * parse one constant expression argument.
1280 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1282 expression_t *expression;
1283 add_anchor_token(')');
1284 expression = parse_constant_expression();
1285 rem_anchor_token(')');
1287 attribute->u.argument = fold_constant(expression);
1290 attribute->invalid = true;
1294 * parse a list of constant expressions arguments.
1296 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1298 argument_list_t **list = &attribute->u.arguments;
1299 argument_list_t *entry;
1300 expression_t *expression;
1301 add_anchor_token(')');
1302 add_anchor_token(',');
1304 expression = parse_constant_expression();
1305 entry = obstack_alloc(&temp_obst, sizeof(entry));
1306 entry->argument = fold_constant(expression);
1309 list = &entry->next;
1310 if (token.type != ',')
1314 rem_anchor_token(',');
1315 rem_anchor_token(')');
1319 attribute->invalid = true;
1323 * parse one string literal argument.
1325 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1328 add_anchor_token('(');
1329 if (token.type != T_STRING_LITERAL) {
1330 parse_error_expected("while parsing attribute directive",
1331 T_STRING_LITERAL, NULL);
1334 *string = parse_string_literals();
1335 rem_anchor_token('(');
1339 attribute->invalid = true;
1343 * parse one tls model.
1345 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1347 static const char *const tls_models[] = {
1353 string_t string = { NULL, 0 };
1354 parse_gnu_attribute_string_arg(attribute, &string);
1355 if (string.begin != NULL) {
1356 for (size_t i = 0; i < 4; ++i) {
1357 if (strcmp(tls_models[i], string.begin) == 0) {
1358 attribute->u.value = i;
1362 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1364 attribute->invalid = true;
1368 * parse one tls model.
1370 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1372 static const char *const visibilities[] = {
1378 string_t string = { NULL, 0 };
1379 parse_gnu_attribute_string_arg(attribute, &string);
1380 if (string.begin != NULL) {
1381 for (size_t i = 0; i < 4; ++i) {
1382 if (strcmp(visibilities[i], string.begin) == 0) {
1383 attribute->u.value = i;
1387 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1389 attribute->invalid = true;
1393 * parse one (code) model.
1395 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1397 static const char *const visibilities[] = {
1402 string_t string = { NULL, 0 };
1403 parse_gnu_attribute_string_arg(attribute, &string);
1404 if (string.begin != NULL) {
1405 for (int i = 0; i < 3; ++i) {
1406 if (strcmp(visibilities[i], string.begin) == 0) {
1407 attribute->u.value = i;
1411 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1413 attribute->invalid = true;
1416 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1418 /* TODO: find out what is allowed here... */
1420 /* at least: byte, word, pointer, list of machine modes
1421 * __XXX___ is interpreted as XXX */
1422 add_anchor_token(')');
1424 if (token.type != T_IDENTIFIER) {
1425 expect(T_IDENTIFIER);
1428 /* This isn't really correct, the backend should provide a list of machine
1429 * specific modes (according to gcc philosophy that is...) */
1430 const char *symbol_str = token.v.symbol->string;
1431 if (strcmp_underscore("QI", symbol_str) == 0 ||
1432 strcmp_underscore("byte", symbol_str) == 0) {
1433 attribute->u.akind = ATOMIC_TYPE_CHAR;
1434 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1435 attribute->u.akind = ATOMIC_TYPE_SHORT;
1436 } else if (strcmp_underscore("SI", symbol_str) == 0
1437 || strcmp_underscore("word", symbol_str) == 0
1438 || strcmp_underscore("pointer", symbol_str) == 0) {
1439 attribute->u.akind = ATOMIC_TYPE_INT;
1440 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1441 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1444 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1445 attribute->invalid = true;
1449 rem_anchor_token(')');
1453 attribute->invalid = true;
1457 * parse one interrupt argument.
1459 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1461 static const char *const interrupts[] = {
1468 string_t string = { NULL, 0 };
1469 parse_gnu_attribute_string_arg(attribute, &string);
1470 if (string.begin != NULL) {
1471 for (size_t i = 0; i < 5; ++i) {
1472 if (strcmp(interrupts[i], string.begin) == 0) {
1473 attribute->u.value = i;
1477 errorf(HERE, "'%s' is not an interrupt", string.begin);
1479 attribute->invalid = true;
1483 * parse ( identifier, const expression, const expression )
1485 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1487 static const char *const format_names[] = {
1495 if (token.type != T_IDENTIFIER) {
1496 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1499 const char *name = token.v.symbol->string;
1500 for (i = 0; i < 4; ++i) {
1501 if (strcmp_underscore(format_names[i], name) == 0)
1505 if (warning.attribute)
1506 warningf(HERE, "'%s' is an unrecognized format function type", name);
1511 add_anchor_token(')');
1512 add_anchor_token(',');
1513 parse_constant_expression();
1514 rem_anchor_token(',');
1515 rem_anchor_token(')');
1518 add_anchor_token(')');
1519 parse_constant_expression();
1520 rem_anchor_token(')');
1524 attribute->u.value = true;
1527 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1529 if (!attribute->have_arguments)
1532 /* should have no arguments */
1533 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1534 eat_until_matching_token('(');
1535 /* we have already consumed '(', so we stop before ')', eat it */
1537 attribute->invalid = true;
1541 * Parse one GNU attribute.
1543 * Note that attribute names can be specified WITH or WITHOUT
1544 * double underscores, ie const or __const__.
1546 * The following attributes are parsed without arguments
1571 * no_instrument_function
1572 * warn_unused_result
1589 * externally_visible
1597 * The following attributes are parsed with arguments
1598 * aligned( const expression )
1599 * alias( string literal )
1600 * section( string literal )
1601 * format( identifier, const expression, const expression )
1602 * format_arg( const expression )
1603 * tls_model( string literal )
1604 * visibility( string literal )
1605 * regparm( const expression )
1606 * model( string leteral )
1607 * trap_exit( const expression )
1608 * sp_switch( string literal )
1610 * The following attributes might have arguments
1611 * weak_ref( string literal )
1612 * non_null( const expression // ',' )
1613 * interrupt( string literal )
1614 * sentinel( constant expression )
1616 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1618 gnu_attribute_t *head = *attributes;
1619 gnu_attribute_t *last = *attributes;
1620 decl_modifiers_t modifiers = 0;
1621 gnu_attribute_t *attribute;
1623 eat(T___attribute__);
1627 if (token.type != ')') {
1628 /* find the end of the list */
1630 while (last->next != NULL)
1634 /* non-empty attribute list */
1637 if (token.type == T_const) {
1639 } else if (token.type == T_volatile) {
1641 } else if (token.type == T_cdecl) {
1642 /* __attribute__((cdecl)), WITH ms mode */
1644 } else if (token.type == T_IDENTIFIER) {
1645 const symbol_t *sym = token.v.symbol;
1648 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1655 for (i = 0; i < GNU_AK_LAST; ++i) {
1656 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1659 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1662 if (kind == GNU_AK_LAST) {
1663 if (warning.attribute)
1664 warningf(HERE, "'%s' attribute directive ignored", name);
1666 /* skip possible arguments */
1667 if (token.type == '(') {
1668 eat_until_matching_token(')');
1671 /* check for arguments */
1672 attribute = allocate_gnu_attribute(kind);
1673 if (token.type == '(') {
1675 if (token.type == ')') {
1676 /* empty args are allowed */
1679 attribute->have_arguments = true;
1683 case GNU_AK_VOLATILE:
1688 case GNU_AK_NOCOMMON:
1690 case GNU_AK_NOTSHARED:
1691 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1692 case GNU_AK_WARN_UNUSED_RESULT:
1693 case GNU_AK_LONGCALL:
1694 case GNU_AK_SHORTCALL:
1695 case GNU_AK_LONG_CALL:
1696 case GNU_AK_SHORT_CALL:
1697 case GNU_AK_FUNCTION_VECTOR:
1698 case GNU_AK_INTERRUPT_HANDLER:
1699 case GNU_AK_NMI_HANDLER:
1700 case GNU_AK_NESTING:
1704 case GNU_AK_EIGTHBIT_DATA:
1705 case GNU_AK_TINY_DATA:
1706 case GNU_AK_SAVEALL:
1707 case GNU_AK_FLATTEN:
1708 case GNU_AK_SSEREGPARM:
1709 case GNU_AK_EXTERNALLY_VISIBLE:
1710 case GNU_AK_RETURN_TWICE:
1711 case GNU_AK_MAY_ALIAS:
1712 case GNU_AK_MS_STRUCT:
1713 case GNU_AK_GCC_STRUCT:
1716 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1717 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1718 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1719 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1720 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1721 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1722 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1723 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1724 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1725 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1726 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1727 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1728 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1729 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1730 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1731 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1732 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1733 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1735 case GNU_AK_ALIGNED:
1736 /* __align__ may be used without an argument */
1737 if (attribute->have_arguments) {
1738 parse_gnu_attribute_const_arg(attribute);
1742 case GNU_AK_FORMAT_ARG:
1743 case GNU_AK_REGPARM:
1744 case GNU_AK_TRAP_EXIT:
1745 if (!attribute->have_arguments) {
1746 /* should have arguments */
1747 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1748 attribute->invalid = true;
1750 parse_gnu_attribute_const_arg(attribute);
1753 case GNU_AK_SECTION:
1754 case GNU_AK_SP_SWITCH:
1755 if (!attribute->have_arguments) {
1756 /* should have arguments */
1757 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1758 attribute->invalid = true;
1760 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1763 if (!attribute->have_arguments) {
1764 /* should have arguments */
1765 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1766 attribute->invalid = true;
1768 parse_gnu_attribute_format_args(attribute);
1770 case GNU_AK_WEAKREF:
1771 /* may have one string argument */
1772 if (attribute->have_arguments)
1773 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1775 case GNU_AK_NONNULL:
1776 if (attribute->have_arguments)
1777 parse_gnu_attribute_const_arg_list(attribute);
1779 case GNU_AK_TLS_MODEL:
1780 if (!attribute->have_arguments) {
1781 /* should have arguments */
1782 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1784 parse_gnu_attribute_tls_model_arg(attribute);
1786 case GNU_AK_VISIBILITY:
1787 if (!attribute->have_arguments) {
1788 /* should have arguments */
1789 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1791 parse_gnu_attribute_visibility_arg(attribute);
1794 if (!attribute->have_arguments) {
1795 /* should have arguments */
1796 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1798 parse_gnu_attribute_model_arg(attribute);
1802 if (!attribute->have_arguments) {
1803 /* should have arguments */
1804 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1806 parse_gnu_attribute_mode_arg(attribute);
1809 case GNU_AK_INTERRUPT:
1810 /* may have one string argument */
1811 if (attribute->have_arguments)
1812 parse_gnu_attribute_interrupt_arg(attribute);
1814 case GNU_AK_SENTINEL:
1815 /* may have one string argument */
1816 if (attribute->have_arguments)
1817 parse_gnu_attribute_const_arg(attribute);
1820 /* already handled */
1824 check_no_argument(attribute, name);
1827 if (attribute != NULL) {
1829 last->next = attribute;
1832 head = last = attribute;
1836 if (token.type != ',')
1850 * Parse GNU attributes.
1852 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1854 decl_modifiers_t modifiers = 0;
1857 switch (token.type) {
1858 case T___attribute__:
1859 modifiers |= parse_gnu_attribute(attributes);
1865 if (token.type != T_STRING_LITERAL) {
1866 parse_error_expected("while parsing assembler attribute",
1867 T_STRING_LITERAL, NULL);
1868 eat_until_matching_token('(');
1871 parse_string_literals();
1876 case T_cdecl: modifiers |= DM_CDECL; break;
1877 case T__fastcall: modifiers |= DM_FASTCALL; break;
1878 case T__stdcall: modifiers |= DM_STDCALL; break;
1881 /* TODO record modifier */
1883 warningf(HERE, "Ignoring declaration modifier %K", &token);
1887 default: return modifiers;
1894 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1896 static variable_t *determine_lhs_var(expression_t *const expr,
1897 variable_t *lhs_var)
1899 switch (expr->kind) {
1900 case EXPR_REFERENCE: {
1901 entity_t *const entity = expr->reference.entity;
1902 /* we should only find variables as lavlues... */
1903 if (entity->base.kind != ENTITY_VARIABLE)
1906 return &entity->variable;
1909 case EXPR_ARRAY_ACCESS: {
1910 expression_t *const ref = expr->array_access.array_ref;
1911 variable_t * var = NULL;
1912 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1913 var = determine_lhs_var(ref, lhs_var);
1916 mark_vars_read(expr->select.compound, lhs_var);
1918 mark_vars_read(expr->array_access.index, lhs_var);
1923 if (is_type_compound(skip_typeref(expr->base.type))) {
1924 return determine_lhs_var(expr->select.compound, lhs_var);
1926 mark_vars_read(expr->select.compound, lhs_var);
1931 case EXPR_UNARY_DEREFERENCE: {
1932 expression_t *const val = expr->unary.value;
1933 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1935 return determine_lhs_var(val->unary.value, lhs_var);
1937 mark_vars_read(val, NULL);
1943 mark_vars_read(expr, NULL);
1948 #define VAR_ANY ((variable_t*)-1)
1951 * Mark declarations, which are read. This is used to deted variables, which
1955 * x is not marked as "read", because it is only read to calculate its own new
1959 * x and y are not detected as "not read", because multiple variables are
1962 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1964 switch (expr->kind) {
1965 case EXPR_REFERENCE: {
1966 entity_t *const entity = expr->reference.entity;
1967 if (entity->kind != ENTITY_VARIABLE)
1970 variable_t *variable = &entity->variable;
1971 if (lhs_var != variable && lhs_var != VAR_ANY) {
1972 variable->read = true;
1978 // TODO respect pure/const
1979 mark_vars_read(expr->call.function, NULL);
1980 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1981 mark_vars_read(arg->expression, NULL);
1985 case EXPR_CONDITIONAL:
1986 // TODO lhs_decl should depend on whether true/false have an effect
1987 mark_vars_read(expr->conditional.condition, NULL);
1988 if (expr->conditional.true_expression != NULL)
1989 mark_vars_read(expr->conditional.true_expression, lhs_var);
1990 mark_vars_read(expr->conditional.false_expression, lhs_var);
1994 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
1996 mark_vars_read(expr->select.compound, lhs_var);
1999 case EXPR_ARRAY_ACCESS: {
2000 expression_t *const ref = expr->array_access.array_ref;
2001 mark_vars_read(ref, lhs_var);
2002 lhs_var = determine_lhs_var(ref, lhs_var);
2003 mark_vars_read(expr->array_access.index, lhs_var);
2008 mark_vars_read(expr->va_arge.ap, lhs_var);
2011 case EXPR_UNARY_CAST:
2012 /* Special case: Use void cast to mark a variable as "read" */
2013 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2018 case EXPR_UNARY_THROW:
2019 if (expr->unary.value == NULL)
2022 case EXPR_UNARY_DEREFERENCE:
2023 case EXPR_UNARY_DELETE:
2024 case EXPR_UNARY_DELETE_ARRAY:
2025 if (lhs_var == VAR_ANY)
2029 case EXPR_UNARY_NEGATE:
2030 case EXPR_UNARY_PLUS:
2031 case EXPR_UNARY_BITWISE_NEGATE:
2032 case EXPR_UNARY_NOT:
2033 case EXPR_UNARY_TAKE_ADDRESS:
2034 case EXPR_UNARY_POSTFIX_INCREMENT:
2035 case EXPR_UNARY_POSTFIX_DECREMENT:
2036 case EXPR_UNARY_PREFIX_INCREMENT:
2037 case EXPR_UNARY_PREFIX_DECREMENT:
2038 case EXPR_UNARY_CAST_IMPLICIT:
2039 case EXPR_UNARY_ASSUME:
2041 mark_vars_read(expr->unary.value, lhs_var);
2044 case EXPR_BINARY_ADD:
2045 case EXPR_BINARY_SUB:
2046 case EXPR_BINARY_MUL:
2047 case EXPR_BINARY_DIV:
2048 case EXPR_BINARY_MOD:
2049 case EXPR_BINARY_EQUAL:
2050 case EXPR_BINARY_NOTEQUAL:
2051 case EXPR_BINARY_LESS:
2052 case EXPR_BINARY_LESSEQUAL:
2053 case EXPR_BINARY_GREATER:
2054 case EXPR_BINARY_GREATEREQUAL:
2055 case EXPR_BINARY_BITWISE_AND:
2056 case EXPR_BINARY_BITWISE_OR:
2057 case EXPR_BINARY_BITWISE_XOR:
2058 case EXPR_BINARY_LOGICAL_AND:
2059 case EXPR_BINARY_LOGICAL_OR:
2060 case EXPR_BINARY_SHIFTLEFT:
2061 case EXPR_BINARY_SHIFTRIGHT:
2062 case EXPR_BINARY_COMMA:
2063 case EXPR_BINARY_ISGREATER:
2064 case EXPR_BINARY_ISGREATEREQUAL:
2065 case EXPR_BINARY_ISLESS:
2066 case EXPR_BINARY_ISLESSEQUAL:
2067 case EXPR_BINARY_ISLESSGREATER:
2068 case EXPR_BINARY_ISUNORDERED:
2069 mark_vars_read(expr->binary.left, lhs_var);
2070 mark_vars_read(expr->binary.right, lhs_var);
2073 case EXPR_BINARY_ASSIGN:
2074 case EXPR_BINARY_MUL_ASSIGN:
2075 case EXPR_BINARY_DIV_ASSIGN:
2076 case EXPR_BINARY_MOD_ASSIGN:
2077 case EXPR_BINARY_ADD_ASSIGN:
2078 case EXPR_BINARY_SUB_ASSIGN:
2079 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2080 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2081 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2082 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2083 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2084 if (lhs_var == VAR_ANY)
2086 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2087 mark_vars_read(expr->binary.right, lhs_var);
2092 determine_lhs_var(expr->va_starte.ap, lhs_var);
2098 case EXPR_CHARACTER_CONSTANT:
2099 case EXPR_WIDE_CHARACTER_CONSTANT:
2100 case EXPR_STRING_LITERAL:
2101 case EXPR_WIDE_STRING_LITERAL:
2102 case EXPR_COMPOUND_LITERAL: // TODO init?
2104 case EXPR_CLASSIFY_TYPE:
2107 case EXPR_BUILTIN_SYMBOL:
2108 case EXPR_BUILTIN_CONSTANT_P:
2109 case EXPR_BUILTIN_PREFETCH:
2111 case EXPR_STATEMENT: // TODO
2112 case EXPR_LABEL_ADDRESS:
2113 case EXPR_BINARY_BUILTIN_EXPECT:
2114 case EXPR_REFERENCE_ENUM_VALUE:
2118 panic("unhandled expression");
2121 static designator_t *parse_designation(void)
2123 designator_t *result = NULL;
2124 designator_t *last = NULL;
2127 designator_t *designator;
2128 switch (token.type) {
2130 designator = allocate_ast_zero(sizeof(designator[0]));
2131 designator->source_position = token.source_position;
2133 add_anchor_token(']');
2134 designator->array_index = parse_constant_expression();
2135 rem_anchor_token(']');
2139 designator = allocate_ast_zero(sizeof(designator[0]));
2140 designator->source_position = token.source_position;
2142 if (token.type != T_IDENTIFIER) {
2143 parse_error_expected("while parsing designator",
2144 T_IDENTIFIER, NULL);
2147 designator->symbol = token.v.symbol;
2155 assert(designator != NULL);
2157 last->next = designator;
2159 result = designator;
2167 static initializer_t *initializer_from_string(array_type_t *type,
2168 const string_t *const string)
2170 /* TODO: check len vs. size of array type */
2173 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2174 initializer->string.string = *string;
2179 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2180 wide_string_t *const string)
2182 /* TODO: check len vs. size of array type */
2185 initializer_t *const initializer =
2186 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2187 initializer->wide_string.string = *string;
2193 * Build an initializer from a given expression.
2195 static initializer_t *initializer_from_expression(type_t *orig_type,
2196 expression_t *expression)
2198 /* TODO check that expression is a constant expression */
2200 /* § 6.7.8.14/15 char array may be initialized by string literals */
2201 type_t *type = skip_typeref(orig_type);
2202 type_t *expr_type_orig = expression->base.type;
2203 type_t *expr_type = skip_typeref(expr_type_orig);
2204 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2205 array_type_t *const array_type = &type->array;
2206 type_t *const element_type = skip_typeref(array_type->element_type);
2208 if (element_type->kind == TYPE_ATOMIC) {
2209 atomic_type_kind_t akind = element_type->atomic.akind;
2210 switch (expression->kind) {
2211 case EXPR_STRING_LITERAL:
2212 if (akind == ATOMIC_TYPE_CHAR
2213 || akind == ATOMIC_TYPE_SCHAR
2214 || akind == ATOMIC_TYPE_UCHAR) {
2215 return initializer_from_string(array_type,
2216 &expression->string.value);
2219 case EXPR_WIDE_STRING_LITERAL: {
2220 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2221 if (get_unqualified_type(element_type) == bare_wchar_type) {
2222 return initializer_from_wide_string(array_type,
2223 &expression->wide_string.value);
2233 assign_error_t error = semantic_assign(type, expression);
2234 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2236 report_assign_error(error, type, expression, "initializer",
2237 &expression->base.source_position);
2239 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2241 if (type->kind == TYPE_BITFIELD) {
2242 type = type->bitfield.base_type;
2245 result->value.value = create_implicit_cast(expression, type);
2251 * Checks if a given expression can be used as an constant initializer.
2253 static bool is_initializer_constant(const expression_t *expression)
2255 return is_constant_expression(expression)
2256 || is_address_constant(expression);
2260 * Parses an scalar initializer.
2262 * § 6.7.8.11; eat {} without warning
2264 static initializer_t *parse_scalar_initializer(type_t *type,
2265 bool must_be_constant)
2267 /* there might be extra {} hierarchies */
2269 if (token.type == '{') {
2271 warningf(HERE, "extra curly braces around scalar initializer");
2275 } while (token.type == '{');
2278 expression_t *expression = parse_assignment_expression();
2279 mark_vars_read(expression, NULL);
2280 if (must_be_constant && !is_initializer_constant(expression)) {
2281 errorf(&expression->base.source_position,
2282 "Initialisation expression '%E' is not constant\n",
2286 initializer_t *initializer = initializer_from_expression(type, expression);
2288 if (initializer == NULL) {
2289 errorf(&expression->base.source_position,
2290 "expression '%E' (type '%T') doesn't match expected type '%T'",
2291 expression, expression->base.type, type);
2296 bool additional_warning_displayed = false;
2297 while (braces > 0) {
2298 if (token.type == ',') {
2301 if (token.type != '}') {
2302 if (!additional_warning_displayed && warning.other) {
2303 warningf(HERE, "additional elements in scalar initializer");
2304 additional_warning_displayed = true;
2315 * An entry in the type path.
2317 typedef struct type_path_entry_t type_path_entry_t;
2318 struct type_path_entry_t {
2319 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2321 size_t index; /**< For array types: the current index. */
2322 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2327 * A type path expression a position inside compound or array types.
2329 typedef struct type_path_t type_path_t;
2330 struct type_path_t {
2331 type_path_entry_t *path; /**< An flexible array containing the current path. */
2332 type_t *top_type; /**< type of the element the path points */
2333 size_t max_index; /**< largest index in outermost array */
2337 * Prints a type path for debugging.
2339 static __attribute__((unused)) void debug_print_type_path(
2340 const type_path_t *path)
2342 size_t len = ARR_LEN(path->path);
2344 for (size_t i = 0; i < len; ++i) {
2345 const type_path_entry_t *entry = & path->path[i];
2347 type_t *type = skip_typeref(entry->type);
2348 if (is_type_compound(type)) {
2349 /* in gcc mode structs can have no members */
2350 if (entry->v.compound_entry == NULL) {
2354 fprintf(stderr, ".%s",
2355 entry->v.compound_entry->base.symbol->string);
2356 } else if (is_type_array(type)) {
2357 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2359 fprintf(stderr, "-INVALID-");
2362 if (path->top_type != NULL) {
2363 fprintf(stderr, " (");
2364 print_type(path->top_type);
2365 fprintf(stderr, ")");
2370 * Return the top type path entry, ie. in a path
2371 * (type).a.b returns the b.
2373 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2375 size_t len = ARR_LEN(path->path);
2377 return &path->path[len-1];
2381 * Enlarge the type path by an (empty) element.
2383 static type_path_entry_t *append_to_type_path(type_path_t *path)
2385 size_t len = ARR_LEN(path->path);
2386 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2388 type_path_entry_t *result = & path->path[len];
2389 memset(result, 0, sizeof(result[0]));
2394 * Descending into a sub-type. Enter the scope of the current top_type.
2396 static void descend_into_subtype(type_path_t *path)
2398 type_t *orig_top_type = path->top_type;
2399 type_t *top_type = skip_typeref(orig_top_type);
2401 type_path_entry_t *top = append_to_type_path(path);
2402 top->type = top_type;
2404 if (is_type_compound(top_type)) {
2405 compound_t *compound = top_type->compound.compound;
2406 entity_t *entry = compound->members.entities;
2408 if (entry != NULL) {
2409 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2410 top->v.compound_entry = &entry->declaration;
2411 path->top_type = entry->declaration.type;
2413 path->top_type = NULL;
2415 } else if (is_type_array(top_type)) {
2417 path->top_type = top_type->array.element_type;
2419 assert(!is_type_valid(top_type));
2424 * Pop an entry from the given type path, ie. returning from
2425 * (type).a.b to (type).a
2427 static void ascend_from_subtype(type_path_t *path)
2429 type_path_entry_t *top = get_type_path_top(path);
2431 path->top_type = top->type;
2433 size_t len = ARR_LEN(path->path);
2434 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2438 * Pop entries from the given type path until the given
2439 * path level is reached.
2441 static void ascend_to(type_path_t *path, size_t top_path_level)
2443 size_t len = ARR_LEN(path->path);
2445 while (len > top_path_level) {
2446 ascend_from_subtype(path);
2447 len = ARR_LEN(path->path);
2451 static bool walk_designator(type_path_t *path, const designator_t *designator,
2452 bool used_in_offsetof)
2454 for (; designator != NULL; designator = designator->next) {
2455 type_path_entry_t *top = get_type_path_top(path);
2456 type_t *orig_type = top->type;
2458 type_t *type = skip_typeref(orig_type);
2460 if (designator->symbol != NULL) {
2461 symbol_t *symbol = designator->symbol;
2462 if (!is_type_compound(type)) {
2463 if (is_type_valid(type)) {
2464 errorf(&designator->source_position,
2465 "'.%Y' designator used for non-compound type '%T'",
2469 top->type = type_error_type;
2470 top->v.compound_entry = NULL;
2471 orig_type = type_error_type;
2473 compound_t *compound = type->compound.compound;
2474 entity_t *iter = compound->members.entities;
2475 for (; iter != NULL; iter = iter->base.next) {
2476 if (iter->base.symbol == symbol) {
2481 errorf(&designator->source_position,
2482 "'%T' has no member named '%Y'", orig_type, symbol);
2485 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2486 if (used_in_offsetof) {
2487 type_t *real_type = skip_typeref(iter->declaration.type);
2488 if (real_type->kind == TYPE_BITFIELD) {
2489 errorf(&designator->source_position,
2490 "offsetof designator '%Y' may not specify bitfield",
2496 top->type = orig_type;
2497 top->v.compound_entry = &iter->declaration;
2498 orig_type = iter->declaration.type;
2501 expression_t *array_index = designator->array_index;
2502 assert(designator->array_index != NULL);
2504 if (!is_type_array(type)) {
2505 if (is_type_valid(type)) {
2506 errorf(&designator->source_position,
2507 "[%E] designator used for non-array type '%T'",
2508 array_index, orig_type);
2513 long index = fold_constant(array_index);
2514 if (!used_in_offsetof) {
2516 errorf(&designator->source_position,
2517 "array index [%E] must be positive", array_index);
2518 } else if (type->array.size_constant) {
2519 long array_size = type->array.size;
2520 if (index >= array_size) {
2521 errorf(&designator->source_position,
2522 "designator [%E] (%d) exceeds array size %d",
2523 array_index, index, array_size);
2528 top->type = orig_type;
2529 top->v.index = (size_t) index;
2530 orig_type = type->array.element_type;
2532 path->top_type = orig_type;
2534 if (designator->next != NULL) {
2535 descend_into_subtype(path);
2544 static void advance_current_object(type_path_t *path, size_t top_path_level)
2546 type_path_entry_t *top = get_type_path_top(path);
2548 type_t *type = skip_typeref(top->type);
2549 if (is_type_union(type)) {
2550 /* in unions only the first element is initialized */
2551 top->v.compound_entry = NULL;
2552 } else if (is_type_struct(type)) {
2553 declaration_t *entry = top->v.compound_entry;
2555 entity_t *next_entity = entry->base.next;
2556 if (next_entity != NULL) {
2557 assert(is_declaration(next_entity));
2558 entry = &next_entity->declaration;
2563 top->v.compound_entry = entry;
2564 if (entry != NULL) {
2565 path->top_type = entry->type;
2568 } else if (is_type_array(type)) {
2569 assert(is_type_array(type));
2573 if (!type->array.size_constant || top->v.index < type->array.size) {
2577 assert(!is_type_valid(type));
2581 /* we're past the last member of the current sub-aggregate, try if we
2582 * can ascend in the type hierarchy and continue with another subobject */
2583 size_t len = ARR_LEN(path->path);
2585 if (len > top_path_level) {
2586 ascend_from_subtype(path);
2587 advance_current_object(path, top_path_level);
2589 path->top_type = NULL;
2594 * skip until token is found.
2596 static void skip_until(int type)
2598 while (token.type != type) {
2599 if (token.type == T_EOF)
2606 * skip any {...} blocks until a closing bracket is reached.
2608 static void skip_initializers(void)
2610 if (token.type == '{')
2613 while (token.type != '}') {
2614 if (token.type == T_EOF)
2616 if (token.type == '{') {
2624 static initializer_t *create_empty_initializer(void)
2626 static initializer_t empty_initializer
2627 = { .list = { { INITIALIZER_LIST }, 0 } };
2628 return &empty_initializer;
2632 * Parse a part of an initialiser for a struct or union,
2634 static initializer_t *parse_sub_initializer(type_path_t *path,
2635 type_t *outer_type, size_t top_path_level,
2636 parse_initializer_env_t *env)
2638 if (token.type == '}') {
2639 /* empty initializer */
2640 return create_empty_initializer();
2643 type_t *orig_type = path->top_type;
2644 type_t *type = NULL;
2646 if (orig_type == NULL) {
2647 /* We are initializing an empty compound. */
2649 type = skip_typeref(orig_type);
2652 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2655 designator_t *designator = NULL;
2656 if (token.type == '.' || token.type == '[') {
2657 designator = parse_designation();
2658 goto finish_designator;
2659 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2660 /* GNU-style designator ("identifier: value") */
2661 designator = allocate_ast_zero(sizeof(designator[0]));
2662 designator->source_position = token.source_position;
2663 designator->symbol = token.v.symbol;
2668 /* reset path to toplevel, evaluate designator from there */
2669 ascend_to(path, top_path_level);
2670 if (!walk_designator(path, designator, false)) {
2671 /* can't continue after designation error */
2675 initializer_t *designator_initializer
2676 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2677 designator_initializer->designator.designator = designator;
2678 ARR_APP1(initializer_t*, initializers, designator_initializer);
2680 orig_type = path->top_type;
2681 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2686 if (token.type == '{') {
2687 if (type != NULL && is_type_scalar(type)) {
2688 sub = parse_scalar_initializer(type, env->must_be_constant);
2692 if (env->entity != NULL) {
2694 "extra brace group at end of initializer for '%Y'",
2695 env->entity->base.symbol);
2697 errorf(HERE, "extra brace group at end of initializer");
2700 descend_into_subtype(path);
2702 add_anchor_token('}');
2703 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2705 rem_anchor_token('}');
2708 ascend_from_subtype(path);
2712 goto error_parse_next;
2716 /* must be an expression */
2717 expression_t *expression = parse_assignment_expression();
2719 if (env->must_be_constant && !is_initializer_constant(expression)) {
2720 errorf(&expression->base.source_position,
2721 "Initialisation expression '%E' is not constant\n",
2726 /* we are already outside, ... */
2727 type_t *const outer_type_skip = skip_typeref(outer_type);
2728 if (is_type_compound(outer_type_skip) &&
2729 !outer_type_skip->compound.compound->complete) {
2730 goto error_parse_next;
2735 /* handle { "string" } special case */
2736 if ((expression->kind == EXPR_STRING_LITERAL
2737 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2738 && outer_type != NULL) {
2739 sub = initializer_from_expression(outer_type, expression);
2741 if (token.type == ',') {
2744 if (token.type != '}' && warning.other) {
2745 warningf(HERE, "excessive elements in initializer for type '%T'",
2748 /* TODO: eat , ... */
2753 /* descend into subtypes until expression matches type */
2755 orig_type = path->top_type;
2756 type = skip_typeref(orig_type);
2758 sub = initializer_from_expression(orig_type, expression);
2762 if (!is_type_valid(type)) {
2765 if (is_type_scalar(type)) {
2766 errorf(&expression->base.source_position,
2767 "expression '%E' doesn't match expected type '%T'",
2768 expression, orig_type);
2772 descend_into_subtype(path);
2776 /* update largest index of top array */
2777 const type_path_entry_t *first = &path->path[0];
2778 type_t *first_type = first->type;
2779 first_type = skip_typeref(first_type);
2780 if (is_type_array(first_type)) {
2781 size_t index = first->v.index;
2782 if (index > path->max_index)
2783 path->max_index = index;
2787 /* append to initializers list */
2788 ARR_APP1(initializer_t*, initializers, sub);
2791 if (warning.other) {
2792 if (env->entity != NULL) {
2793 warningf(HERE, "excess elements in struct initializer for '%Y'",
2794 env->entity->base.symbol);
2796 warningf(HERE, "excess elements in struct initializer");
2802 if (token.type == '}') {
2806 if (token.type == '}') {
2811 /* advance to the next declaration if we are not at the end */
2812 advance_current_object(path, top_path_level);
2813 orig_type = path->top_type;
2814 if (orig_type != NULL)
2815 type = skip_typeref(orig_type);
2821 size_t len = ARR_LEN(initializers);
2822 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2823 initializer_t *result = allocate_ast_zero(size);
2824 result->kind = INITIALIZER_LIST;
2825 result->list.len = len;
2826 memcpy(&result->list.initializers, initializers,
2827 len * sizeof(initializers[0]));
2829 DEL_ARR_F(initializers);
2830 ascend_to(path, top_path_level+1);
2835 skip_initializers();
2836 DEL_ARR_F(initializers);
2837 ascend_to(path, top_path_level+1);
2842 * Parses an initializer. Parsers either a compound literal
2843 * (env->declaration == NULL) or an initializer of a declaration.
2845 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2847 type_t *type = skip_typeref(env->type);
2848 initializer_t *result = NULL;
2851 if (is_type_scalar(type)) {
2852 result = parse_scalar_initializer(type, env->must_be_constant);
2853 } else if (token.type == '{') {
2857 memset(&path, 0, sizeof(path));
2858 path.top_type = env->type;
2859 path.path = NEW_ARR_F(type_path_entry_t, 0);
2861 descend_into_subtype(&path);
2863 add_anchor_token('}');
2864 result = parse_sub_initializer(&path, env->type, 1, env);
2865 rem_anchor_token('}');
2867 max_index = path.max_index;
2868 DEL_ARR_F(path.path);
2872 /* parse_scalar_initializer() also works in this case: we simply
2873 * have an expression without {} around it */
2874 result = parse_scalar_initializer(type, env->must_be_constant);
2877 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2878 * the array type size */
2879 if (is_type_array(type) && type->array.size_expression == NULL
2880 && result != NULL) {
2882 switch (result->kind) {
2883 case INITIALIZER_LIST:
2884 size = max_index + 1;
2887 case INITIALIZER_STRING:
2888 size = result->string.string.size;
2891 case INITIALIZER_WIDE_STRING:
2892 size = result->wide_string.string.size;
2895 case INITIALIZER_DESIGNATOR:
2896 case INITIALIZER_VALUE:
2897 /* can happen for parse errors */
2902 internal_errorf(HERE, "invalid initializer type");
2905 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2906 cnst->base.type = type_size_t;
2907 cnst->conste.v.int_value = size;
2909 type_t *new_type = duplicate_type(type);
2911 new_type->array.size_expression = cnst;
2912 new_type->array.size_constant = true;
2913 new_type->array.has_implicit_size = true;
2914 new_type->array.size = size;
2915 env->type = new_type;
2923 static void append_entity(scope_t *scope, entity_t *entity)
2925 if (scope->last_entity != NULL) {
2926 scope->last_entity->base.next = entity;
2928 scope->entities = entity;
2930 scope->last_entity = entity;
2934 static compound_t *parse_compound_type_specifier(bool is_struct)
2936 gnu_attribute_t *attributes = NULL;
2937 decl_modifiers_t modifiers = 0;
2944 symbol_t *symbol = NULL;
2945 compound_t *compound = NULL;
2947 if (token.type == T___attribute__) {
2948 modifiers |= parse_attributes(&attributes);
2951 if (token.type == T_IDENTIFIER) {
2952 symbol = token.v.symbol;
2955 namespace_tag_t const namespc =
2956 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2957 entity_t *entity = get_entity(symbol, namespc);
2958 if (entity != NULL) {
2959 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2960 compound = &entity->compound;
2961 if (compound->base.parent_scope != current_scope &&
2962 (token.type == '{' || token.type == ';')) {
2963 /* we're in an inner scope and have a definition. Override
2964 existing definition in outer scope */
2966 } else if (compound->complete && token.type == '{') {
2967 assert(symbol != NULL);
2968 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2969 is_struct ? "struct" : "union", symbol,
2970 &compound->base.source_position);
2971 /* clear members in the hope to avoid further errors */
2972 compound->members.entities = NULL;
2975 } else if (token.type != '{') {
2977 parse_error_expected("while parsing struct type specifier",
2978 T_IDENTIFIER, '{', NULL);
2980 parse_error_expected("while parsing union type specifier",
2981 T_IDENTIFIER, '{', NULL);
2987 if (compound == NULL) {
2988 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2989 entity_t *entity = allocate_entity_zero(kind);
2990 compound = &entity->compound;
2992 compound->base.namespc =
2993 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2994 compound->base.source_position = token.source_position;
2995 compound->base.symbol = symbol;
2996 compound->base.parent_scope = current_scope;
2997 if (symbol != NULL) {
2998 environment_push(entity);
3000 append_entity(current_scope, entity);
3003 if (token.type == '{') {
3004 parse_compound_type_entries(compound);
3005 modifiers |= parse_attributes(&attributes);
3007 if (symbol == NULL) {
3008 assert(anonymous_entity == NULL);
3009 anonymous_entity = (entity_t*)compound;
3013 compound->modifiers |= modifiers;
3017 static void parse_enum_entries(type_t *const enum_type)
3021 if (token.type == '}') {
3022 errorf(HERE, "empty enum not allowed");
3027 add_anchor_token('}');
3029 if (token.type != T_IDENTIFIER) {
3030 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3032 rem_anchor_token('}');
3036 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3037 entity->enum_value.enum_type = enum_type;
3038 entity->base.symbol = token.v.symbol;
3039 entity->base.source_position = token.source_position;
3042 if (token.type == '=') {
3044 expression_t *value = parse_constant_expression();
3046 value = create_implicit_cast(value, enum_type);
3047 entity->enum_value.value = value;
3052 record_entity(entity, false);
3054 if (token.type != ',')
3057 } while (token.type != '}');
3058 rem_anchor_token('}');
3066 static type_t *parse_enum_specifier(void)
3068 gnu_attribute_t *attributes = NULL;
3073 if (token.type == T_IDENTIFIER) {
3074 symbol = token.v.symbol;
3077 entity = get_entity(symbol, NAMESPACE_ENUM);
3078 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3079 } else if (token.type != '{') {
3080 parse_error_expected("while parsing enum type specifier",
3081 T_IDENTIFIER, '{', NULL);
3088 if (entity == NULL) {
3089 entity = allocate_entity_zero(ENTITY_ENUM);
3090 entity->base.namespc = NAMESPACE_ENUM;
3091 entity->base.source_position = token.source_position;
3092 entity->base.symbol = symbol;
3093 entity->base.parent_scope = current_scope;
3096 type_t *const type = allocate_type_zero(TYPE_ENUM);
3097 type->enumt.enume = &entity->enume;
3099 if (token.type == '{') {
3100 if (entity->enume.complete) {
3101 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3102 symbol, &entity->base.source_position);
3104 if (symbol != NULL) {
3105 environment_push(entity);
3107 append_entity(current_scope, entity);
3108 entity->enume.complete = true;
3110 parse_enum_entries(type);
3111 parse_attributes(&attributes);
3113 if (symbol == NULL) {
3114 assert(anonymous_entity == NULL);
3115 anonymous_entity = entity;
3117 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3118 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3126 * if a symbol is a typedef to another type, return true
3128 static bool is_typedef_symbol(symbol_t *symbol)
3130 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3131 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3134 static type_t *parse_typeof(void)
3141 add_anchor_token(')');
3143 expression_t *expression = NULL;
3145 bool old_type_prop = in_type_prop;
3146 bool old_gcc_extension = in_gcc_extension;
3147 in_type_prop = true;
3149 while (token.type == T___extension__) {
3150 /* This can be a prefix to a typename or an expression. */
3152 in_gcc_extension = true;
3154 switch (token.type) {
3156 if (is_typedef_symbol(token.v.symbol)) {
3157 type = parse_typename();
3159 expression = parse_expression();
3160 type = expression->base.type;
3165 type = parse_typename();
3169 expression = parse_expression();
3170 type = expression->base.type;
3173 in_type_prop = old_type_prop;
3174 in_gcc_extension = old_gcc_extension;
3176 rem_anchor_token(')');
3179 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3180 typeof_type->typeoft.expression = expression;
3181 typeof_type->typeoft.typeof_type = type;
3188 typedef enum specifiers_t {
3189 SPECIFIER_SIGNED = 1 << 0,
3190 SPECIFIER_UNSIGNED = 1 << 1,
3191 SPECIFIER_LONG = 1 << 2,
3192 SPECIFIER_INT = 1 << 3,
3193 SPECIFIER_DOUBLE = 1 << 4,
3194 SPECIFIER_CHAR = 1 << 5,
3195 SPECIFIER_SHORT = 1 << 6,
3196 SPECIFIER_LONG_LONG = 1 << 7,
3197 SPECIFIER_FLOAT = 1 << 8,
3198 SPECIFIER_BOOL = 1 << 9,
3199 SPECIFIER_VOID = 1 << 10,
3200 SPECIFIER_INT8 = 1 << 11,
3201 SPECIFIER_INT16 = 1 << 12,
3202 SPECIFIER_INT32 = 1 << 13,
3203 SPECIFIER_INT64 = 1 << 14,
3204 SPECIFIER_INT128 = 1 << 15,
3205 SPECIFIER_COMPLEX = 1 << 16,
3206 SPECIFIER_IMAGINARY = 1 << 17,
3209 static type_t *create_builtin_type(symbol_t *const symbol,
3210 type_t *const real_type)
3212 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3213 type->builtin.symbol = symbol;
3214 type->builtin.real_type = real_type;
3216 type_t *result = typehash_insert(type);
3217 if (type != result) {
3224 static type_t *get_typedef_type(symbol_t *symbol)
3226 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3227 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3230 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3231 type->typedeft.typedefe = &entity->typedefe;
3237 * check for the allowed MS alignment values.
3239 static bool check_alignment_value(long long intvalue)
3241 if (intvalue < 1 || intvalue > 8192) {
3242 errorf(HERE, "illegal alignment value");
3245 unsigned v = (unsigned)intvalue;
3246 for (unsigned i = 1; i <= 8192; i += i) {
3250 errorf(HERE, "alignment must be power of two");
3254 #define DET_MOD(name, tag) do { \
3255 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3256 *modifiers |= tag; \
3259 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3261 decl_modifiers_t *modifiers = &specifiers->modifiers;
3264 if (token.type == T_restrict) {
3266 DET_MOD(restrict, DM_RESTRICT);
3268 } else if (token.type != T_IDENTIFIER)
3270 symbol_t *symbol = token.v.symbol;
3271 if (symbol == sym_align) {
3274 if (token.type != T_INTEGER)
3276 if (check_alignment_value(token.v.intvalue)) {
3277 if (specifiers->alignment != 0 && warning.other)
3278 warningf(HERE, "align used more than once");
3279 specifiers->alignment = (unsigned char)token.v.intvalue;
3283 } else if (symbol == sym_allocate) {
3286 if (token.type != T_IDENTIFIER)
3288 (void)token.v.symbol;
3290 } else if (symbol == sym_dllimport) {
3292 DET_MOD(dllimport, DM_DLLIMPORT);
3293 } else if (symbol == sym_dllexport) {
3295 DET_MOD(dllexport, DM_DLLEXPORT);
3296 } else if (symbol == sym_thread) {
3298 DET_MOD(thread, DM_THREAD);
3299 } else if (symbol == sym_naked) {
3301 DET_MOD(naked, DM_NAKED);
3302 } else if (symbol == sym_noinline) {
3304 DET_MOD(noinline, DM_NOINLINE);
3305 } else if (symbol == sym_noreturn) {
3307 DET_MOD(noreturn, DM_NORETURN);
3308 } else if (symbol == sym_nothrow) {
3310 DET_MOD(nothrow, DM_NOTHROW);
3311 } else if (symbol == sym_novtable) {
3313 DET_MOD(novtable, DM_NOVTABLE);
3314 } else if (symbol == sym_property) {
3318 bool is_get = false;
3319 if (token.type != T_IDENTIFIER)
3321 if (token.v.symbol == sym_get) {
3323 } else if (token.v.symbol == sym_put) {
3325 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3330 if (token.type != T_IDENTIFIER)
3333 if (specifiers->get_property_sym != NULL) {
3334 errorf(HERE, "get property name already specified");
3336 specifiers->get_property_sym = token.v.symbol;
3339 if (specifiers->put_property_sym != NULL) {
3340 errorf(HERE, "put property name already specified");
3342 specifiers->put_property_sym = token.v.symbol;
3346 if (token.type == ',') {
3353 } else if (symbol == sym_selectany) {
3355 DET_MOD(selectany, DM_SELECTANY);
3356 } else if (symbol == sym_uuid) {
3359 if (token.type != T_STRING_LITERAL)
3363 } else if (symbol == sym_deprecated) {
3365 if (specifiers->deprecated != 0 && warning.other)
3366 warningf(HERE, "deprecated used more than once");
3367 specifiers->deprecated = true;
3368 if (token.type == '(') {
3370 if (token.type == T_STRING_LITERAL) {
3371 specifiers->deprecated_string = token.v.string.begin;
3374 errorf(HERE, "string literal expected");
3378 } else if (symbol == sym_noalias) {
3380 DET_MOD(noalias, DM_NOALIAS);
3383 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3385 if (token.type == '(')
3389 if (token.type == ',')
3396 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3398 entity_t *entity = allocate_entity_zero(kind);
3399 entity->base.source_position = *HERE;
3400 entity->base.symbol = symbol;
3401 if (is_declaration(entity)) {
3402 entity->declaration.type = type_error_type;
3403 entity->declaration.implicit = true;
3404 } else if (kind == ENTITY_TYPEDEF) {
3405 entity->typedefe.type = type_error_type;
3407 record_entity(entity, false);
3411 static void parse_microsoft_based(based_spec_t *based_spec)
3413 if (token.type != T_IDENTIFIER) {
3414 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3417 symbol_t *symbol = token.v.symbol;
3418 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3420 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3421 errorf(HERE, "'%Y' is not a variable name.", symbol);
3422 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3424 variable_t *variable = &entity->variable;
3426 if (based_spec->base_variable != NULL) {
3427 errorf(HERE, "__based type qualifier specified more than once");
3429 based_spec->source_position = token.source_position;
3430 based_spec->base_variable = variable;
3432 type_t *const type = variable->base.type;
3434 if (is_type_valid(type)) {
3435 if (! is_type_pointer(skip_typeref(type))) {
3436 errorf(HERE, "variable in __based modifier must have pointer type instead of %T", type);
3438 if (variable->base.base.parent_scope != file_scope) {
3439 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3447 * Finish the construction of a struct type by calculating
3448 * its size, offsets, alignment.
3450 static void finish_struct_type(compound_type_t *type)
3452 assert(type->compound != NULL);
3454 compound_t *compound = type->compound;
3455 if (!compound->complete)
3460 il_alignment_t alignment = 1;
3461 bool need_pad = false;
3463 entity_t *entry = compound->members.entities;
3464 for (; entry != NULL; entry = entry->base.next) {
3465 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3468 type_t *m_type = skip_typeref(entry->declaration.type);
3469 if (! is_type_valid(m_type)) {
3470 /* simply ignore errors here */
3473 il_alignment_t m_alignment = m_type->base.alignment;
3474 if (m_alignment > alignment)
3475 alignment = m_alignment;
3477 offset = (size + m_alignment - 1) & -m_alignment;
3481 entry->compound_member.offset = offset;
3482 size = offset + m_type->base.size;
3484 if (type->base.alignment != 0) {
3485 alignment = type->base.alignment;
3488 offset = (size + alignment - 1) & -alignment;
3492 if (warning.padded && need_pad) {
3493 warningf(&compound->base.source_position,
3494 "'%#T' needs padding", type, compound->base.symbol);
3496 if (warning.packed && !need_pad) {
3497 warningf(&compound->base.source_position,
3498 "superfluous packed attribute on '%#T'",
3499 type, compound->base.symbol);
3502 type->base.size = offset;
3503 type->base.alignment = alignment;
3507 * Finish the construction of an union type by calculating
3508 * its size and alignment.
3510 static void finish_union_type(compound_type_t *type)
3512 assert(type->compound != NULL);
3514 compound_t *compound = type->compound;
3515 if (! compound->complete)
3519 il_alignment_t alignment = 1;
3521 entity_t *entry = compound->members.entities;
3522 for (; entry != NULL; entry = entry->base.next) {
3523 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3526 type_t *m_type = skip_typeref(entry->declaration.type);
3527 if (! is_type_valid(m_type))
3530 entry->compound_member.offset = 0;
3531 if (m_type->base.size > size)
3532 size = m_type->base.size;
3533 if (m_type->base.alignment > alignment)
3534 alignment = m_type->base.alignment;
3536 if (type->base.alignment != 0) {
3537 alignment = type->base.alignment;
3539 size = (size + alignment - 1) & -alignment;
3540 type->base.size = size;
3541 type->base.alignment = alignment;
3544 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3546 type_t *type = NULL;
3547 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3548 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3549 unsigned type_specifiers = 0;
3550 bool newtype = false;
3551 bool saw_error = false;
3552 bool old_gcc_extension = in_gcc_extension;
3554 specifiers->source_position = token.source_position;
3557 specifiers->modifiers
3558 |= parse_attributes(&specifiers->gnu_attributes);
3559 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3560 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3562 switch (token.type) {
3565 #define MATCH_STORAGE_CLASS(token, class) \
3567 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3568 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3570 specifiers->storage_class = class; \
3574 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3575 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3576 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3577 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3578 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3583 add_anchor_token(')');
3584 parse_microsoft_extended_decl_modifier(specifiers);
3585 rem_anchor_token(')');
3590 switch (specifiers->storage_class) {
3591 case STORAGE_CLASS_NONE:
3592 specifiers->storage_class = STORAGE_CLASS_THREAD;
3595 case STORAGE_CLASS_EXTERN:
3596 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3599 case STORAGE_CLASS_STATIC:
3600 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3604 errorf(HERE, "multiple storage classes in declaration specifiers");
3610 /* type qualifiers */
3611 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3613 qualifiers |= qualifier; \
3617 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3618 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3619 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3620 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3621 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3622 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3623 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3624 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3626 case T___extension__:
3628 in_gcc_extension = true;
3631 /* type specifiers */
3632 #define MATCH_SPECIFIER(token, specifier, name) \
3634 if (type_specifiers & specifier) { \
3635 errorf(HERE, "multiple " name " type specifiers given"); \
3637 type_specifiers |= specifier; \
3642 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3643 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3644 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3645 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3646 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3647 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3648 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3649 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3650 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3651 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3652 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3653 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3654 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3655 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3656 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3657 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3658 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3660 case T__forceinline:
3661 /* only in microsoft mode */
3662 specifiers->modifiers |= DM_FORCEINLINE;
3667 specifiers->is_inline = true;
3671 if (type_specifiers & SPECIFIER_LONG_LONG) {
3672 errorf(HERE, "multiple type specifiers given");
3673 } else if (type_specifiers & SPECIFIER_LONG) {
3674 type_specifiers |= SPECIFIER_LONG_LONG;
3676 type_specifiers |= SPECIFIER_LONG;
3682 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3684 type->compound.compound = parse_compound_type_specifier(true);
3685 finish_struct_type(&type->compound);
3689 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3690 type->compound.compound = parse_compound_type_specifier(false);
3691 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3692 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3693 finish_union_type(&type->compound);
3697 type = parse_enum_specifier();
3700 type = parse_typeof();
3702 case T___builtin_va_list:
3703 type = duplicate_type(type_valist);
3707 case T_IDENTIFIER: {
3708 /* only parse identifier if we haven't found a type yet */
3709 if (type != NULL || type_specifiers != 0) {
3710 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3711 * declaration, so it doesn't generate errors about expecting '(' or
3713 switch (look_ahead(1)->type) {
3720 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3724 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3729 goto finish_specifiers;
3733 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3734 if (typedef_type == NULL) {
3735 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3736 * declaration, so it doesn't generate 'implicit int' followed by more
3737 * errors later on. */
3738 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3744 errorf(HERE, "%K does not name a type", &token);
3747 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3749 type = allocate_type_zero(TYPE_TYPEDEF);
3750 type->typedeft.typedefe = &entity->typedefe;
3754 if (la1_type == '&' || la1_type == '*')
3755 goto finish_specifiers;
3760 goto finish_specifiers;
3765 type = typedef_type;
3769 /* function specifier */
3771 goto finish_specifiers;
3776 in_gcc_extension = old_gcc_extension;
3778 if (type == NULL || (saw_error && type_specifiers != 0)) {
3779 atomic_type_kind_t atomic_type;
3781 /* match valid basic types */
3782 switch (type_specifiers) {
3783 case SPECIFIER_VOID:
3784 atomic_type = ATOMIC_TYPE_VOID;
3786 case SPECIFIER_CHAR:
3787 atomic_type = ATOMIC_TYPE_CHAR;
3789 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3790 atomic_type = ATOMIC_TYPE_SCHAR;
3792 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3793 atomic_type = ATOMIC_TYPE_UCHAR;
3795 case SPECIFIER_SHORT:
3796 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3797 case SPECIFIER_SHORT | SPECIFIER_INT:
3798 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3799 atomic_type = ATOMIC_TYPE_SHORT;
3801 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3802 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3803 atomic_type = ATOMIC_TYPE_USHORT;
3806 case SPECIFIER_SIGNED:
3807 case SPECIFIER_SIGNED | SPECIFIER_INT:
3808 atomic_type = ATOMIC_TYPE_INT;
3810 case SPECIFIER_UNSIGNED:
3811 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3812 atomic_type = ATOMIC_TYPE_UINT;
3814 case SPECIFIER_LONG:
3815 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3816 case SPECIFIER_LONG | SPECIFIER_INT:
3817 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3818 atomic_type = ATOMIC_TYPE_LONG;
3820 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3821 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3822 atomic_type = ATOMIC_TYPE_ULONG;
3825 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3826 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3827 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3828 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3830 atomic_type = ATOMIC_TYPE_LONGLONG;
3831 goto warn_about_long_long;
3833 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3834 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3836 atomic_type = ATOMIC_TYPE_ULONGLONG;
3837 warn_about_long_long:
3838 if (warning.long_long) {
3839 warningf(&specifiers->source_position,
3840 "ISO C90 does not support 'long long'");
3844 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3845 atomic_type = unsigned_int8_type_kind;
3848 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3849 atomic_type = unsigned_int16_type_kind;
3852 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3853 atomic_type = unsigned_int32_type_kind;
3856 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3857 atomic_type = unsigned_int64_type_kind;
3860 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3861 atomic_type = unsigned_int128_type_kind;
3864 case SPECIFIER_INT8:
3865 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3866 atomic_type = int8_type_kind;
3869 case SPECIFIER_INT16:
3870 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3871 atomic_type = int16_type_kind;
3874 case SPECIFIER_INT32:
3875 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3876 atomic_type = int32_type_kind;
3879 case SPECIFIER_INT64:
3880 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3881 atomic_type = int64_type_kind;
3884 case SPECIFIER_INT128:
3885 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3886 atomic_type = int128_type_kind;
3889 case SPECIFIER_FLOAT:
3890 atomic_type = ATOMIC_TYPE_FLOAT;
3892 case SPECIFIER_DOUBLE:
3893 atomic_type = ATOMIC_TYPE_DOUBLE;
3895 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3896 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3898 case SPECIFIER_BOOL:
3899 atomic_type = ATOMIC_TYPE_BOOL;
3901 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3902 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3903 atomic_type = ATOMIC_TYPE_FLOAT;
3905 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3906 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3907 atomic_type = ATOMIC_TYPE_DOUBLE;
3909 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3910 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3911 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3914 /* invalid specifier combination, give an error message */
3915 if (type_specifiers == 0) {
3919 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3920 if (!(c_mode & _CXX) && !strict_mode) {
3921 if (warning.implicit_int) {
3922 warningf(HERE, "no type specifiers in declaration, using 'int'");
3924 atomic_type = ATOMIC_TYPE_INT;
3927 errorf(HERE, "no type specifiers given in declaration");
3929 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3930 (type_specifiers & SPECIFIER_UNSIGNED)) {
3931 errorf(HERE, "signed and unsigned specifiers given");
3932 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3933 errorf(HERE, "only integer types can be signed or unsigned");
3935 errorf(HERE, "multiple datatypes in declaration");
3940 if (type_specifiers & SPECIFIER_COMPLEX) {
3941 type = allocate_type_zero(TYPE_COMPLEX);
3942 type->complex.akind = atomic_type;
3943 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3944 type = allocate_type_zero(TYPE_IMAGINARY);
3945 type->imaginary.akind = atomic_type;
3947 type = allocate_type_zero(TYPE_ATOMIC);
3948 type->atomic.akind = atomic_type;
3951 } else if (type_specifiers != 0) {
3952 errorf(HERE, "multiple datatypes in declaration");
3955 /* FIXME: check type qualifiers here */
3957 type->base.qualifiers = qualifiers;
3958 type->base.modifiers = modifiers;
3960 type_t *result = typehash_insert(type);
3961 if (newtype && result != type) {
3965 specifiers->type = result;
3969 specifiers->type = type_error_type;
3973 static type_qualifiers_t parse_type_qualifiers(void)
3975 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3978 switch (token.type) {
3979 /* type qualifiers */
3980 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3981 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3982 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3983 /* microsoft extended type modifiers */
3984 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3985 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3986 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3987 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3988 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3997 * Parses an K&R identifier list
3999 static void parse_identifier_list(scope_t *scope)
4002 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4003 entity->base.source_position = token.source_position;
4004 entity->base.namespc = NAMESPACE_NORMAL;
4005 entity->base.symbol = token.v.symbol;
4006 /* a K&R parameter has no type, yet */
4009 append_entity(scope, entity);
4011 if (token.type != ',') {
4015 } while (token.type == T_IDENTIFIER);
4018 static type_t *automatic_type_conversion(type_t *orig_type);
4020 static void semantic_parameter(declaration_t *declaration)
4022 /* TODO: improve error messages */
4023 source_position_t const* const pos = &declaration->base.source_position;
4025 /* §6.9.1:6 The declarations in the declaration list shall contain no
4026 * storage-class specifier other than register and no
4027 * initializations. */
4028 switch (declaration->declared_storage_class) {
4029 /* Allowed storage classes */
4030 case STORAGE_CLASS_NONE:
4031 case STORAGE_CLASS_REGISTER:
4035 errorf(pos, "parameter may only have none or register storage class");
4039 type_t *const orig_type = declaration->type;
4040 /* §6.7.5.3:7 A declaration of a parameter as ``array of type'' shall be
4041 * adjusted to ``qualified pointer to type'', [...]
4042 * §6.7.5.3:8 A declaration of a parameter as ``function returning type''
4043 * shall be adjusted to ``pointer to function returning type'',
4046 type_t *const type = automatic_type_conversion(orig_type);
4047 declaration->type = type;
4049 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type list in
4050 * a function declarator that is part of a definition of that
4051 * function shall not have incomplete type. */
4052 if (is_type_incomplete(skip_typeref(type))) {
4053 errorf(pos, "parameter '%#T' has incomplete type",
4054 orig_type, declaration->base.symbol);
4058 static entity_t *parse_parameter(void)
4060 declaration_specifiers_t specifiers;
4061 memset(&specifiers, 0, sizeof(specifiers));
4063 parse_declaration_specifiers(&specifiers);
4065 entity_t *entity = parse_declarator(&specifiers, true, false);
4066 anonymous_entity = NULL;
4071 * Parses function type parameters (and optionally creates variable_t entities
4072 * for them in a scope)
4074 static void parse_parameters(function_type_t *type, scope_t *scope)
4077 add_anchor_token(')');
4078 int saved_comma_state = save_and_reset_anchor_state(',');
4080 if (token.type == T_IDENTIFIER &&
4081 !is_typedef_symbol(token.v.symbol)) {
4082 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4083 if (la1_type == ',' || la1_type == ')') {
4084 type->kr_style_parameters = true;
4085 parse_identifier_list(scope);
4086 goto parameters_finished;
4090 if (token.type == ')') {
4091 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4092 if (!(c_mode & _CXX))
4093 type->unspecified_parameters = true;
4094 goto parameters_finished;
4097 function_parameter_t *parameter;
4098 function_parameter_t *last_parameter = NULL;
4101 switch (token.type) {
4104 type->variadic = true;
4105 goto parameters_finished;
4108 case T___extension__:
4111 entity_t *entity = parse_parameter();
4112 if (entity->kind == ENTITY_TYPEDEF) {
4113 errorf(&entity->base.source_position,
4114 "typedef not allowed as function parameter");
4117 assert(is_declaration(entity));
4119 /* func(void) is not a parameter */
4120 if (last_parameter == NULL
4121 && token.type == ')'
4122 && entity->base.symbol == NULL
4123 && skip_typeref(entity->declaration.type) == type_void) {
4124 goto parameters_finished;
4126 semantic_parameter(&entity->declaration);
4128 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4129 memset(parameter, 0, sizeof(parameter[0]));
4130 parameter->type = entity->declaration.type;
4132 if (scope != NULL) {
4133 append_entity(scope, entity);
4136 if (last_parameter != NULL) {
4137 last_parameter->next = parameter;
4139 type->parameters = parameter;
4141 last_parameter = parameter;
4146 goto parameters_finished;
4148 if (token.type != ',') {
4149 goto parameters_finished;
4155 parameters_finished:
4156 rem_anchor_token(')');
4160 restore_anchor_state(',', saved_comma_state);
4163 typedef enum construct_type_kind_t {
4166 CONSTRUCT_REFERENCE,
4169 } construct_type_kind_t;
4171 typedef struct construct_type_t construct_type_t;
4172 struct construct_type_t {
4173 construct_type_kind_t kind;
4174 construct_type_t *next;
4177 typedef struct parsed_pointer_t parsed_pointer_t;
4178 struct parsed_pointer_t {
4179 construct_type_t construct_type;
4180 type_qualifiers_t type_qualifiers;
4181 variable_t *base_variable; /**< MS __based extension. */
4184 typedef struct parsed_reference_t parsed_reference_t;
4185 struct parsed_reference_t {
4186 construct_type_t construct_type;
4189 typedef struct construct_function_type_t construct_function_type_t;
4190 struct construct_function_type_t {
4191 construct_type_t construct_type;
4192 type_t *function_type;
4195 typedef struct parsed_array_t parsed_array_t;
4196 struct parsed_array_t {
4197 construct_type_t construct_type;
4198 type_qualifiers_t type_qualifiers;
4204 typedef struct construct_base_type_t construct_base_type_t;
4205 struct construct_base_type_t {
4206 construct_type_t construct_type;
4210 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4214 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4215 memset(pointer, 0, sizeof(pointer[0]));
4216 pointer->construct_type.kind = CONSTRUCT_POINTER;
4217 pointer->type_qualifiers = parse_type_qualifiers();
4218 pointer->base_variable = base_variable;
4220 return &pointer->construct_type;
4223 static construct_type_t *parse_reference_declarator(void)
4227 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4228 memset(reference, 0, sizeof(reference[0]));
4229 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4231 return (construct_type_t*)reference;
4234 static construct_type_t *parse_array_declarator(void)
4237 add_anchor_token(']');
4239 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4240 memset(array, 0, sizeof(array[0]));
4241 array->construct_type.kind = CONSTRUCT_ARRAY;
4243 if (token.type == T_static) {
4244 array->is_static = true;
4248 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4249 if (type_qualifiers != 0) {
4250 if (token.type == T_static) {
4251 array->is_static = true;
4255 array->type_qualifiers = type_qualifiers;
4257 if (token.type == '*' && look_ahead(1)->type == ']') {
4258 array->is_variable = true;
4260 } else if (token.type != ']') {
4261 array->size = parse_assignment_expression();
4264 rem_anchor_token(']');
4268 return &array->construct_type;
4271 static construct_type_t *parse_function_declarator(scope_t *scope,
4272 decl_modifiers_t modifiers)
4274 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4275 function_type_t *ftype = &type->function;
4277 ftype->linkage = current_linkage;
4279 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4280 case DM_NONE: break;
4281 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4282 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4283 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4284 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4287 errorf(HERE, "multiple calling conventions in declaration");
4291 parse_parameters(ftype, scope);
4293 construct_function_type_t *construct_function_type =
4294 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4295 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4296 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4297 construct_function_type->function_type = type;
4299 return &construct_function_type->construct_type;
4302 typedef struct parse_declarator_env_t {
4303 decl_modifiers_t modifiers;
4305 source_position_t source_position;
4307 } parse_declarator_env_t;
4309 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4310 bool may_be_abstract)
4312 /* construct a single linked list of construct_type_t's which describe
4313 * how to construct the final declarator type */
4314 construct_type_t *first = NULL;
4315 construct_type_t *last = NULL;
4316 gnu_attribute_t *attributes = NULL;
4318 decl_modifiers_t modifiers = parse_attributes(&attributes);
4320 /* MS __based extension */
4321 based_spec_t base_spec;
4322 base_spec.base_variable = NULL;
4325 construct_type_t *type;
4326 switch (token.type) {
4328 if (!(c_mode & _CXX))
4329 errorf(HERE, "references are only available for C++");
4330 if (base_spec.base_variable != NULL && warning.other) {
4331 warningf(&base_spec.source_position,
4332 "__based does not precede a pointer operator, ignored");
4334 type = parse_reference_declarator();
4336 base_spec.base_variable = NULL;
4340 type = parse_pointer_declarator(base_spec.base_variable);
4342 base_spec.base_variable = NULL;
4348 add_anchor_token(')');
4349 parse_microsoft_based(&base_spec);
4350 rem_anchor_token(')');
4355 goto ptr_operator_end;
4366 /* TODO: find out if this is correct */
4367 modifiers |= parse_attributes(&attributes);
4370 if (base_spec.base_variable != NULL && warning.other) {
4371 warningf(&base_spec.source_position,
4372 "__based does not precede a pointer operator, ignored");
4376 modifiers |= env->modifiers;
4377 env->modifiers = modifiers;
4380 construct_type_t *inner_types = NULL;
4382 switch (token.type) {
4385 errorf(HERE, "no identifier expected in typename");
4387 env->symbol = token.v.symbol;
4388 env->source_position = token.source_position;
4394 add_anchor_token(')');
4395 inner_types = parse_inner_declarator(env, may_be_abstract);
4396 if (inner_types != NULL) {
4397 /* All later declarators only modify the return type */
4400 rem_anchor_token(')');
4404 if (may_be_abstract)
4406 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4411 construct_type_t *p = last;
4414 construct_type_t *type;
4415 switch (token.type) {
4417 scope_t *scope = NULL;
4419 scope = &env->parameters;
4421 type = parse_function_declarator(scope, modifiers);
4425 type = parse_array_declarator();
4428 goto declarator_finished;
4431 /* insert in the middle of the list (behind p) */
4433 type->next = p->next;
4444 declarator_finished:
4445 /* append inner_types at the end of the list, we don't to set last anymore
4446 * as it's not needed anymore */
4448 assert(first == NULL);
4449 first = inner_types;
4451 last->next = inner_types;
4459 static void parse_declaration_attributes(entity_t *entity)
4461 gnu_attribute_t *attributes = NULL;
4462 decl_modifiers_t modifiers = parse_attributes(&attributes);
4468 if (entity->kind == ENTITY_TYPEDEF) {
4469 modifiers |= entity->typedefe.modifiers;
4470 type = entity->typedefe.type;
4472 assert(is_declaration(entity));
4473 modifiers |= entity->declaration.modifiers;
4474 type = entity->declaration.type;
4479 /* handle these strange/stupid mode attributes */
4480 gnu_attribute_t *attribute = attributes;
4481 for ( ; attribute != NULL; attribute = attribute->next) {
4482 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4485 atomic_type_kind_t akind = attribute->u.akind;
4486 if (!is_type_signed(type)) {
4488 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4489 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4490 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4491 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4493 panic("invalid akind in mode attribute");
4497 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4498 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4499 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4500 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4502 panic("invalid akind in mode attribute");
4506 type = make_atomic_type(akind, type->base.qualifiers);
4509 type_modifiers_t type_modifiers = type->base.modifiers;
4510 if (modifiers & DM_TRANSPARENT_UNION)
4511 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4513 if (type->base.modifiers != type_modifiers) {
4514 type_t *copy = duplicate_type(type);
4515 copy->base.modifiers = type_modifiers;
4517 type = typehash_insert(copy);
4519 obstack_free(type_obst, copy);
4523 if (entity->kind == ENTITY_TYPEDEF) {
4524 entity->typedefe.type = type;
4525 entity->typedefe.modifiers = modifiers;
4527 entity->declaration.type = type;
4528 entity->declaration.modifiers = modifiers;
4532 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4534 construct_type_t *iter = construct_list;
4535 for (; iter != NULL; iter = iter->next) {
4536 switch (iter->kind) {
4537 case CONSTRUCT_INVALID:
4538 internal_errorf(HERE, "invalid type construction found");
4539 case CONSTRUCT_FUNCTION: {
4540 construct_function_type_t *construct_function_type
4541 = (construct_function_type_t*) iter;
4543 type_t *function_type = construct_function_type->function_type;
4545 function_type->function.return_type = type;
4547 type_t *skipped_return_type = skip_typeref(type);
4549 if (is_type_function(skipped_return_type)) {
4550 errorf(HERE, "function returning function is not allowed");
4551 } else if (is_type_array(skipped_return_type)) {
4552 errorf(HERE, "function returning array is not allowed");
4554 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4556 "type qualifiers in return type of function type are meaningless");
4560 type = function_type;
4564 case CONSTRUCT_POINTER: {
4565 if (is_type_reference(skip_typeref(type)))
4566 errorf(HERE, "cannot declare a pointer to reference");
4568 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4569 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4573 case CONSTRUCT_REFERENCE:
4574 if (is_type_reference(skip_typeref(type)))
4575 errorf(HERE, "cannot declare a reference to reference");
4577 type = make_reference_type(type);
4580 case CONSTRUCT_ARRAY: {
4581 if (is_type_reference(skip_typeref(type)))
4582 errorf(HERE, "cannot declare an array of references");
4584 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4585 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4587 expression_t *size_expression = parsed_array->size;
4588 if (size_expression != NULL) {
4590 = create_implicit_cast(size_expression, type_size_t);
4593 array_type->base.qualifiers = parsed_array->type_qualifiers;
4594 array_type->array.element_type = type;
4595 array_type->array.is_static = parsed_array->is_static;
4596 array_type->array.is_variable = parsed_array->is_variable;
4597 array_type->array.size_expression = size_expression;
4599 if (size_expression != NULL) {
4600 if (is_constant_expression(size_expression)) {
4601 array_type->array.size_constant = true;
4602 array_type->array.size
4603 = fold_constant(size_expression);
4605 array_type->array.is_vla = true;
4609 type_t *skipped_type = skip_typeref(type);
4611 if (is_type_incomplete(skipped_type)) {
4612 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4613 } else if (is_type_function(skipped_type)) {
4614 errorf(HERE, "array of functions is not allowed");
4621 type_t *hashed_type = typehash_insert(type);
4622 if (hashed_type != type) {
4623 /* the function type was constructed earlier freeing it here will
4624 * destroy other types... */
4625 if (iter->kind != CONSTRUCT_FUNCTION) {
4635 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4636 bool may_be_abstract,
4637 bool create_compound_member)
4639 parse_declarator_env_t env;
4640 memset(&env, 0, sizeof(env));
4641 env.modifiers = specifiers->modifiers;
4643 construct_type_t *construct_type
4644 = parse_inner_declarator(&env, may_be_abstract);
4645 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4647 if (construct_type != NULL) {
4648 obstack_free(&temp_obst, construct_type);
4652 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4653 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4654 entity->base.symbol = env.symbol;
4655 entity->base.source_position = env.source_position;
4656 entity->typedefe.type = type;
4658 if (anonymous_entity != NULL) {
4659 if (is_type_compound(type)) {
4660 assert(anonymous_entity->compound.alias == NULL);
4661 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4662 anonymous_entity->kind == ENTITY_UNION);
4663 anonymous_entity->compound.alias = entity;
4664 anonymous_entity = NULL;
4665 } else if (is_type_enum(type)) {
4666 assert(anonymous_entity->enume.alias == NULL);
4667 assert(anonymous_entity->kind == ENTITY_ENUM);
4668 anonymous_entity->enume.alias = entity;
4669 anonymous_entity = NULL;
4673 if (create_compound_member) {
4674 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4675 } else if (is_type_function(skip_typeref(type))) {
4676 entity = allocate_entity_zero(ENTITY_FUNCTION);
4678 entity->function.is_inline = specifiers->is_inline;
4679 entity->function.parameters = env.parameters;
4681 entity = allocate_entity_zero(ENTITY_VARIABLE);
4683 entity->variable.get_property_sym = specifiers->get_property_sym;
4684 entity->variable.put_property_sym = specifiers->put_property_sym;
4685 if (specifiers->alignment != 0) {
4686 /* TODO: add checks here */
4687 entity->variable.alignment = specifiers->alignment;
4690 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4691 warningf(&env.source_position,
4692 "variable '%Y' declared 'inline'\n", env.symbol);
4696 entity->base.source_position = env.source_position;
4697 entity->base.symbol = env.symbol;
4698 entity->base.namespc = NAMESPACE_NORMAL;
4699 entity->declaration.type = type;
4700 entity->declaration.modifiers = env.modifiers;
4701 entity->declaration.deprecated_string = specifiers->deprecated_string;
4703 storage_class_t storage_class = specifiers->storage_class;
4704 entity->declaration.declared_storage_class = storage_class;
4706 if (storage_class == STORAGE_CLASS_NONE
4707 && current_scope != file_scope) {
4708 storage_class = STORAGE_CLASS_AUTO;
4710 entity->declaration.storage_class = storage_class;
4713 parse_declaration_attributes(entity);
4718 static type_t *parse_abstract_declarator(type_t *base_type)
4720 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4722 type_t *result = construct_declarator_type(construct_type, base_type);
4723 if (construct_type != NULL) {
4724 obstack_free(&temp_obst, construct_type);
4731 * Check if the declaration of main is suspicious. main should be a
4732 * function with external linkage, returning int, taking either zero
4733 * arguments, two, or three arguments of appropriate types, ie.
4735 * int main([ int argc, char **argv [, char **env ] ]).
4737 * @param decl the declaration to check
4738 * @param type the function type of the declaration
4740 static void check_type_of_main(const entity_t *entity)
4742 const source_position_t *pos = &entity->base.source_position;
4743 if (entity->kind != ENTITY_FUNCTION) {
4744 warningf(pos, "'main' is not a function");
4748 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4749 warningf(pos, "'main' is normally a non-static function");
4752 type_t *type = skip_typeref(entity->declaration.type);
4753 assert(is_type_function(type));
4755 function_type_t *func_type = &type->function;
4756 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4757 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4758 func_type->return_type);
4760 const function_parameter_t *parm = func_type->parameters;
4762 type_t *const first_type = parm->type;
4763 if (!types_compatible(skip_typeref(first_type), type_int)) {
4765 "first argument of 'main' should be 'int', but is '%T'",
4770 type_t *const second_type = parm->type;
4771 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4772 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4776 type_t *const third_type = parm->type;
4777 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4778 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4782 goto warn_arg_count;
4786 warningf(pos, "'main' takes only zero, two or three arguments");
4792 * Check if a symbol is the equal to "main".
4794 static bool is_sym_main(const symbol_t *const sym)
4796 return strcmp(sym->string, "main") == 0;
4799 static const char *get_entity_kind_name(entity_kind_t kind)
4801 switch ((entity_kind_tag_t) kind) {
4802 case ENTITY_FUNCTION: return "function";
4803 case ENTITY_VARIABLE: return "variable";
4804 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4805 case ENTITY_STRUCT: return "struct";
4806 case ENTITY_UNION: return "union";
4807 case ENTITY_ENUM: return "enum";
4808 case ENTITY_ENUM_VALUE: return "enum value";
4809 case ENTITY_LABEL: return "label";
4810 case ENTITY_LOCAL_LABEL: return "local label";
4811 case ENTITY_TYPEDEF: return "typedef";
4812 case ENTITY_NAMESPACE: return "namespace";
4813 case ENTITY_INVALID: break;
4816 panic("Invalid entity kind encountered in get_entity_kind_name");
4819 static void error_redefined_as_different_kind(const source_position_t *pos,
4820 const entity_t *old, entity_kind_t new_kind)
4822 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4823 get_entity_kind_name(old->kind), old->base.symbol,
4824 get_entity_kind_name(new_kind), &old->base.source_position);
4828 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4829 * for various problems that occur for multiple definitions
4831 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4833 const symbol_t *const symbol = entity->base.symbol;
4834 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4835 const source_position_t *pos = &entity->base.source_position;
4837 assert(symbol != NULL);
4838 entity_t *previous_entity = get_entity(symbol, namespc);
4839 /* pushing the same entity twice will break the stack structure */
4840 assert(previous_entity != entity);
4842 if (entity->kind == ENTITY_FUNCTION) {
4843 type_t *const orig_type = entity->declaration.type;
4844 type_t *const type = skip_typeref(orig_type);
4846 assert(is_type_function(type));
4847 if (type->function.unspecified_parameters &&
4848 warning.strict_prototypes &&
4849 previous_entity == NULL) {
4850 warningf(pos, "function declaration '%#T' is not a prototype",
4854 if (warning.main && current_scope == file_scope
4855 && is_sym_main(symbol)) {
4856 check_type_of_main(entity);
4860 if (is_declaration(entity)) {
4861 if (warning.nested_externs
4862 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4863 && current_scope != file_scope) {
4864 warningf(pos, "nested extern declaration of '%#T'",
4865 entity->declaration.type, symbol);
4869 if (previous_entity != NULL
4870 && previous_entity->base.parent_scope == ¤t_function->parameters
4871 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4873 assert(previous_entity->kind == ENTITY_VARIABLE);
4875 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4876 entity->declaration.type, symbol,
4877 previous_entity->declaration.type, symbol,
4878 &previous_entity->base.source_position);
4882 if (previous_entity != NULL
4883 && previous_entity->base.parent_scope == current_scope) {
4885 if (previous_entity->kind != entity->kind) {
4886 error_redefined_as_different_kind(pos, previous_entity,
4890 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4892 "redeclaration of enum entry '%Y' (declared %P)",
4893 symbol, &previous_entity->base.source_position);
4896 if (previous_entity->kind == ENTITY_TYPEDEF) {
4897 /* TODO: C++ allows this for exactly the same type */
4899 "redefinition of typedef '%Y' (declared %P)",
4900 symbol, &previous_entity->base.source_position);
4904 /* at this point we should have only VARIABLES or FUNCTIONS */
4905 assert(is_declaration(previous_entity) && is_declaration(entity));
4907 /* can happen for K&R style declarations */
4908 if (previous_entity->kind == ENTITY_VARIABLE
4909 && previous_entity->declaration.type == NULL
4910 && entity->kind == ENTITY_VARIABLE) {
4911 previous_entity->declaration.type = entity->declaration.type;
4912 previous_entity->declaration.storage_class
4913 = entity->declaration.storage_class;
4914 previous_entity->declaration.declared_storage_class
4915 = entity->declaration.declared_storage_class;
4916 previous_entity->declaration.modifiers
4917 = entity->declaration.modifiers;
4918 previous_entity->declaration.deprecated_string
4919 = entity->declaration.deprecated_string;
4921 assert(entity->declaration.type != NULL);
4923 declaration_t *const previous_declaration
4924 = &previous_entity->declaration;
4925 declaration_t *const declaration = &entity->declaration;
4926 type_t *const orig_type = entity->declaration.type;
4927 type_t *const type = skip_typeref(orig_type);
4929 type_t *prev_type = skip_typeref(previous_declaration->type);
4931 if (!types_compatible(type, prev_type)) {
4933 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4934 orig_type, symbol, previous_declaration->type, symbol,
4935 &previous_entity->base.source_position);
4937 unsigned old_storage_class = previous_declaration->storage_class;
4938 if (warning.redundant_decls && is_definition
4939 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4940 && !(previous_declaration->modifiers & DM_USED)
4941 && !previous_declaration->used) {
4942 warningf(&previous_entity->base.source_position,
4943 "unnecessary static forward declaration for '%#T'",
4944 previous_declaration->type, symbol);
4947 unsigned new_storage_class = declaration->storage_class;
4948 if (is_type_incomplete(prev_type)) {
4949 previous_declaration->type = type;
4953 /* pretend no storage class means extern for function
4954 * declarations (except if the previous declaration is neither
4955 * none nor extern) */
4956 if (entity->kind == ENTITY_FUNCTION) {
4957 if (prev_type->function.unspecified_parameters) {
4958 previous_declaration->type = type;
4962 switch (old_storage_class) {
4963 case STORAGE_CLASS_NONE:
4964 old_storage_class = STORAGE_CLASS_EXTERN;
4967 case STORAGE_CLASS_EXTERN:
4968 if (is_definition) {
4969 if (warning.missing_prototypes &&
4970 prev_type->function.unspecified_parameters &&
4971 !is_sym_main(symbol)) {
4972 warningf(pos, "no previous prototype for '%#T'",
4975 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4976 new_storage_class = STORAGE_CLASS_EXTERN;
4985 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4986 new_storage_class == STORAGE_CLASS_EXTERN) {
4987 warn_redundant_declaration:
4988 if (!is_definition &&
4989 warning.redundant_decls &&
4990 is_type_valid(prev_type) &&
4991 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4993 "redundant declaration for '%Y' (declared %P)",
4994 symbol, &previous_entity->base.source_position);
4996 } else if (current_function == NULL) {
4997 if (old_storage_class != STORAGE_CLASS_STATIC &&
4998 new_storage_class == STORAGE_CLASS_STATIC) {
5000 "static declaration of '%Y' follows non-static declaration (declared %P)",
5001 symbol, &previous_entity->base.source_position);
5002 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5003 previous_declaration->storage_class = STORAGE_CLASS_NONE;
5004 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5006 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5008 goto error_redeclaration;
5009 goto warn_redundant_declaration;
5011 } else if (is_type_valid(prev_type)) {
5012 if (old_storage_class == new_storage_class) {
5013 error_redeclaration:
5014 errorf(pos, "redeclaration of '%Y' (declared %P)",
5015 symbol, &previous_entity->base.source_position);
5018 "redeclaration of '%Y' with different linkage (declared %P)",
5019 symbol, &previous_entity->base.source_position);
5024 previous_declaration->modifiers |= declaration->modifiers;
5025 if (entity->kind == ENTITY_FUNCTION) {
5026 previous_entity->function.is_inline |= entity->function.is_inline;
5028 return previous_entity;
5031 if (entity->kind == ENTITY_FUNCTION) {
5032 if (is_definition &&
5033 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5034 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5035 warningf(pos, "no previous prototype for '%#T'",
5036 entity->declaration.type, symbol);
5037 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5038 warningf(pos, "no previous declaration for '%#T'",
5039 entity->declaration.type, symbol);
5042 } else if (warning.missing_declarations
5043 && entity->kind == ENTITY_VARIABLE
5044 && current_scope == file_scope) {
5045 declaration_t *declaration = &entity->declaration;
5046 if (declaration->storage_class == STORAGE_CLASS_NONE ||
5047 declaration->storage_class == STORAGE_CLASS_THREAD) {
5048 warningf(pos, "no previous declaration for '%#T'",
5049 declaration->type, symbol);
5054 assert(entity->base.parent_scope == NULL);
5055 assert(current_scope != NULL);
5057 entity->base.parent_scope = current_scope;
5058 entity->base.namespc = NAMESPACE_NORMAL;
5059 environment_push(entity);
5060 append_entity(current_scope, entity);
5065 static void parser_error_multiple_definition(entity_t *entity,
5066 const source_position_t *source_position)
5068 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5069 entity->base.symbol, &entity->base.source_position);
5072 static bool is_declaration_specifier(const token_t *token,
5073 bool only_specifiers_qualifiers)
5075 switch (token->type) {
5080 return is_typedef_symbol(token->v.symbol);
5082 case T___extension__:
5084 return !only_specifiers_qualifiers;
5091 static void parse_init_declarator_rest(entity_t *entity)
5093 assert(is_declaration(entity));
5094 declaration_t *const declaration = &entity->declaration;
5098 type_t *orig_type = declaration->type;
5099 type_t *type = skip_typeref(orig_type);
5101 if (entity->kind == ENTITY_VARIABLE
5102 && entity->variable.initializer != NULL) {
5103 parser_error_multiple_definition(entity, HERE);
5106 bool must_be_constant = false;
5107 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5108 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5109 entity->base.parent_scope == file_scope) {
5110 must_be_constant = true;
5113 if (is_type_function(type)) {
5114 errorf(&entity->base.source_position,
5115 "function '%#T' is initialized like a variable",
5116 orig_type, entity->base.symbol);
5117 orig_type = type_error_type;
5120 parse_initializer_env_t env;
5121 env.type = orig_type;
5122 env.must_be_constant = must_be_constant;
5123 env.entity = entity;
5124 current_init_decl = entity;
5126 initializer_t *initializer = parse_initializer(&env);
5127 current_init_decl = NULL;
5129 if (entity->kind == ENTITY_VARIABLE) {
5130 /* § 6.7.5 (22) array initializers for arrays with unknown size
5131 * determine the array type size */
5132 declaration->type = env.type;
5133 entity->variable.initializer = initializer;
5137 /* parse rest of a declaration without any declarator */
5138 static void parse_anonymous_declaration_rest(
5139 const declaration_specifiers_t *specifiers)
5142 anonymous_entity = NULL;
5144 if (warning.other) {
5145 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5146 warningf(&specifiers->source_position,
5147 "useless storage class in empty declaration");
5150 type_t *type = specifiers->type;
5151 switch (type->kind) {
5152 case TYPE_COMPOUND_STRUCT:
5153 case TYPE_COMPOUND_UNION: {
5154 if (type->compound.compound->base.symbol == NULL) {
5155 warningf(&specifiers->source_position,
5156 "unnamed struct/union that defines no instances");
5165 warningf(&specifiers->source_position, "empty declaration");
5171 static void check_variable_type_complete(entity_t *ent)
5173 if (ent->kind != ENTITY_VARIABLE)
5176 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5177 * type for the object shall be complete [...] */
5178 declaration_t *decl = &ent->declaration;
5179 if (decl->storage_class != STORAGE_CLASS_NONE)
5182 type_t *type = decl->type;
5183 if (!is_type_incomplete(skip_typeref(type)))
5186 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5187 type, ent->base.symbol);
5191 static void parse_declaration_rest(entity_t *ndeclaration,
5192 const declaration_specifiers_t *specifiers,
5193 parsed_declaration_func finished_declaration)
5195 add_anchor_token(';');
5196 add_anchor_token(',');
5198 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5200 if (token.type == '=') {
5201 parse_init_declarator_rest(entity);
5202 } else if (entity->kind == ENTITY_VARIABLE) {
5203 type_t *type = entity->declaration.type;
5204 if (is_type_reference(skip_typeref(type))) {
5205 errorf(&entity->base.source_position,
5206 "reference '%#T' must be initialized",
5207 type, entity->base.symbol);
5211 check_variable_type_complete(entity);
5213 if (token.type != ',')
5217 add_anchor_token('=');
5218 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5219 rem_anchor_token('=');
5224 anonymous_entity = NULL;
5225 rem_anchor_token(';');
5226 rem_anchor_token(',');
5229 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5231 symbol_t *symbol = entity->base.symbol;
5232 if (symbol == NULL) {
5233 errorf(HERE, "anonymous declaration not valid as function parameter");
5237 assert(entity->base.namespc == NAMESPACE_NORMAL);
5238 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5239 if (previous_entity == NULL
5240 || previous_entity->base.parent_scope != current_scope) {
5241 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5246 if (is_definition) {
5247 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5250 return record_entity(entity, false);
5253 static void parse_declaration(parsed_declaration_func finished_declaration)
5255 declaration_specifiers_t specifiers;
5256 memset(&specifiers, 0, sizeof(specifiers));
5258 add_anchor_token(';');
5259 parse_declaration_specifiers(&specifiers);
5260 rem_anchor_token(';');
5262 if (token.type == ';') {
5263 parse_anonymous_declaration_rest(&specifiers);
5265 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5266 parse_declaration_rest(entity, &specifiers, finished_declaration);
5270 static type_t *get_default_promoted_type(type_t *orig_type)
5272 type_t *result = orig_type;
5274 type_t *type = skip_typeref(orig_type);
5275 if (is_type_integer(type)) {
5276 result = promote_integer(type);
5277 } else if (type == type_float) {
5278 result = type_double;
5284 static void parse_kr_declaration_list(entity_t *entity)
5286 if (entity->kind != ENTITY_FUNCTION)
5289 type_t *type = skip_typeref(entity->declaration.type);
5290 assert(is_type_function(type));
5291 if (!type->function.kr_style_parameters)
5295 add_anchor_token('{');
5297 /* push function parameters */
5298 size_t const top = environment_top();
5299 scope_push(&entity->function.parameters);
5301 entity_t *parameter = entity->function.parameters.entities;
5302 for ( ; parameter != NULL; parameter = parameter->base.next) {
5303 assert(parameter->base.parent_scope == NULL);
5304 parameter->base.parent_scope = current_scope;
5305 environment_push(parameter);
5308 /* parse declaration list */
5309 while (is_declaration_specifier(&token, false)) {
5310 parse_declaration(finished_kr_declaration);
5313 /* pop function parameters */
5314 assert(current_scope == &entity->function.parameters);
5316 environment_pop_to(top);
5318 /* update function type */
5319 type_t *new_type = duplicate_type(type);
5321 function_parameter_t *parameters = NULL;
5322 function_parameter_t *last_parameter = NULL;
5324 entity_t *parameter_declaration = entity->function.parameters.entities;
5325 for (; parameter_declaration != NULL;
5326 parameter_declaration = parameter_declaration->base.next) {
5327 type_t *parameter_type = parameter_declaration->declaration.type;
5328 if (parameter_type == NULL) {
5330 errorf(HERE, "no type specified for function parameter '%Y'",
5331 parameter_declaration->base.symbol);
5333 if (warning.implicit_int) {
5334 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5335 parameter_declaration->base.symbol);
5337 parameter_type = type_int;
5338 parameter_declaration->declaration.type = parameter_type;
5342 semantic_parameter(¶meter_declaration->declaration);
5343 parameter_type = parameter_declaration->declaration.type;
5346 * we need the default promoted types for the function type
5348 parameter_type = get_default_promoted_type(parameter_type);
5350 function_parameter_t *function_parameter
5351 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5352 memset(function_parameter, 0, sizeof(function_parameter[0]));
5354 function_parameter->type = parameter_type;
5355 if (last_parameter != NULL) {
5356 last_parameter->next = function_parameter;
5358 parameters = function_parameter;
5360 last_parameter = function_parameter;
5363 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5365 new_type->function.parameters = parameters;
5366 new_type->function.unspecified_parameters = true;
5368 type = typehash_insert(new_type);
5369 if (type != new_type) {
5370 obstack_free(type_obst, new_type);
5373 entity->declaration.type = type;
5375 rem_anchor_token('{');
5378 static bool first_err = true;
5381 * When called with first_err set, prints the name of the current function,
5384 static void print_in_function(void)
5388 diagnosticf("%s: In function '%Y':\n",
5389 current_function->base.base.source_position.input_name,
5390 current_function->base.base.symbol);
5395 * Check if all labels are defined in the current function.
5396 * Check if all labels are used in the current function.
5398 static void check_labels(void)
5400 for (const goto_statement_t *goto_statement = goto_first;
5401 goto_statement != NULL;
5402 goto_statement = goto_statement->next) {
5403 /* skip computed gotos */
5404 if (goto_statement->expression != NULL)
5407 label_t *label = goto_statement->label;
5410 if (label->base.source_position.input_name == NULL) {
5411 print_in_function();
5412 errorf(&goto_statement->base.source_position,
5413 "label '%Y' used but not defined", label->base.symbol);
5417 if (warning.unused_label) {
5418 for (const label_statement_t *label_statement = label_first;
5419 label_statement != NULL;
5420 label_statement = label_statement->next) {
5421 label_t *label = label_statement->label;
5423 if (! label->used) {
5424 print_in_function();
5425 warningf(&label_statement->base.source_position,
5426 "label '%Y' defined but not used", label->base.symbol);
5432 static void warn_unused_decl(entity_t *entity, entity_t *end,
5433 char const *const what)
5435 for (; entity != NULL; entity = entity->base.next) {
5436 if (!is_declaration(entity))
5439 declaration_t *declaration = &entity->declaration;
5440 if (declaration->implicit)
5443 if (!declaration->used) {
5444 print_in_function();
5445 warningf(&entity->base.source_position, "%s '%Y' is unused",
5446 what, entity->base.symbol);
5447 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5448 print_in_function();
5449 warningf(&entity->base.source_position, "%s '%Y' is never read",
5450 what, entity->base.symbol);
5458 static void check_unused_variables(statement_t *const stmt, void *const env)
5462 switch (stmt->kind) {
5463 case STATEMENT_DECLARATION: {
5464 declaration_statement_t const *const decls = &stmt->declaration;
5465 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5471 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5480 * Check declarations of current_function for unused entities.
5482 static void check_declarations(void)
5484 if (warning.unused_parameter) {
5485 const scope_t *scope = ¤t_function->parameters;
5487 /* do not issue unused warnings for main */
5488 if (!is_sym_main(current_function->base.base.symbol)) {
5489 warn_unused_decl(scope->entities, NULL, "parameter");
5492 if (warning.unused_variable) {
5493 walk_statements(current_function->statement, check_unused_variables,
5498 static int determine_truth(expression_t const* const cond)
5501 !is_constant_expression(cond) ? 0 :
5502 fold_constant(cond) != 0 ? 1 :
5506 static bool expression_returns(expression_t const *const expr)
5508 switch (expr->kind) {
5510 expression_t const *const func = expr->call.function;
5511 if (func->kind == EXPR_REFERENCE) {
5512 entity_t *entity = func->reference.entity;
5513 if (entity->kind == ENTITY_FUNCTION
5514 && entity->declaration.modifiers & DM_NORETURN)
5518 if (!expression_returns(func))
5521 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5522 if (!expression_returns(arg->expression))
5529 case EXPR_REFERENCE:
5530 case EXPR_REFERENCE_ENUM_VALUE:
5532 case EXPR_CHARACTER_CONSTANT:
5533 case EXPR_WIDE_CHARACTER_CONSTANT:
5534 case EXPR_STRING_LITERAL:
5535 case EXPR_WIDE_STRING_LITERAL:
5536 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5537 case EXPR_LABEL_ADDRESS:
5538 case EXPR_CLASSIFY_TYPE:
5539 case EXPR_SIZEOF: // TODO handle obscure VLA case
5542 case EXPR_BUILTIN_SYMBOL:
5543 case EXPR_BUILTIN_CONSTANT_P:
5544 case EXPR_BUILTIN_PREFETCH:
5547 case EXPR_STATEMENT: // TODO implement
5550 case EXPR_CONDITIONAL:
5551 // TODO handle constant expression
5553 expression_returns(expr->conditional.condition) && (
5554 expression_returns(expr->conditional.true_expression) ||
5555 expression_returns(expr->conditional.false_expression)
5559 return expression_returns(expr->select.compound);
5561 case EXPR_ARRAY_ACCESS:
5563 expression_returns(expr->array_access.array_ref) &&
5564 expression_returns(expr->array_access.index);
5567 return expression_returns(expr->va_starte.ap);
5570 return expression_returns(expr->va_arge.ap);
5572 EXPR_UNARY_CASES_MANDATORY
5573 return expression_returns(expr->unary.value);
5575 case EXPR_UNARY_THROW:
5579 // TODO handle constant lhs of && and ||
5581 expression_returns(expr->binary.left) &&
5582 expression_returns(expr->binary.right);
5588 panic("unhandled expression");
5591 static bool noreturn_candidate;
5593 static void check_reachable(statement_t *const stmt)
5595 if (stmt->base.reachable)
5597 if (stmt->kind != STATEMENT_DO_WHILE)
5598 stmt->base.reachable = true;
5600 statement_t *last = stmt;
5602 switch (stmt->kind) {
5603 case STATEMENT_INVALID:
5604 case STATEMENT_EMPTY:
5605 case STATEMENT_DECLARATION:
5606 case STATEMENT_LOCAL_LABEL:
5608 next = stmt->base.next;
5611 case STATEMENT_COMPOUND:
5612 next = stmt->compound.statements;
5615 case STATEMENT_RETURN:
5616 noreturn_candidate = false;
5619 case STATEMENT_IF: {
5620 if_statement_t const* const ifs = &stmt->ifs;
5621 int const val = determine_truth(ifs->condition);
5624 check_reachable(ifs->true_statement);
5629 if (ifs->false_statement != NULL) {
5630 check_reachable(ifs->false_statement);
5634 next = stmt->base.next;
5638 case STATEMENT_SWITCH: {
5639 switch_statement_t const *const switchs = &stmt->switchs;
5640 expression_t const *const expr = switchs->expression;
5642 if (is_constant_expression(expr)) {
5643 long const val = fold_constant(expr);
5644 case_label_statement_t * defaults = NULL;
5645 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5646 if (i->expression == NULL) {
5651 if (i->first_case <= val && val <= i->last_case) {
5652 check_reachable((statement_t*)i);
5657 if (defaults != NULL) {
5658 check_reachable((statement_t*)defaults);
5662 bool has_default = false;
5663 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5664 if (i->expression == NULL)
5667 check_reachable((statement_t*)i);
5674 next = stmt->base.next;
5678 case STATEMENT_EXPRESSION: {
5679 /* Check for noreturn function call */
5680 expression_t const *const expr = stmt->expression.expression;
5681 if (!expression_returns(expr))
5684 next = stmt->base.next;
5688 case STATEMENT_CONTINUE: {
5689 statement_t *parent = stmt;
5691 parent = parent->base.parent;
5692 if (parent == NULL) /* continue not within loop */
5696 switch (parent->kind) {
5697 case STATEMENT_WHILE: goto continue_while;
5698 case STATEMENT_DO_WHILE: goto continue_do_while;
5699 case STATEMENT_FOR: goto continue_for;
5706 case STATEMENT_BREAK: {
5707 statement_t *parent = stmt;
5709 parent = parent->base.parent;
5710 if (parent == NULL) /* break not within loop/switch */
5713 switch (parent->kind) {
5714 case STATEMENT_SWITCH:
5715 case STATEMENT_WHILE:
5716 case STATEMENT_DO_WHILE:
5719 next = parent->base.next;
5720 goto found_break_parent;
5729 case STATEMENT_GOTO:
5730 if (stmt->gotos.expression) {
5731 statement_t *parent = stmt->base.parent;
5732 if (parent == NULL) /* top level goto */
5736 next = stmt->gotos.label->statement;
5737 if (next == NULL) /* missing label */
5742 case STATEMENT_LABEL:
5743 next = stmt->label.statement;
5746 case STATEMENT_CASE_LABEL:
5747 next = stmt->case_label.statement;
5750 case STATEMENT_WHILE: {
5751 while_statement_t const *const whiles = &stmt->whiles;
5752 int const val = determine_truth(whiles->condition);
5755 check_reachable(whiles->body);
5760 next = stmt->base.next;
5764 case STATEMENT_DO_WHILE:
5765 next = stmt->do_while.body;
5768 case STATEMENT_FOR: {
5769 for_statement_t *const fors = &stmt->fors;
5771 if (fors->condition_reachable)
5773 fors->condition_reachable = true;
5775 expression_t const *const cond = fors->condition;
5777 cond == NULL ? 1 : determine_truth(cond);
5780 check_reachable(fors->body);
5785 next = stmt->base.next;
5789 case STATEMENT_MS_TRY: {
5790 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5791 check_reachable(ms_try->try_statement);
5792 next = ms_try->final_statement;
5796 case STATEMENT_LEAVE: {
5797 statement_t *parent = stmt;
5799 parent = parent->base.parent;
5800 if (parent == NULL) /* __leave not within __try */
5803 if (parent->kind == STATEMENT_MS_TRY) {
5805 next = parent->ms_try.final_statement;
5813 while (next == NULL) {
5814 next = last->base.parent;
5816 noreturn_candidate = false;
5818 type_t *const type = current_function->base.type;
5819 assert(is_type_function(type));
5820 type_t *const ret = skip_typeref(type->function.return_type);
5821 if (warning.return_type &&
5822 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5823 is_type_valid(ret) &&
5824 !is_sym_main(current_function->base.base.symbol)) {
5825 warningf(&stmt->base.source_position,
5826 "control reaches end of non-void function");
5831 switch (next->kind) {
5832 case STATEMENT_INVALID:
5833 case STATEMENT_EMPTY:
5834 case STATEMENT_DECLARATION:
5835 case STATEMENT_LOCAL_LABEL:
5836 case STATEMENT_EXPRESSION:
5838 case STATEMENT_RETURN:
5839 case STATEMENT_CONTINUE:
5840 case STATEMENT_BREAK:
5841 case STATEMENT_GOTO:
5842 case STATEMENT_LEAVE:
5843 panic("invalid control flow in function");
5845 case STATEMENT_COMPOUND:
5847 case STATEMENT_SWITCH:
5848 case STATEMENT_LABEL:
5849 case STATEMENT_CASE_LABEL:
5851 next = next->base.next;
5854 case STATEMENT_WHILE: {
5856 if (next->base.reachable)
5858 next->base.reachable = true;
5860 while_statement_t const *const whiles = &next->whiles;
5861 int const val = determine_truth(whiles->condition);
5864 check_reachable(whiles->body);
5870 next = next->base.next;
5874 case STATEMENT_DO_WHILE: {
5876 if (next->base.reachable)
5878 next->base.reachable = true;
5880 do_while_statement_t const *const dw = &next->do_while;
5881 int const val = determine_truth(dw->condition);
5884 check_reachable(dw->body);
5890 next = next->base.next;
5894 case STATEMENT_FOR: {
5896 for_statement_t *const fors = &next->fors;
5898 fors->step_reachable = true;
5900 if (fors->condition_reachable)
5902 fors->condition_reachable = true;
5904 expression_t const *const cond = fors->condition;
5906 cond == NULL ? 1 : determine_truth(cond);
5909 check_reachable(fors->body);
5915 next = next->base.next;
5919 case STATEMENT_MS_TRY:
5921 next = next->ms_try.final_statement;
5926 check_reachable(next);
5929 static void check_unreachable(statement_t* const stmt, void *const env)
5933 switch (stmt->kind) {
5934 case STATEMENT_DO_WHILE:
5935 if (!stmt->base.reachable) {
5936 expression_t const *const cond = stmt->do_while.condition;
5937 if (determine_truth(cond) >= 0) {
5938 warningf(&cond->base.source_position,
5939 "condition of do-while-loop is unreachable");
5944 case STATEMENT_FOR: {
5945 for_statement_t const* const fors = &stmt->fors;
5947 // if init and step are unreachable, cond is unreachable, too
5948 if (!stmt->base.reachable && !fors->step_reachable) {
5949 warningf(&stmt->base.source_position, "statement is unreachable");
5951 if (!stmt->base.reachable && fors->initialisation != NULL) {
5952 warningf(&fors->initialisation->base.source_position,
5953 "initialisation of for-statement is unreachable");
5956 if (!fors->condition_reachable && fors->condition != NULL) {
5957 warningf(&fors->condition->base.source_position,
5958 "condition of for-statement is unreachable");
5961 if (!fors->step_reachable && fors->step != NULL) {
5962 warningf(&fors->step->base.source_position,
5963 "step of for-statement is unreachable");
5969 case STATEMENT_COMPOUND:
5970 if (stmt->compound.statements != NULL)
5975 if (!stmt->base.reachable)
5976 warningf(&stmt->base.source_position, "statement is unreachable");
5981 static void parse_external_declaration(void)
5983 /* function-definitions and declarations both start with declaration
5985 declaration_specifiers_t specifiers;
5986 memset(&specifiers, 0, sizeof(specifiers));
5988 add_anchor_token(';');
5989 parse_declaration_specifiers(&specifiers);
5990 rem_anchor_token(';');
5992 /* must be a declaration */
5993 if (token.type == ';') {
5994 parse_anonymous_declaration_rest(&specifiers);
5998 add_anchor_token(',');
5999 add_anchor_token('=');
6000 add_anchor_token(';');
6001 add_anchor_token('{');
6003 /* declarator is common to both function-definitions and declarations */
6004 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
6006 rem_anchor_token('{');
6007 rem_anchor_token(';');
6008 rem_anchor_token('=');
6009 rem_anchor_token(',');
6011 /* must be a declaration */
6012 switch (token.type) {
6016 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
6020 /* must be a function definition */
6021 parse_kr_declaration_list(ndeclaration);
6023 if (token.type != '{') {
6024 parse_error_expected("while parsing function definition", '{', NULL);
6025 eat_until_matching_token(';');
6029 assert(is_declaration(ndeclaration));
6030 type_t *type = skip_typeref(ndeclaration->declaration.type);
6032 if (!is_type_function(type)) {
6033 if (is_type_valid(type)) {
6034 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6035 type, ndeclaration->base.symbol);
6041 if (warning.aggregate_return &&
6042 is_type_compound(skip_typeref(type->function.return_type))) {
6043 warningf(HERE, "function '%Y' returns an aggregate",
6044 ndeclaration->base.symbol);
6046 if (warning.traditional && !type->function.unspecified_parameters) {
6047 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6048 ndeclaration->base.symbol);
6050 if (warning.old_style_definition && type->function.unspecified_parameters) {
6051 warningf(HERE, "old-style function definition '%Y'",
6052 ndeclaration->base.symbol);
6055 /* § 6.7.5.3 (14) a function definition with () means no
6056 * parameters (and not unspecified parameters) */
6057 if (type->function.unspecified_parameters
6058 && type->function.parameters == NULL
6059 && !type->function.kr_style_parameters) {
6060 type_t *duplicate = duplicate_type(type);
6061 duplicate->function.unspecified_parameters = false;
6063 type = typehash_insert(duplicate);
6064 if (type != duplicate) {
6065 obstack_free(type_obst, duplicate);
6067 ndeclaration->declaration.type = type;
6070 entity_t *const entity = record_entity(ndeclaration, true);
6071 assert(entity->kind == ENTITY_FUNCTION);
6072 assert(ndeclaration->kind == ENTITY_FUNCTION);
6074 function_t *function = &entity->function;
6075 if (ndeclaration != entity) {
6076 function->parameters = ndeclaration->function.parameters;
6078 assert(is_declaration(entity));
6079 type = skip_typeref(entity->declaration.type);
6081 /* push function parameters and switch scope */
6082 size_t const top = environment_top();
6083 scope_push(&function->parameters);
6085 entity_t *parameter = function->parameters.entities;
6086 for (; parameter != NULL; parameter = parameter->base.next) {
6087 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6088 parameter->base.parent_scope = current_scope;
6090 assert(parameter->base.parent_scope == NULL
6091 || parameter->base.parent_scope == current_scope);
6092 parameter->base.parent_scope = current_scope;
6093 if (parameter->base.symbol == NULL) {
6094 errorf(¶meter->base.source_position, "parameter name omitted");
6097 environment_push(parameter);
6100 if (function->statement != NULL) {
6101 parser_error_multiple_definition(entity, HERE);
6104 /* parse function body */
6105 int label_stack_top = label_top();
6106 function_t *old_current_function = current_function;
6107 current_function = function;
6108 current_parent = NULL;
6111 goto_anchor = &goto_first;
6113 label_anchor = &label_first;
6115 statement_t *const body = parse_compound_statement(false);
6116 function->statement = body;
6119 check_declarations();
6120 if (warning.return_type ||
6121 warning.unreachable_code ||
6122 (warning.missing_noreturn
6123 && !(function->base.modifiers & DM_NORETURN))) {
6124 noreturn_candidate = true;
6125 check_reachable(body);
6126 if (warning.unreachable_code)
6127 walk_statements(body, check_unreachable, NULL);
6128 if (warning.missing_noreturn &&
6129 noreturn_candidate &&
6130 !(function->base.modifiers & DM_NORETURN)) {
6131 warningf(&body->base.source_position,
6132 "function '%#T' is candidate for attribute 'noreturn'",
6133 type, entity->base.symbol);
6137 assert(current_parent == NULL);
6138 assert(current_function == function);
6139 current_function = old_current_function;
6140 label_pop_to(label_stack_top);
6143 assert(current_scope == &function->parameters);
6145 environment_pop_to(top);
6148 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6149 source_position_t *source_position,
6150 const symbol_t *symbol)
6152 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6154 type->bitfield.base_type = base_type;
6155 type->bitfield.size_expression = size;
6158 type_t *skipped_type = skip_typeref(base_type);
6159 if (!is_type_integer(skipped_type)) {
6160 errorf(HERE, "bitfield base type '%T' is not an integer type",
6164 bit_size = skipped_type->base.size * 8;
6167 if (is_constant_expression(size)) {
6168 long v = fold_constant(size);
6171 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6172 } else if (v == 0) {
6173 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6174 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6175 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6177 type->bitfield.bit_size = v;
6184 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6186 entity_t *iter = compound->members.entities;
6187 for (; iter != NULL; iter = iter->base.next) {
6188 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6191 if (iter->base.symbol == symbol) {
6193 } else if (iter->base.symbol == NULL) {
6194 type_t *type = skip_typeref(iter->declaration.type);
6195 if (is_type_compound(type)) {
6197 = find_compound_entry(type->compound.compound, symbol);
6208 static void parse_compound_declarators(compound_t *compound,
6209 const declaration_specifiers_t *specifiers)
6214 if (token.type == ':') {
6215 source_position_t source_position = *HERE;
6218 type_t *base_type = specifiers->type;
6219 expression_t *size = parse_constant_expression();
6221 type_t *type = make_bitfield_type(base_type, size,
6222 &source_position, sym_anonymous);
6224 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6225 entity->base.namespc = NAMESPACE_NORMAL;
6226 entity->base.source_position = source_position;
6227 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6228 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6229 entity->declaration.modifiers = specifiers->modifiers;
6230 entity->declaration.type = type;
6232 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6233 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6235 if (token.type == ':') {
6236 source_position_t source_position = *HERE;
6238 expression_t *size = parse_constant_expression();
6240 type_t *type = entity->declaration.type;
6241 type_t *bitfield_type = make_bitfield_type(type, size,
6242 &source_position, entity->base.symbol);
6243 entity->declaration.type = bitfield_type;
6247 /* make sure we don't define a symbol multiple times */
6248 symbol_t *symbol = entity->base.symbol;
6249 if (symbol != NULL) {
6250 entity_t *prev = find_compound_entry(compound, symbol);
6253 errorf(&entity->base.source_position,
6254 "multiple declarations of symbol '%Y' (declared %P)",
6255 symbol, &prev->base.source_position);
6259 append_entity(&compound->members, entity);
6261 type_t *orig_type = entity->declaration.type;
6262 type_t *type = skip_typeref(orig_type);
6263 if (is_type_function(type)) {
6264 errorf(&entity->base.source_position,
6265 "compound member '%Y' must not have function type '%T'",
6266 entity->base.symbol, orig_type);
6267 } else if (is_type_incomplete(type)) {
6268 /* §6.7.2.1:16 flexible array member */
6269 if (is_type_array(type) &&
6270 token.type == ';' &&
6271 look_ahead(1)->type == '}') {
6272 compound->has_flexible_member = true;
6274 errorf(&entity->base.source_position,
6275 "compound member '%Y' has incomplete type '%T'",
6276 entity->base.symbol, orig_type);
6280 if (token.type != ',')
6287 anonymous_entity = NULL;
6290 static void parse_compound_type_entries(compound_t *compound)
6293 add_anchor_token('}');
6295 while (token.type != '}') {
6296 if (token.type == T_EOF) {
6297 errorf(HERE, "EOF while parsing struct");
6300 declaration_specifiers_t specifiers;
6301 memset(&specifiers, 0, sizeof(specifiers));
6302 parse_declaration_specifiers(&specifiers);
6304 parse_compound_declarators(compound, &specifiers);
6306 rem_anchor_token('}');
6310 compound->complete = true;
6313 static type_t *parse_typename(void)
6315 declaration_specifiers_t specifiers;
6316 memset(&specifiers, 0, sizeof(specifiers));
6317 parse_declaration_specifiers(&specifiers);
6318 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6319 /* TODO: improve error message, user does probably not know what a
6320 * storage class is...
6322 errorf(HERE, "typename may not have a storage class");
6325 type_t *result = parse_abstract_declarator(specifiers.type);
6333 typedef expression_t* (*parse_expression_function)(void);
6334 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6336 typedef struct expression_parser_function_t expression_parser_function_t;
6337 struct expression_parser_function_t {
6338 parse_expression_function parser;
6339 unsigned infix_precedence;
6340 parse_expression_infix_function infix_parser;
6343 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6346 * Prints an error message if an expression was expected but not read
6348 static expression_t *expected_expression_error(void)
6350 /* skip the error message if the error token was read */
6351 if (token.type != T_ERROR) {
6352 errorf(HERE, "expected expression, got token '%K'", &token);
6356 return create_invalid_expression();
6360 * Parse a string constant.
6362 static expression_t *parse_string_const(void)
6365 if (token.type == T_STRING_LITERAL) {
6366 string_t res = token.v.string;
6368 while (token.type == T_STRING_LITERAL) {
6369 res = concat_strings(&res, &token.v.string);
6372 if (token.type != T_WIDE_STRING_LITERAL) {
6373 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6374 /* note: that we use type_char_ptr here, which is already the
6375 * automatic converted type. revert_automatic_type_conversion
6376 * will construct the array type */
6377 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6378 cnst->string.value = res;
6382 wres = concat_string_wide_string(&res, &token.v.wide_string);
6384 wres = token.v.wide_string;
6389 switch (token.type) {
6390 case T_WIDE_STRING_LITERAL:
6391 wres = concat_wide_strings(&wres, &token.v.wide_string);
6394 case T_STRING_LITERAL:
6395 wres = concat_wide_string_string(&wres, &token.v.string);
6399 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6400 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6401 cnst->wide_string.value = wres;
6410 * Parse a boolean constant.
6412 static expression_t *parse_bool_const(bool value)
6414 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6415 cnst->base.type = type_bool;
6416 cnst->conste.v.int_value = value;
6424 * Parse an integer constant.
6426 static expression_t *parse_int_const(void)
6428 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6429 cnst->base.type = token.datatype;
6430 cnst->conste.v.int_value = token.v.intvalue;
6438 * Parse a character constant.
6440 static expression_t *parse_character_constant(void)
6442 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6443 cnst->base.type = token.datatype;
6444 cnst->conste.v.character = token.v.string;
6446 if (cnst->conste.v.character.size != 1) {
6448 errorf(HERE, "more than 1 character in character constant");
6449 } else if (warning.multichar) {
6450 warningf(HERE, "multi-character character constant");
6459 * Parse a wide character constant.
6461 static expression_t *parse_wide_character_constant(void)
6463 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6464 cnst->base.type = token.datatype;
6465 cnst->conste.v.wide_character = token.v.wide_string;
6467 if (cnst->conste.v.wide_character.size != 1) {
6469 errorf(HERE, "more than 1 character in character constant");
6470 } else if (warning.multichar) {
6471 warningf(HERE, "multi-character character constant");
6480 * Parse a float constant.
6482 static expression_t *parse_float_const(void)
6484 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6485 cnst->base.type = token.datatype;
6486 cnst->conste.v.float_value = token.v.floatvalue;
6493 static entity_t *create_implicit_function(symbol_t *symbol,
6494 const source_position_t *source_position)
6496 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6497 ntype->function.return_type = type_int;
6498 ntype->function.unspecified_parameters = true;
6500 type_t *type = typehash_insert(ntype);
6501 if (type != ntype) {
6505 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6506 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6507 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6508 entity->declaration.type = type;
6509 entity->declaration.implicit = true;
6510 entity->base.symbol = symbol;
6511 entity->base.source_position = *source_position;
6513 bool strict_prototypes_old = warning.strict_prototypes;
6514 warning.strict_prototypes = false;
6515 record_entity(entity, false);
6516 warning.strict_prototypes = strict_prototypes_old;
6522 * Creates a return_type (func)(argument_type) function type if not
6525 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6526 type_t *argument_type2)
6528 function_parameter_t *parameter2
6529 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6530 memset(parameter2, 0, sizeof(parameter2[0]));
6531 parameter2->type = argument_type2;
6533 function_parameter_t *parameter1
6534 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6535 memset(parameter1, 0, sizeof(parameter1[0]));
6536 parameter1->type = argument_type1;
6537 parameter1->next = parameter2;
6539 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6540 type->function.return_type = return_type;
6541 type->function.parameters = parameter1;
6543 type_t *result = typehash_insert(type);
6544 if (result != type) {
6552 * Creates a return_type (func)(argument_type) function type if not
6555 * @param return_type the return type
6556 * @param argument_type the argument type
6558 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6560 function_parameter_t *parameter
6561 = obstack_alloc(type_obst, sizeof(parameter[0]));
6562 memset(parameter, 0, sizeof(parameter[0]));
6563 parameter->type = argument_type;
6565 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6566 type->function.return_type = return_type;
6567 type->function.parameters = parameter;
6569 type_t *result = typehash_insert(type);
6570 if (result != type) {
6577 static type_t *make_function_0_type(type_t *return_type)
6579 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6580 type->function.return_type = return_type;
6581 type->function.parameters = NULL;
6583 type_t *result = typehash_insert(type);
6584 if (result != type) {
6592 * Creates a function type for some function like builtins.
6594 * @param symbol the symbol describing the builtin
6596 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6598 switch (symbol->ID) {
6599 case T___builtin_alloca:
6600 return make_function_1_type(type_void_ptr, type_size_t);
6601 case T___builtin_huge_val:
6602 return make_function_0_type(type_double);
6603 case T___builtin_inf:
6604 return make_function_0_type(type_double);
6605 case T___builtin_inff:
6606 return make_function_0_type(type_float);
6607 case T___builtin_infl:
6608 return make_function_0_type(type_long_double);
6609 case T___builtin_nan:
6610 return make_function_1_type(type_double, type_char_ptr);
6611 case T___builtin_nanf:
6612 return make_function_1_type(type_float, type_char_ptr);
6613 case T___builtin_nanl:
6614 return make_function_1_type(type_long_double, type_char_ptr);
6615 case T___builtin_va_end:
6616 return make_function_1_type(type_void, type_valist);
6617 case T___builtin_expect:
6618 return make_function_2_type(type_long, type_long, type_long);
6620 internal_errorf(HERE, "not implemented builtin symbol found");
6625 * Performs automatic type cast as described in § 6.3.2.1.
6627 * @param orig_type the original type
6629 static type_t *automatic_type_conversion(type_t *orig_type)
6631 type_t *type = skip_typeref(orig_type);
6632 if (is_type_array(type)) {
6633 array_type_t *array_type = &type->array;
6634 type_t *element_type = array_type->element_type;
6635 unsigned qualifiers = array_type->base.qualifiers;
6637 return make_pointer_type(element_type, qualifiers);
6640 if (is_type_function(type)) {
6641 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6648 * reverts the automatic casts of array to pointer types and function
6649 * to function-pointer types as defined § 6.3.2.1
6651 type_t *revert_automatic_type_conversion(const expression_t *expression)
6653 switch (expression->kind) {
6654 case EXPR_REFERENCE: {
6655 entity_t *entity = expression->reference.entity;
6656 if (is_declaration(entity)) {
6657 return entity->declaration.type;
6658 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6659 return entity->enum_value.enum_type;
6661 panic("no declaration or enum in reference");
6666 entity_t *entity = expression->select.compound_entry;
6667 assert(is_declaration(entity));
6668 type_t *type = entity->declaration.type;
6669 return get_qualified_type(type,
6670 expression->base.type->base.qualifiers);
6673 case EXPR_UNARY_DEREFERENCE: {
6674 const expression_t *const value = expression->unary.value;
6675 type_t *const type = skip_typeref(value->base.type);
6676 assert(is_type_pointer(type));
6677 return type->pointer.points_to;
6680 case EXPR_BUILTIN_SYMBOL:
6681 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6683 case EXPR_ARRAY_ACCESS: {
6684 const expression_t *array_ref = expression->array_access.array_ref;
6685 type_t *type_left = skip_typeref(array_ref->base.type);
6686 if (!is_type_valid(type_left))
6688 assert(is_type_pointer(type_left));
6689 return type_left->pointer.points_to;
6692 case EXPR_STRING_LITERAL: {
6693 size_t size = expression->string.value.size;
6694 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6697 case EXPR_WIDE_STRING_LITERAL: {
6698 size_t size = expression->wide_string.value.size;
6699 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6702 case EXPR_COMPOUND_LITERAL:
6703 return expression->compound_literal.type;
6708 return expression->base.type;
6711 static expression_t *parse_reference(void)
6713 symbol_t *const symbol = token.v.symbol;
6715 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6717 if (entity == NULL) {
6718 if (!strict_mode && look_ahead(1)->type == '(') {
6719 /* an implicitly declared function */
6720 if (warning.implicit_function_declaration) {
6721 warningf(HERE, "implicit declaration of function '%Y'",
6725 entity = create_implicit_function(symbol, HERE);
6727 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6728 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6734 if (is_declaration(entity)) {
6735 orig_type = entity->declaration.type;
6736 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6737 orig_type = entity->enum_value.enum_type;
6738 } else if (entity->kind == ENTITY_TYPEDEF) {
6739 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6742 return create_invalid_expression();
6744 panic("expected declaration or enum value in reference");
6747 /* we always do the auto-type conversions; the & and sizeof parser contains
6748 * code to revert this! */
6749 type_t *type = automatic_type_conversion(orig_type);
6751 expression_kind_t kind = EXPR_REFERENCE;
6752 if (entity->kind == ENTITY_ENUM_VALUE)
6753 kind = EXPR_REFERENCE_ENUM_VALUE;
6755 expression_t *expression = allocate_expression_zero(kind);
6756 expression->reference.entity = entity;
6757 expression->base.type = type;
6759 /* this declaration is used */
6760 if (is_declaration(entity)) {
6761 entity->declaration.used = true;
6764 if (entity->base.parent_scope != file_scope
6765 && entity->base.parent_scope->depth < current_function->parameters.depth
6766 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6767 if (entity->kind == ENTITY_VARIABLE) {
6768 /* access of a variable from an outer function */
6769 entity->variable.address_taken = true;
6771 current_function->need_closure = true;
6774 /* check for deprecated functions */
6775 if (warning.deprecated_declarations
6776 && is_declaration(entity)
6777 && entity->declaration.modifiers & DM_DEPRECATED) {
6778 declaration_t *declaration = &entity->declaration;
6780 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6781 "function" : "variable";
6783 if (declaration->deprecated_string != NULL) {
6784 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6785 prefix, entity->base.symbol, &entity->base.source_position,
6786 declaration->deprecated_string);
6788 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6789 entity->base.symbol, &entity->base.source_position);
6793 if (warning.init_self && entity == current_init_decl && !in_type_prop
6794 && entity->kind == ENTITY_VARIABLE) {
6795 current_init_decl = NULL;
6796 warningf(HERE, "variable '%#T' is initialized by itself",
6797 entity->declaration.type, entity->base.symbol);
6804 static bool semantic_cast(expression_t *cast)
6806 expression_t *expression = cast->unary.value;
6807 type_t *orig_dest_type = cast->base.type;
6808 type_t *orig_type_right = expression->base.type;
6809 type_t const *dst_type = skip_typeref(orig_dest_type);
6810 type_t const *src_type = skip_typeref(orig_type_right);
6811 source_position_t const *pos = &cast->base.source_position;
6813 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6814 if (dst_type == type_void)
6817 /* only integer and pointer can be casted to pointer */
6818 if (is_type_pointer(dst_type) &&
6819 !is_type_pointer(src_type) &&
6820 !is_type_integer(src_type) &&
6821 is_type_valid(src_type)) {
6822 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6826 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6827 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6831 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6832 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6836 if (warning.cast_qual &&
6837 is_type_pointer(src_type) &&
6838 is_type_pointer(dst_type)) {
6839 type_t *src = skip_typeref(src_type->pointer.points_to);
6840 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6841 unsigned missing_qualifiers =
6842 src->base.qualifiers & ~dst->base.qualifiers;
6843 if (missing_qualifiers != 0) {
6845 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6846 missing_qualifiers, orig_type_right);
6852 static expression_t *parse_compound_literal(type_t *type)
6854 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6856 parse_initializer_env_t env;
6859 env.must_be_constant = false;
6860 initializer_t *initializer = parse_initializer(&env);
6863 expression->compound_literal.initializer = initializer;
6864 expression->compound_literal.type = type;
6865 expression->base.type = automatic_type_conversion(type);
6871 * Parse a cast expression.
6873 static expression_t *parse_cast(void)
6875 add_anchor_token(')');
6877 source_position_t source_position = token.source_position;
6879 type_t *type = parse_typename();
6881 rem_anchor_token(')');
6884 if (token.type == '{') {
6885 return parse_compound_literal(type);
6888 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6889 cast->base.source_position = source_position;
6891 expression_t *value = parse_sub_expression(PREC_CAST);
6892 cast->base.type = type;
6893 cast->unary.value = value;
6895 if (! semantic_cast(cast)) {
6896 /* TODO: record the error in the AST. else it is impossible to detect it */
6901 return create_invalid_expression();
6905 * Parse a statement expression.
6907 static expression_t *parse_statement_expression(void)
6909 add_anchor_token(')');
6911 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6913 statement_t *statement = parse_compound_statement(true);
6914 expression->statement.statement = statement;
6916 /* find last statement and use its type */
6917 type_t *type = type_void;
6918 const statement_t *stmt = statement->compound.statements;
6920 while (stmt->base.next != NULL)
6921 stmt = stmt->base.next;
6923 if (stmt->kind == STATEMENT_EXPRESSION) {
6924 type = stmt->expression.expression->base.type;
6926 } else if (warning.other) {
6927 warningf(&expression->base.source_position, "empty statement expression ({})");
6929 expression->base.type = type;
6931 rem_anchor_token(')');
6939 * Parse a parenthesized expression.
6941 static expression_t *parse_parenthesized_expression(void)
6945 switch (token.type) {
6947 /* gcc extension: a statement expression */
6948 return parse_statement_expression();
6952 return parse_cast();
6954 if (is_typedef_symbol(token.v.symbol)) {
6955 return parse_cast();
6959 add_anchor_token(')');
6960 expression_t *result = parse_expression();
6961 rem_anchor_token(')');
6968 static expression_t *parse_function_keyword(void)
6972 if (current_function == NULL) {
6973 errorf(HERE, "'__func__' used outside of a function");
6976 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6977 expression->base.type = type_char_ptr;
6978 expression->funcname.kind = FUNCNAME_FUNCTION;
6985 static expression_t *parse_pretty_function_keyword(void)
6987 if (current_function == NULL) {
6988 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6991 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6992 expression->base.type = type_char_ptr;
6993 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6995 eat(T___PRETTY_FUNCTION__);
7000 static expression_t *parse_funcsig_keyword(void)
7002 if (current_function == NULL) {
7003 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7006 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7007 expression->base.type = type_char_ptr;
7008 expression->funcname.kind = FUNCNAME_FUNCSIG;
7015 static expression_t *parse_funcdname_keyword(void)
7017 if (current_function == NULL) {
7018 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7021 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7022 expression->base.type = type_char_ptr;
7023 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7025 eat(T___FUNCDNAME__);
7030 static designator_t *parse_designator(void)
7032 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7033 result->source_position = *HERE;
7035 if (token.type != T_IDENTIFIER) {
7036 parse_error_expected("while parsing member designator",
7037 T_IDENTIFIER, NULL);
7040 result->symbol = token.v.symbol;
7043 designator_t *last_designator = result;
7045 if (token.type == '.') {
7047 if (token.type != T_IDENTIFIER) {
7048 parse_error_expected("while parsing member designator",
7049 T_IDENTIFIER, NULL);
7052 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7053 designator->source_position = *HERE;
7054 designator->symbol = token.v.symbol;
7057 last_designator->next = designator;
7058 last_designator = designator;
7061 if (token.type == '[') {
7063 add_anchor_token(']');
7064 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7065 designator->source_position = *HERE;
7066 designator->array_index = parse_expression();
7067 rem_anchor_token(']');
7069 if (designator->array_index == NULL) {
7073 last_designator->next = designator;
7074 last_designator = designator;
7086 * Parse the __builtin_offsetof() expression.
7088 static expression_t *parse_offsetof(void)
7090 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7091 expression->base.type = type_size_t;
7093 eat(T___builtin_offsetof);
7096 add_anchor_token(',');
7097 type_t *type = parse_typename();
7098 rem_anchor_token(',');
7100 add_anchor_token(')');
7101 designator_t *designator = parse_designator();
7102 rem_anchor_token(')');
7105 expression->offsetofe.type = type;
7106 expression->offsetofe.designator = designator;
7109 memset(&path, 0, sizeof(path));
7110 path.top_type = type;
7111 path.path = NEW_ARR_F(type_path_entry_t, 0);
7113 descend_into_subtype(&path);
7115 if (!walk_designator(&path, designator, true)) {
7116 return create_invalid_expression();
7119 DEL_ARR_F(path.path);
7123 return create_invalid_expression();
7127 * Parses a _builtin_va_start() expression.
7129 static expression_t *parse_va_start(void)
7131 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7133 eat(T___builtin_va_start);
7136 add_anchor_token(',');
7137 expression->va_starte.ap = parse_assignment_expression();
7138 rem_anchor_token(',');
7140 expression_t *const expr = parse_assignment_expression();
7141 if (expr->kind == EXPR_REFERENCE) {
7142 entity_t *const entity = expr->reference.entity;
7143 if (entity->base.parent_scope != ¤t_function->parameters
7144 || entity->base.next != NULL
7145 || entity->kind != ENTITY_VARIABLE) {
7146 errorf(&expr->base.source_position,
7147 "second argument of 'va_start' must be last parameter of the current function");
7149 expression->va_starte.parameter = &entity->variable;
7156 return create_invalid_expression();
7160 * Parses a _builtin_va_arg() expression.
7162 static expression_t *parse_va_arg(void)
7164 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7166 eat(T___builtin_va_arg);
7169 expression->va_arge.ap = parse_assignment_expression();
7171 expression->base.type = parse_typename();
7176 return create_invalid_expression();
7179 static expression_t *parse_builtin_symbol(void)
7181 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7183 symbol_t *symbol = token.v.symbol;
7185 expression->builtin_symbol.symbol = symbol;
7188 type_t *type = get_builtin_symbol_type(symbol);
7189 type = automatic_type_conversion(type);
7191 expression->base.type = type;
7196 * Parses a __builtin_constant() expression.
7198 static expression_t *parse_builtin_constant(void)
7200 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7202 eat(T___builtin_constant_p);
7205 add_anchor_token(')');
7206 expression->builtin_constant.value = parse_assignment_expression();
7207 rem_anchor_token(')');
7209 expression->base.type = type_int;
7213 return create_invalid_expression();
7217 * Parses a __builtin_prefetch() expression.
7219 static expression_t *parse_builtin_prefetch(void)
7221 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7223 eat(T___builtin_prefetch);
7226 add_anchor_token(')');
7227 expression->builtin_prefetch.adr = parse_assignment_expression();
7228 if (token.type == ',') {
7230 expression->builtin_prefetch.rw = parse_assignment_expression();
7232 if (token.type == ',') {
7234 expression->builtin_prefetch.locality = parse_assignment_expression();
7236 rem_anchor_token(')');
7238 expression->base.type = type_void;
7242 return create_invalid_expression();
7246 * Parses a __builtin_is_*() compare expression.
7248 static expression_t *parse_compare_builtin(void)
7250 expression_t *expression;
7252 switch (token.type) {
7253 case T___builtin_isgreater:
7254 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7256 case T___builtin_isgreaterequal:
7257 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7259 case T___builtin_isless:
7260 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7262 case T___builtin_islessequal:
7263 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7265 case T___builtin_islessgreater:
7266 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7268 case T___builtin_isunordered:
7269 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7272 internal_errorf(HERE, "invalid compare builtin found");
7274 expression->base.source_position = *HERE;
7278 expression->binary.left = parse_assignment_expression();
7280 expression->binary.right = parse_assignment_expression();
7283 type_t *const orig_type_left = expression->binary.left->base.type;
7284 type_t *const orig_type_right = expression->binary.right->base.type;
7286 type_t *const type_left = skip_typeref(orig_type_left);
7287 type_t *const type_right = skip_typeref(orig_type_right);
7288 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7289 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7290 type_error_incompatible("invalid operands in comparison",
7291 &expression->base.source_position, orig_type_left, orig_type_right);
7294 semantic_comparison(&expression->binary);
7299 return create_invalid_expression();
7304 * Parses a __builtin_expect() expression.
7306 static expression_t *parse_builtin_expect(void)
7308 expression_t *expression
7309 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7311 eat(T___builtin_expect);
7314 expression->binary.left = parse_assignment_expression();
7316 expression->binary.right = parse_constant_expression();
7319 expression->base.type = expression->binary.left->base.type;
7323 return create_invalid_expression();
7328 * Parses a MS assume() expression.
7330 static expression_t *parse_assume(void)
7332 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7337 add_anchor_token(')');
7338 expression->unary.value = parse_assignment_expression();
7339 rem_anchor_token(')');
7342 expression->base.type = type_void;
7345 return create_invalid_expression();
7349 * Return the declaration for a given label symbol or create a new one.
7351 * @param symbol the symbol of the label
7353 static label_t *get_label(symbol_t *symbol)
7356 assert(current_function != NULL);
7358 label = get_entity(symbol, NAMESPACE_LABEL);
7359 /* if we found a local label, we already created the declaration */
7360 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7361 if (label->base.parent_scope != current_scope) {
7362 assert(label->base.parent_scope->depth < current_scope->depth);
7363 current_function->goto_to_outer = true;
7365 return &label->label;
7368 label = get_entity(symbol, NAMESPACE_LABEL);
7369 /* if we found a label in the same function, then we already created the
7372 && label->base.parent_scope == ¤t_function->parameters) {
7373 return &label->label;
7376 /* otherwise we need to create a new one */
7377 label = allocate_entity_zero(ENTITY_LABEL);
7378 label->base.namespc = NAMESPACE_LABEL;
7379 label->base.symbol = symbol;
7383 return &label->label;
7387 * Parses a GNU && label address expression.
7389 static expression_t *parse_label_address(void)
7391 source_position_t source_position = token.source_position;
7393 if (token.type != T_IDENTIFIER) {
7394 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7397 symbol_t *symbol = token.v.symbol;
7400 label_t *label = get_label(symbol);
7402 label->address_taken = true;
7404 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7405 expression->base.source_position = source_position;
7407 /* label address is threaten as a void pointer */
7408 expression->base.type = type_void_ptr;
7409 expression->label_address.label = label;
7412 return create_invalid_expression();
7416 * Parse a microsoft __noop expression.
7418 static expression_t *parse_noop_expression(void)
7420 /* the result is a (int)0 */
7421 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7422 cnst->base.type = type_int;
7423 cnst->conste.v.int_value = 0;
7424 cnst->conste.is_ms_noop = true;
7428 if (token.type == '(') {
7429 /* parse arguments */
7431 add_anchor_token(')');
7432 add_anchor_token(',');
7434 if (token.type != ')') {
7436 (void)parse_assignment_expression();
7437 if (token.type != ',')
7443 rem_anchor_token(',');
7444 rem_anchor_token(')');
7452 * Parses a primary expression.
7454 static expression_t *parse_primary_expression(void)
7456 switch (token.type) {
7457 case T_false: return parse_bool_const(false);
7458 case T_true: return parse_bool_const(true);
7459 case T_INTEGER: return parse_int_const();
7460 case T_CHARACTER_CONSTANT: return parse_character_constant();
7461 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7462 case T_FLOATINGPOINT: return parse_float_const();
7463 case T_STRING_LITERAL:
7464 case T_WIDE_STRING_LITERAL: return parse_string_const();
7465 case T_IDENTIFIER: return parse_reference();
7466 case T___FUNCTION__:
7467 case T___func__: return parse_function_keyword();
7468 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7469 case T___FUNCSIG__: return parse_funcsig_keyword();
7470 case T___FUNCDNAME__: return parse_funcdname_keyword();
7471 case T___builtin_offsetof: return parse_offsetof();
7472 case T___builtin_va_start: return parse_va_start();
7473 case T___builtin_va_arg: return parse_va_arg();
7474 case T___builtin_expect:
7475 case T___builtin_alloca:
7476 case T___builtin_inf:
7477 case T___builtin_inff:
7478 case T___builtin_infl:
7479 case T___builtin_nan:
7480 case T___builtin_nanf:
7481 case T___builtin_nanl:
7482 case T___builtin_huge_val:
7483 case T___builtin_va_end: return parse_builtin_symbol();
7484 case T___builtin_isgreater:
7485 case T___builtin_isgreaterequal:
7486 case T___builtin_isless:
7487 case T___builtin_islessequal:
7488 case T___builtin_islessgreater:
7489 case T___builtin_isunordered: return parse_compare_builtin();
7490 case T___builtin_constant_p: return parse_builtin_constant();
7491 case T___builtin_prefetch: return parse_builtin_prefetch();
7492 case T__assume: return parse_assume();
7495 return parse_label_address();
7498 case '(': return parse_parenthesized_expression();
7499 case T___noop: return parse_noop_expression();
7502 errorf(HERE, "unexpected token %K, expected an expression", &token);
7503 return create_invalid_expression();
7507 * Check if the expression has the character type and issue a warning then.
7509 static void check_for_char_index_type(const expression_t *expression)
7511 type_t *const type = expression->base.type;
7512 const type_t *const base_type = skip_typeref(type);
7514 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7515 warning.char_subscripts) {
7516 warningf(&expression->base.source_position,
7517 "array subscript has type '%T'", type);
7521 static expression_t *parse_array_expression(expression_t *left)
7523 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7526 add_anchor_token(']');
7528 expression_t *inside = parse_expression();
7530 type_t *const orig_type_left = left->base.type;
7531 type_t *const orig_type_inside = inside->base.type;
7533 type_t *const type_left = skip_typeref(orig_type_left);
7534 type_t *const type_inside = skip_typeref(orig_type_inside);
7536 type_t *return_type;
7537 array_access_expression_t *array_access = &expression->array_access;
7538 if (is_type_pointer(type_left)) {
7539 return_type = type_left->pointer.points_to;
7540 array_access->array_ref = left;
7541 array_access->index = inside;
7542 check_for_char_index_type(inside);
7543 } else if (is_type_pointer(type_inside)) {
7544 return_type = type_inside->pointer.points_to;
7545 array_access->array_ref = inside;
7546 array_access->index = left;
7547 array_access->flipped = true;
7548 check_for_char_index_type(left);
7550 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7552 "array access on object with non-pointer types '%T', '%T'",
7553 orig_type_left, orig_type_inside);
7555 return_type = type_error_type;
7556 array_access->array_ref = left;
7557 array_access->index = inside;
7560 expression->base.type = automatic_type_conversion(return_type);
7562 rem_anchor_token(']');
7568 static expression_t *parse_typeprop(expression_kind_t const kind)
7570 expression_t *tp_expression = allocate_expression_zero(kind);
7571 tp_expression->base.type = type_size_t;
7573 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7575 /* we only refer to a type property, mark this case */
7576 bool old = in_type_prop;
7577 in_type_prop = true;
7580 expression_t *expression;
7581 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7583 add_anchor_token(')');
7584 orig_type = parse_typename();
7585 rem_anchor_token(')');
7588 if (token.type == '{') {
7589 /* It was not sizeof(type) after all. It is sizeof of an expression
7590 * starting with a compound literal */
7591 expression = parse_compound_literal(orig_type);
7592 goto typeprop_expression;
7595 expression = parse_sub_expression(PREC_UNARY);
7597 typeprop_expression:
7598 tp_expression->typeprop.tp_expression = expression;
7600 orig_type = revert_automatic_type_conversion(expression);
7601 expression->base.type = orig_type;
7604 tp_expression->typeprop.type = orig_type;
7605 type_t const* const type = skip_typeref(orig_type);
7606 char const* const wrong_type =
7607 is_type_incomplete(type) ? "incomplete" :
7608 type->kind == TYPE_FUNCTION ? "function designator" :
7609 type->kind == TYPE_BITFIELD ? "bitfield" :
7611 if (wrong_type != NULL) {
7612 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7613 errorf(&tp_expression->base.source_position,
7614 "operand of %s expression must not be of %s type '%T'",
7615 what, wrong_type, orig_type);
7620 return tp_expression;
7623 static expression_t *parse_sizeof(void)
7625 return parse_typeprop(EXPR_SIZEOF);
7628 static expression_t *parse_alignof(void)
7630 return parse_typeprop(EXPR_ALIGNOF);
7633 static expression_t *parse_select_expression(expression_t *compound)
7635 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7636 select->select.compound = compound;
7638 assert(token.type == '.' || token.type == T_MINUSGREATER);
7639 bool is_pointer = (token.type == T_MINUSGREATER);
7642 if (token.type != T_IDENTIFIER) {
7643 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7646 symbol_t *symbol = token.v.symbol;
7649 type_t *const orig_type = compound->base.type;
7650 type_t *const type = skip_typeref(orig_type);
7653 bool saw_error = false;
7654 if (is_type_pointer(type)) {
7657 "request for member '%Y' in something not a struct or union, but '%T'",
7661 type_left = skip_typeref(type->pointer.points_to);
7663 if (is_pointer && is_type_valid(type)) {
7664 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7671 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7672 type_left->kind == TYPE_COMPOUND_UNION) {
7673 compound_t *compound = type_left->compound.compound;
7675 if (!compound->complete) {
7676 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7678 goto create_error_entry;
7681 entry = find_compound_entry(compound, symbol);
7682 if (entry == NULL) {
7683 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7684 goto create_error_entry;
7687 if (is_type_valid(type_left) && !saw_error) {
7689 "request for member '%Y' in something not a struct or union, but '%T'",
7693 return create_invalid_expression();
7696 assert(is_declaration(entry));
7697 select->select.compound_entry = entry;
7699 type_t *entry_type = entry->declaration.type;
7701 = get_qualified_type(entry_type, type_left->base.qualifiers);
7703 /* we always do the auto-type conversions; the & and sizeof parser contains
7704 * code to revert this! */
7705 select->base.type = automatic_type_conversion(res_type);
7707 type_t *skipped = skip_typeref(res_type);
7708 if (skipped->kind == TYPE_BITFIELD) {
7709 select->base.type = skipped->bitfield.base_type;
7715 static void check_call_argument(const function_parameter_t *parameter,
7716 call_argument_t *argument, unsigned pos)
7718 type_t *expected_type = parameter->type;
7719 type_t *expected_type_skip = skip_typeref(expected_type);
7720 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7721 expression_t *arg_expr = argument->expression;
7722 type_t *arg_type = skip_typeref(arg_expr->base.type);
7724 /* handle transparent union gnu extension */
7725 if (is_type_union(expected_type_skip)
7726 && (expected_type_skip->base.modifiers
7727 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7728 compound_t *union_decl = expected_type_skip->compound.compound;
7729 type_t *best_type = NULL;
7730 entity_t *entry = union_decl->members.entities;
7731 for ( ; entry != NULL; entry = entry->base.next) {
7732 assert(is_declaration(entry));
7733 type_t *decl_type = entry->declaration.type;
7734 error = semantic_assign(decl_type, arg_expr);
7735 if (error == ASSIGN_ERROR_INCOMPATIBLE
7736 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7739 if (error == ASSIGN_SUCCESS) {
7740 best_type = decl_type;
7741 } else if (best_type == NULL) {
7742 best_type = decl_type;
7746 if (best_type != NULL) {
7747 expected_type = best_type;
7751 error = semantic_assign(expected_type, arg_expr);
7752 argument->expression = create_implicit_cast(argument->expression,
7755 if (error != ASSIGN_SUCCESS) {
7756 /* report exact scope in error messages (like "in argument 3") */
7758 snprintf(buf, sizeof(buf), "call argument %u", pos);
7759 report_assign_error(error, expected_type, arg_expr, buf,
7760 &arg_expr->base.source_position);
7761 } else if (warning.traditional || warning.conversion) {
7762 type_t *const promoted_type = get_default_promoted_type(arg_type);
7763 if (!types_compatible(expected_type_skip, promoted_type) &&
7764 !types_compatible(expected_type_skip, type_void_ptr) &&
7765 !types_compatible(type_void_ptr, promoted_type)) {
7766 /* Deliberately show the skipped types in this warning */
7767 warningf(&arg_expr->base.source_position,
7768 "passing call argument %u as '%T' rather than '%T' due to prototype",
7769 pos, expected_type_skip, promoted_type);
7775 * Parse a call expression, ie. expression '( ... )'.
7777 * @param expression the function address
7779 static expression_t *parse_call_expression(expression_t *expression)
7781 expression_t *result = allocate_expression_zero(EXPR_CALL);
7782 call_expression_t *call = &result->call;
7783 call->function = expression;
7785 type_t *const orig_type = expression->base.type;
7786 type_t *const type = skip_typeref(orig_type);
7788 function_type_t *function_type = NULL;
7789 if (is_type_pointer(type)) {
7790 type_t *const to_type = skip_typeref(type->pointer.points_to);
7792 if (is_type_function(to_type)) {
7793 function_type = &to_type->function;
7794 call->base.type = function_type->return_type;
7798 if (function_type == NULL && is_type_valid(type)) {
7799 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7802 /* parse arguments */
7804 add_anchor_token(')');
7805 add_anchor_token(',');
7807 if (token.type != ')') {
7808 call_argument_t *last_argument = NULL;
7811 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7813 argument->expression = parse_assignment_expression();
7814 if (last_argument == NULL) {
7815 call->arguments = argument;
7817 last_argument->next = argument;
7819 last_argument = argument;
7821 if (token.type != ',')
7826 rem_anchor_token(',');
7827 rem_anchor_token(')');
7830 if (function_type == NULL)
7833 function_parameter_t *parameter = function_type->parameters;
7834 call_argument_t *argument = call->arguments;
7835 if (!function_type->unspecified_parameters) {
7836 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7837 parameter = parameter->next, argument = argument->next) {
7838 check_call_argument(parameter, argument, ++pos);
7841 if (parameter != NULL) {
7842 errorf(HERE, "too few arguments to function '%E'", expression);
7843 } else if (argument != NULL && !function_type->variadic) {
7844 errorf(HERE, "too many arguments to function '%E'", expression);
7848 /* do default promotion */
7849 for (; argument != NULL; argument = argument->next) {
7850 type_t *type = argument->expression->base.type;
7852 type = get_default_promoted_type(type);
7854 argument->expression
7855 = create_implicit_cast(argument->expression, type);
7858 check_format(&result->call);
7860 if (warning.aggregate_return &&
7861 is_type_compound(skip_typeref(function_type->return_type))) {
7862 warningf(&result->base.source_position,
7863 "function call has aggregate value");
7870 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7872 static bool same_compound_type(const type_t *type1, const type_t *type2)
7875 is_type_compound(type1) &&
7876 type1->kind == type2->kind &&
7877 type1->compound.compound == type2->compound.compound;
7880 static expression_t const *get_reference_address(expression_t const *expr)
7882 bool regular_take_address = true;
7884 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7885 expr = expr->unary.value;
7887 regular_take_address = false;
7890 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7893 expr = expr->unary.value;
7896 if (expr->kind != EXPR_REFERENCE)
7899 /* special case for functions which are automatically converted to a
7900 * pointer to function without an extra TAKE_ADDRESS operation */
7901 if (!regular_take_address &&
7902 expr->reference.entity->kind != ENTITY_FUNCTION) {
7909 static void warn_reference_address_as_bool(expression_t const* expr)
7911 if (!warning.address)
7914 expr = get_reference_address(expr);
7916 warningf(&expr->base.source_position,
7917 "the address of '%Y' will always evaluate as 'true'",
7918 expr->reference.entity->base.symbol);
7922 static void semantic_condition(expression_t const *const expr,
7923 char const *const context)
7925 type_t *const type = skip_typeref(expr->base.type);
7926 if (is_type_scalar(type)) {
7927 warn_reference_address_as_bool(expr);
7928 } else if (is_type_valid(type)) {
7929 errorf(&expr->base.source_position,
7930 "%s must have scalar type", context);
7935 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7937 * @param expression the conditional expression
7939 static expression_t *parse_conditional_expression(expression_t *expression)
7941 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7943 conditional_expression_t *conditional = &result->conditional;
7944 conditional->condition = expression;
7947 add_anchor_token(':');
7949 /* §6.5.15:2 The first operand shall have scalar type. */
7950 semantic_condition(expression, "condition of conditional operator");
7952 expression_t *true_expression = expression;
7953 bool gnu_cond = false;
7954 if (GNU_MODE && token.type == ':') {
7957 true_expression = parse_expression();
7959 rem_anchor_token(':');
7961 expression_t *false_expression =
7962 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7964 type_t *const orig_true_type = true_expression->base.type;
7965 type_t *const orig_false_type = false_expression->base.type;
7966 type_t *const true_type = skip_typeref(orig_true_type);
7967 type_t *const false_type = skip_typeref(orig_false_type);
7970 type_t *result_type;
7971 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7972 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7973 /* ISO/IEC 14882:1998(E) §5.16:2 */
7974 if (true_expression->kind == EXPR_UNARY_THROW) {
7975 result_type = false_type;
7976 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7977 result_type = true_type;
7979 if (warning.other && (
7980 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7981 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7983 warningf(&conditional->base.source_position,
7984 "ISO C forbids conditional expression with only one void side");
7986 result_type = type_void;
7988 } else if (is_type_arithmetic(true_type)
7989 && is_type_arithmetic(false_type)) {
7990 result_type = semantic_arithmetic(true_type, false_type);
7992 true_expression = create_implicit_cast(true_expression, result_type);
7993 false_expression = create_implicit_cast(false_expression, result_type);
7995 conditional->true_expression = true_expression;
7996 conditional->false_expression = false_expression;
7997 conditional->base.type = result_type;
7998 } else if (same_compound_type(true_type, false_type)) {
7999 /* just take 1 of the 2 types */
8000 result_type = true_type;
8001 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8002 type_t *pointer_type;
8004 expression_t *other_expression;
8005 if (is_type_pointer(true_type) &&
8006 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8007 pointer_type = true_type;
8008 other_type = false_type;
8009 other_expression = false_expression;
8011 pointer_type = false_type;
8012 other_type = true_type;
8013 other_expression = true_expression;
8016 if (is_null_pointer_constant(other_expression)) {
8017 result_type = pointer_type;
8018 } else if (is_type_pointer(other_type)) {
8019 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8020 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8023 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8024 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8026 } else if (types_compatible(get_unqualified_type(to1),
8027 get_unqualified_type(to2))) {
8030 if (warning.other) {
8031 warningf(&conditional->base.source_position,
8032 "pointer types '%T' and '%T' in conditional expression are incompatible",
8033 true_type, false_type);
8038 type_t *const type =
8039 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8040 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8041 } else if (is_type_integer(other_type)) {
8042 if (warning.other) {
8043 warningf(&conditional->base.source_position,
8044 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8046 result_type = pointer_type;
8048 if (is_type_valid(other_type)) {
8049 type_error_incompatible("while parsing conditional",
8050 &expression->base.source_position, true_type, false_type);
8052 result_type = type_error_type;
8055 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8056 type_error_incompatible("while parsing conditional",
8057 &conditional->base.source_position, true_type,
8060 result_type = type_error_type;
8063 conditional->true_expression
8064 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8065 conditional->false_expression
8066 = create_implicit_cast(false_expression, result_type);
8067 conditional->base.type = result_type;
8070 return create_invalid_expression();
8074 * Parse an extension expression.
8076 static expression_t *parse_extension(void)
8078 eat(T___extension__);
8080 bool old_gcc_extension = in_gcc_extension;
8081 in_gcc_extension = true;
8082 expression_t *expression = parse_sub_expression(PREC_UNARY);
8083 in_gcc_extension = old_gcc_extension;
8088 * Parse a __builtin_classify_type() expression.
8090 static expression_t *parse_builtin_classify_type(void)
8092 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8093 result->base.type = type_int;
8095 eat(T___builtin_classify_type);
8098 add_anchor_token(')');
8099 expression_t *expression = parse_expression();
8100 rem_anchor_token(')');
8102 result->classify_type.type_expression = expression;
8106 return create_invalid_expression();
8110 * Parse a delete expression
8111 * ISO/IEC 14882:1998(E) §5.3.5
8113 static expression_t *parse_delete(void)
8115 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8116 result->base.type = type_void;
8120 if (token.type == '[') {
8122 result->kind = EXPR_UNARY_DELETE_ARRAY;
8127 expression_t *const value = parse_sub_expression(PREC_CAST);
8128 result->unary.value = value;
8130 type_t *const type = skip_typeref(value->base.type);
8131 if (!is_type_pointer(type)) {
8132 errorf(&value->base.source_position,
8133 "operand of delete must have pointer type");
8134 } else if (warning.other &&
8135 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8136 warningf(&value->base.source_position,
8137 "deleting 'void*' is undefined");
8144 * Parse a throw expression
8145 * ISO/IEC 14882:1998(E) §15:1
8147 static expression_t *parse_throw(void)
8149 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8150 result->base.type = type_void;
8154 expression_t *value = NULL;
8155 switch (token.type) {
8157 value = parse_assignment_expression();
8158 /* ISO/IEC 14882:1998(E) §15.1:3 */
8159 type_t *const orig_type = value->base.type;
8160 type_t *const type = skip_typeref(orig_type);
8161 if (is_type_incomplete(type)) {
8162 errorf(&value->base.source_position,
8163 "cannot throw object of incomplete type '%T'", orig_type);
8164 } else if (is_type_pointer(type)) {
8165 type_t *const points_to = skip_typeref(type->pointer.points_to);
8166 if (is_type_incomplete(points_to) &&
8167 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8168 errorf(&value->base.source_position,
8169 "cannot throw pointer to incomplete type '%T'", orig_type);
8177 result->unary.value = value;
8182 static bool check_pointer_arithmetic(const source_position_t *source_position,
8183 type_t *pointer_type,
8184 type_t *orig_pointer_type)
8186 type_t *points_to = pointer_type->pointer.points_to;
8187 points_to = skip_typeref(points_to);
8189 if (is_type_incomplete(points_to)) {
8190 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8191 errorf(source_position,
8192 "arithmetic with pointer to incomplete type '%T' not allowed",
8195 } else if (warning.pointer_arith) {
8196 warningf(source_position,
8197 "pointer of type '%T' used in arithmetic",
8200 } else if (is_type_function(points_to)) {
8202 errorf(source_position,
8203 "arithmetic with pointer to function type '%T' not allowed",
8206 } else if (warning.pointer_arith) {
8207 warningf(source_position,
8208 "pointer to a function '%T' used in arithmetic",
8215 static bool is_lvalue(const expression_t *expression)
8217 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8218 switch (expression->kind) {
8219 case EXPR_REFERENCE:
8220 case EXPR_ARRAY_ACCESS:
8222 case EXPR_UNARY_DEREFERENCE:
8226 /* Claim it is an lvalue, if the type is invalid. There was a parse
8227 * error before, which maybe prevented properly recognizing it as
8229 return !is_type_valid(skip_typeref(expression->base.type));
8233 static void semantic_incdec(unary_expression_t *expression)
8235 type_t *const orig_type = expression->value->base.type;
8236 type_t *const type = skip_typeref(orig_type);
8237 if (is_type_pointer(type)) {
8238 if (!check_pointer_arithmetic(&expression->base.source_position,
8242 } else if (!is_type_real(type) && is_type_valid(type)) {
8243 /* TODO: improve error message */
8244 errorf(&expression->base.source_position,
8245 "operation needs an arithmetic or pointer type");
8248 if (!is_lvalue(expression->value)) {
8249 /* TODO: improve error message */
8250 errorf(&expression->base.source_position, "lvalue required as operand");
8252 expression->base.type = orig_type;
8255 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8257 type_t *const orig_type = expression->value->base.type;
8258 type_t *const type = skip_typeref(orig_type);
8259 if (!is_type_arithmetic(type)) {
8260 if (is_type_valid(type)) {
8261 /* TODO: improve error message */
8262 errorf(&expression->base.source_position,
8263 "operation needs an arithmetic type");
8268 expression->base.type = orig_type;
8271 static void semantic_unexpr_plus(unary_expression_t *expression)
8273 semantic_unexpr_arithmetic(expression);
8274 if (warning.traditional)
8275 warningf(&expression->base.source_position,
8276 "traditional C rejects the unary plus operator");
8279 static void semantic_not(unary_expression_t *expression)
8281 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8282 semantic_condition(expression->value, "operand of !");
8283 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8286 static void semantic_unexpr_integer(unary_expression_t *expression)
8288 type_t *const orig_type = expression->value->base.type;
8289 type_t *const type = skip_typeref(orig_type);
8290 if (!is_type_integer(type)) {
8291 if (is_type_valid(type)) {
8292 errorf(&expression->base.source_position,
8293 "operand of ~ must be of integer type");
8298 expression->base.type = orig_type;
8301 static void semantic_dereference(unary_expression_t *expression)
8303 type_t *const orig_type = expression->value->base.type;
8304 type_t *const type = skip_typeref(orig_type);
8305 if (!is_type_pointer(type)) {
8306 if (is_type_valid(type)) {
8307 errorf(&expression->base.source_position,
8308 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8313 type_t *result_type = type->pointer.points_to;
8314 result_type = automatic_type_conversion(result_type);
8315 expression->base.type = result_type;
8319 * Record that an address is taken (expression represents an lvalue).
8321 * @param expression the expression
8322 * @param may_be_register if true, the expression might be an register
8324 static void set_address_taken(expression_t *expression, bool may_be_register)
8326 if (expression->kind != EXPR_REFERENCE)
8329 entity_t *const entity = expression->reference.entity;
8331 if (entity->kind != ENTITY_VARIABLE)
8334 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8335 && !may_be_register) {
8336 errorf(&expression->base.source_position,
8337 "address of register variable '%Y' requested",
8338 entity->base.symbol);
8341 entity->variable.address_taken = true;
8345 * Check the semantic of the address taken expression.
8347 static void semantic_take_addr(unary_expression_t *expression)
8349 expression_t *value = expression->value;
8350 value->base.type = revert_automatic_type_conversion(value);
8352 type_t *orig_type = value->base.type;
8353 type_t *type = skip_typeref(orig_type);
8354 if (!is_type_valid(type))
8358 if (!is_lvalue(value)) {
8359 errorf(&expression->base.source_position, "'&' requires an lvalue");
8361 if (type->kind == TYPE_BITFIELD) {
8362 errorf(&expression->base.source_position,
8363 "'&' not allowed on object with bitfield type '%T'",
8367 set_address_taken(value, false);
8369 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8372 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8373 static expression_t *parse_##unexpression_type(void) \
8375 expression_t *unary_expression \
8376 = allocate_expression_zero(unexpression_type); \
8378 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8380 sfunc(&unary_expression->unary); \
8382 return unary_expression; \
8385 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8386 semantic_unexpr_arithmetic)
8387 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8388 semantic_unexpr_plus)
8389 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8391 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8392 semantic_dereference)
8393 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8395 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8396 semantic_unexpr_integer)
8397 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8399 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8402 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8404 static expression_t *parse_##unexpression_type(expression_t *left) \
8406 expression_t *unary_expression \
8407 = allocate_expression_zero(unexpression_type); \
8409 unary_expression->unary.value = left; \
8411 sfunc(&unary_expression->unary); \
8413 return unary_expression; \
8416 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8417 EXPR_UNARY_POSTFIX_INCREMENT,
8419 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8420 EXPR_UNARY_POSTFIX_DECREMENT,
8423 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8425 /* TODO: handle complex + imaginary types */
8427 type_left = get_unqualified_type(type_left);
8428 type_right = get_unqualified_type(type_right);
8430 /* § 6.3.1.8 Usual arithmetic conversions */
8431 if (type_left == type_long_double || type_right == type_long_double) {
8432 return type_long_double;
8433 } else if (type_left == type_double || type_right == type_double) {
8435 } else if (type_left == type_float || type_right == type_float) {
8439 type_left = promote_integer(type_left);
8440 type_right = promote_integer(type_right);
8442 if (type_left == type_right)
8445 bool const signed_left = is_type_signed(type_left);
8446 bool const signed_right = is_type_signed(type_right);
8447 int const rank_left = get_rank(type_left);
8448 int const rank_right = get_rank(type_right);
8450 if (signed_left == signed_right)
8451 return rank_left >= rank_right ? type_left : type_right;
8460 u_rank = rank_right;
8461 u_type = type_right;
8463 s_rank = rank_right;
8464 s_type = type_right;
8469 if (u_rank >= s_rank)
8472 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8474 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8475 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8479 case ATOMIC_TYPE_INT: return type_unsigned_int;
8480 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8481 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8483 default: panic("invalid atomic type");
8488 * Check the semantic restrictions for a binary expression.
8490 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8492 expression_t *const left = expression->left;
8493 expression_t *const right = expression->right;
8494 type_t *const orig_type_left = left->base.type;
8495 type_t *const orig_type_right = right->base.type;
8496 type_t *const type_left = skip_typeref(orig_type_left);
8497 type_t *const type_right = skip_typeref(orig_type_right);
8499 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8500 /* TODO: improve error message */
8501 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8502 errorf(&expression->base.source_position,
8503 "operation needs arithmetic types");
8508 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8509 expression->left = create_implicit_cast(left, arithmetic_type);
8510 expression->right = create_implicit_cast(right, arithmetic_type);
8511 expression->base.type = arithmetic_type;
8514 static void warn_div_by_zero(binary_expression_t const *const expression)
8516 if (!warning.div_by_zero ||
8517 !is_type_integer(expression->base.type))
8520 expression_t const *const right = expression->right;
8521 /* The type of the right operand can be different for /= */
8522 if (is_type_integer(right->base.type) &&
8523 is_constant_expression(right) &&
8524 fold_constant(right) == 0) {
8525 warningf(&expression->base.source_position, "division by zero");
8530 * Check the semantic restrictions for a div/mod expression.
8532 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8533 semantic_binexpr_arithmetic(expression);
8534 warn_div_by_zero(expression);
8537 static void semantic_shift_op(binary_expression_t *expression)
8539 expression_t *const left = expression->left;
8540 expression_t *const right = expression->right;
8541 type_t *const orig_type_left = left->base.type;
8542 type_t *const orig_type_right = right->base.type;
8543 type_t * type_left = skip_typeref(orig_type_left);
8544 type_t * type_right = skip_typeref(orig_type_right);
8546 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8547 /* TODO: improve error message */
8548 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8549 errorf(&expression->base.source_position,
8550 "operands of shift operation must have integer types");
8555 type_left = promote_integer(type_left);
8556 type_right = promote_integer(type_right);
8558 expression->left = create_implicit_cast(left, type_left);
8559 expression->right = create_implicit_cast(right, type_right);
8560 expression->base.type = type_left;
8563 static void semantic_add(binary_expression_t *expression)
8565 expression_t *const left = expression->left;
8566 expression_t *const right = expression->right;
8567 type_t *const orig_type_left = left->base.type;
8568 type_t *const orig_type_right = right->base.type;
8569 type_t *const type_left = skip_typeref(orig_type_left);
8570 type_t *const type_right = skip_typeref(orig_type_right);
8573 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8574 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8575 expression->left = create_implicit_cast(left, arithmetic_type);
8576 expression->right = create_implicit_cast(right, arithmetic_type);
8577 expression->base.type = arithmetic_type;
8579 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8580 check_pointer_arithmetic(&expression->base.source_position,
8581 type_left, orig_type_left);
8582 expression->base.type = type_left;
8583 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8584 check_pointer_arithmetic(&expression->base.source_position,
8585 type_right, orig_type_right);
8586 expression->base.type = type_right;
8587 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8588 errorf(&expression->base.source_position,
8589 "invalid operands to binary + ('%T', '%T')",
8590 orig_type_left, orig_type_right);
8594 static void semantic_sub(binary_expression_t *expression)
8596 expression_t *const left = expression->left;
8597 expression_t *const right = expression->right;
8598 type_t *const orig_type_left = left->base.type;
8599 type_t *const orig_type_right = right->base.type;
8600 type_t *const type_left = skip_typeref(orig_type_left);
8601 type_t *const type_right = skip_typeref(orig_type_right);
8602 source_position_t const *const pos = &expression->base.source_position;
8605 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8606 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8607 expression->left = create_implicit_cast(left, arithmetic_type);
8608 expression->right = create_implicit_cast(right, arithmetic_type);
8609 expression->base.type = arithmetic_type;
8611 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8612 check_pointer_arithmetic(&expression->base.source_position,
8613 type_left, orig_type_left);
8614 expression->base.type = type_left;
8615 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8616 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8617 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8618 if (!types_compatible(unqual_left, unqual_right)) {
8620 "subtracting pointers to incompatible types '%T' and '%T'",
8621 orig_type_left, orig_type_right);
8622 } else if (!is_type_object(unqual_left)) {
8623 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8624 errorf(pos, "subtracting pointers to non-object types '%T'",
8626 } else if (warning.other) {
8627 warningf(pos, "subtracting pointers to void");
8630 expression->base.type = type_ptrdiff_t;
8631 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8632 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8633 orig_type_left, orig_type_right);
8637 static void warn_string_literal_address(expression_t const* expr)
8639 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8640 expr = expr->unary.value;
8641 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8643 expr = expr->unary.value;
8646 if (expr->kind == EXPR_STRING_LITERAL ||
8647 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8648 warningf(&expr->base.source_position,
8649 "comparison with string literal results in unspecified behaviour");
8654 * Check the semantics of comparison expressions.
8656 * @param expression The expression to check.
8658 static void semantic_comparison(binary_expression_t *expression)
8660 expression_t *left = expression->left;
8661 expression_t *right = expression->right;
8663 if (warning.address) {
8664 warn_string_literal_address(left);
8665 warn_string_literal_address(right);
8667 expression_t const* const func_left = get_reference_address(left);
8668 if (func_left != NULL && is_null_pointer_constant(right)) {
8669 warningf(&expression->base.source_position,
8670 "the address of '%Y' will never be NULL",
8671 func_left->reference.entity->base.symbol);
8674 expression_t const* const func_right = get_reference_address(right);
8675 if (func_right != NULL && is_null_pointer_constant(right)) {
8676 warningf(&expression->base.source_position,
8677 "the address of '%Y' will never be NULL",
8678 func_right->reference.entity->base.symbol);
8682 type_t *orig_type_left = left->base.type;
8683 type_t *orig_type_right = right->base.type;
8684 type_t *type_left = skip_typeref(orig_type_left);
8685 type_t *type_right = skip_typeref(orig_type_right);
8687 /* TODO non-arithmetic types */
8688 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8689 /* test for signed vs unsigned compares */
8690 if (warning.sign_compare &&
8691 (expression->base.kind != EXPR_BINARY_EQUAL &&
8692 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8693 (is_type_signed(type_left) != is_type_signed(type_right))) {
8695 /* check if 1 of the operands is a constant, in this case we just
8696 * check wether we can safely represent the resulting constant in
8697 * the type of the other operand. */
8698 expression_t *const_expr = NULL;
8699 expression_t *other_expr = NULL;
8701 if (is_constant_expression(left)) {
8704 } else if (is_constant_expression(right)) {
8709 if (const_expr != NULL) {
8710 type_t *other_type = skip_typeref(other_expr->base.type);
8711 long val = fold_constant(const_expr);
8712 /* TODO: check if val can be represented by other_type */
8716 warningf(&expression->base.source_position,
8717 "comparison between signed and unsigned");
8719 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8720 expression->left = create_implicit_cast(left, arithmetic_type);
8721 expression->right = create_implicit_cast(right, arithmetic_type);
8722 expression->base.type = arithmetic_type;
8723 if (warning.float_equal &&
8724 (expression->base.kind == EXPR_BINARY_EQUAL ||
8725 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8726 is_type_float(arithmetic_type)) {
8727 warningf(&expression->base.source_position,
8728 "comparing floating point with == or != is unsafe");
8730 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8731 /* TODO check compatibility */
8732 } else if (is_type_pointer(type_left)) {
8733 expression->right = create_implicit_cast(right, type_left);
8734 } else if (is_type_pointer(type_right)) {
8735 expression->left = create_implicit_cast(left, type_right);
8736 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8737 type_error_incompatible("invalid operands in comparison",
8738 &expression->base.source_position,
8739 type_left, type_right);
8741 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8745 * Checks if a compound type has constant fields.
8747 static bool has_const_fields(const compound_type_t *type)
8749 compound_t *compound = type->compound;
8750 entity_t *entry = compound->members.entities;
8752 for (; entry != NULL; entry = entry->base.next) {
8753 if (!is_declaration(entry))
8756 const type_t *decl_type = skip_typeref(entry->declaration.type);
8757 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8764 static bool is_valid_assignment_lhs(expression_t const* const left)
8766 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8767 type_t *const type_left = skip_typeref(orig_type_left);
8769 if (!is_lvalue(left)) {
8770 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8775 if (is_type_array(type_left)) {
8776 errorf(HERE, "cannot assign to arrays ('%E')", left);
8779 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8780 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8784 if (is_type_incomplete(type_left)) {
8785 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8786 left, orig_type_left);
8789 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8790 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8791 left, orig_type_left);
8798 static void semantic_arithmetic_assign(binary_expression_t *expression)
8800 expression_t *left = expression->left;
8801 expression_t *right = expression->right;
8802 type_t *orig_type_left = left->base.type;
8803 type_t *orig_type_right = right->base.type;
8805 if (!is_valid_assignment_lhs(left))
8808 type_t *type_left = skip_typeref(orig_type_left);
8809 type_t *type_right = skip_typeref(orig_type_right);
8811 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8812 /* TODO: improve error message */
8813 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8814 errorf(&expression->base.source_position,
8815 "operation needs arithmetic types");
8820 /* combined instructions are tricky. We can't create an implicit cast on
8821 * the left side, because we need the uncasted form for the store.
8822 * The ast2firm pass has to know that left_type must be right_type
8823 * for the arithmetic operation and create a cast by itself */
8824 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8825 expression->right = create_implicit_cast(right, arithmetic_type);
8826 expression->base.type = type_left;
8829 static void semantic_divmod_assign(binary_expression_t *expression)
8831 semantic_arithmetic_assign(expression);
8832 warn_div_by_zero(expression);
8835 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8837 expression_t *const left = expression->left;
8838 expression_t *const right = expression->right;
8839 type_t *const orig_type_left = left->base.type;
8840 type_t *const orig_type_right = right->base.type;
8841 type_t *const type_left = skip_typeref(orig_type_left);
8842 type_t *const type_right = skip_typeref(orig_type_right);
8844 if (!is_valid_assignment_lhs(left))
8847 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8848 /* combined instructions are tricky. We can't create an implicit cast on
8849 * the left side, because we need the uncasted form for the store.
8850 * The ast2firm pass has to know that left_type must be right_type
8851 * for the arithmetic operation and create a cast by itself */
8852 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8853 expression->right = create_implicit_cast(right, arithmetic_type);
8854 expression->base.type = type_left;
8855 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8856 check_pointer_arithmetic(&expression->base.source_position,
8857 type_left, orig_type_left);
8858 expression->base.type = type_left;
8859 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8860 errorf(&expression->base.source_position,
8861 "incompatible types '%T' and '%T' in assignment",
8862 orig_type_left, orig_type_right);
8867 * Check the semantic restrictions of a logical expression.
8869 static void semantic_logical_op(binary_expression_t *expression)
8871 /* §6.5.13:2 Each of the operands shall have scalar type.
8872 * §6.5.14:2 Each of the operands shall have scalar type. */
8873 semantic_condition(expression->left, "left operand of logical operator");
8874 semantic_condition(expression->right, "right operand of logical operator");
8875 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8879 * Check the semantic restrictions of a binary assign expression.
8881 static void semantic_binexpr_assign(binary_expression_t *expression)
8883 expression_t *left = expression->left;
8884 type_t *orig_type_left = left->base.type;
8886 if (!is_valid_assignment_lhs(left))
8889 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8890 report_assign_error(error, orig_type_left, expression->right,
8891 "assignment", &left->base.source_position);
8892 expression->right = create_implicit_cast(expression->right, orig_type_left);
8893 expression->base.type = orig_type_left;
8897 * Determine if the outermost operation (or parts thereof) of the given
8898 * expression has no effect in order to generate a warning about this fact.
8899 * Therefore in some cases this only examines some of the operands of the
8900 * expression (see comments in the function and examples below).
8902 * f() + 23; // warning, because + has no effect
8903 * x || f(); // no warning, because x controls execution of f()
8904 * x ? y : f(); // warning, because y has no effect
8905 * (void)x; // no warning to be able to suppress the warning
8906 * This function can NOT be used for an "expression has definitely no effect"-
8908 static bool expression_has_effect(const expression_t *const expr)
8910 switch (expr->kind) {
8911 case EXPR_UNKNOWN: break;
8912 case EXPR_INVALID: return true; /* do NOT warn */
8913 case EXPR_REFERENCE: return false;
8914 case EXPR_REFERENCE_ENUM_VALUE: return false;
8915 /* suppress the warning for microsoft __noop operations */
8916 case EXPR_CONST: return expr->conste.is_ms_noop;
8917 case EXPR_CHARACTER_CONSTANT: return false;
8918 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8919 case EXPR_STRING_LITERAL: return false;
8920 case EXPR_WIDE_STRING_LITERAL: return false;
8921 case EXPR_LABEL_ADDRESS: return false;
8924 const call_expression_t *const call = &expr->call;
8925 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8928 switch (call->function->builtin_symbol.symbol->ID) {
8929 case T___builtin_va_end: return true;
8930 default: return false;
8934 /* Generate the warning if either the left or right hand side of a
8935 * conditional expression has no effect */
8936 case EXPR_CONDITIONAL: {
8937 const conditional_expression_t *const cond = &expr->conditional;
8939 expression_has_effect(cond->true_expression) &&
8940 expression_has_effect(cond->false_expression);
8943 case EXPR_SELECT: return false;
8944 case EXPR_ARRAY_ACCESS: return false;
8945 case EXPR_SIZEOF: return false;
8946 case EXPR_CLASSIFY_TYPE: return false;
8947 case EXPR_ALIGNOF: return false;
8949 case EXPR_FUNCNAME: return false;
8950 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8951 case EXPR_BUILTIN_CONSTANT_P: return false;
8952 case EXPR_BUILTIN_PREFETCH: return true;
8953 case EXPR_OFFSETOF: return false;
8954 case EXPR_VA_START: return true;
8955 case EXPR_VA_ARG: return true;
8956 case EXPR_STATEMENT: return true; // TODO
8957 case EXPR_COMPOUND_LITERAL: return false;
8959 case EXPR_UNARY_NEGATE: return false;
8960 case EXPR_UNARY_PLUS: return false;
8961 case EXPR_UNARY_BITWISE_NEGATE: return false;
8962 case EXPR_UNARY_NOT: return false;
8963 case EXPR_UNARY_DEREFERENCE: return false;
8964 case EXPR_UNARY_TAKE_ADDRESS: return false;
8965 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8966 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8967 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8968 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8970 /* Treat void casts as if they have an effect in order to being able to
8971 * suppress the warning */
8972 case EXPR_UNARY_CAST: {
8973 type_t *const type = skip_typeref(expr->base.type);
8974 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8977 case EXPR_UNARY_CAST_IMPLICIT: return true;
8978 case EXPR_UNARY_ASSUME: return true;
8979 case EXPR_UNARY_DELETE: return true;
8980 case EXPR_UNARY_DELETE_ARRAY: return true;
8981 case EXPR_UNARY_THROW: return true;
8983 case EXPR_BINARY_ADD: return false;
8984 case EXPR_BINARY_SUB: return false;
8985 case EXPR_BINARY_MUL: return false;
8986 case EXPR_BINARY_DIV: return false;
8987 case EXPR_BINARY_MOD: return false;
8988 case EXPR_BINARY_EQUAL: return false;
8989 case EXPR_BINARY_NOTEQUAL: return false;
8990 case EXPR_BINARY_LESS: return false;
8991 case EXPR_BINARY_LESSEQUAL: return false;
8992 case EXPR_BINARY_GREATER: return false;
8993 case EXPR_BINARY_GREATEREQUAL: return false;
8994 case EXPR_BINARY_BITWISE_AND: return false;
8995 case EXPR_BINARY_BITWISE_OR: return false;
8996 case EXPR_BINARY_BITWISE_XOR: return false;
8997 case EXPR_BINARY_SHIFTLEFT: return false;
8998 case EXPR_BINARY_SHIFTRIGHT: return false;
8999 case EXPR_BINARY_ASSIGN: return true;
9000 case EXPR_BINARY_MUL_ASSIGN: return true;
9001 case EXPR_BINARY_DIV_ASSIGN: return true;
9002 case EXPR_BINARY_MOD_ASSIGN: return true;
9003 case EXPR_BINARY_ADD_ASSIGN: return true;
9004 case EXPR_BINARY_SUB_ASSIGN: return true;
9005 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9006 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9007 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9008 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9009 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9011 /* Only examine the right hand side of && and ||, because the left hand
9012 * side already has the effect of controlling the execution of the right
9014 case EXPR_BINARY_LOGICAL_AND:
9015 case EXPR_BINARY_LOGICAL_OR:
9016 /* Only examine the right hand side of a comma expression, because the left
9017 * hand side has a separate warning */
9018 case EXPR_BINARY_COMMA:
9019 return expression_has_effect(expr->binary.right);
9021 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9022 case EXPR_BINARY_ISGREATER: return false;
9023 case EXPR_BINARY_ISGREATEREQUAL: return false;
9024 case EXPR_BINARY_ISLESS: return false;
9025 case EXPR_BINARY_ISLESSEQUAL: return false;
9026 case EXPR_BINARY_ISLESSGREATER: return false;
9027 case EXPR_BINARY_ISUNORDERED: return false;
9030 internal_errorf(HERE, "unexpected expression");
9033 static void semantic_comma(binary_expression_t *expression)
9035 if (warning.unused_value) {
9036 const expression_t *const left = expression->left;
9037 if (!expression_has_effect(left)) {
9038 warningf(&left->base.source_position,
9039 "left-hand operand of comma expression has no effect");
9042 expression->base.type = expression->right->base.type;
9046 * @param prec_r precedence of the right operand
9048 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9049 static expression_t *parse_##binexpression_type(expression_t *left) \
9051 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9052 binexpr->binary.left = left; \
9055 expression_t *right = parse_sub_expression(prec_r); \
9057 binexpr->binary.right = right; \
9058 sfunc(&binexpr->binary); \
9063 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9064 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9065 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9066 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9067 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9068 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9069 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9070 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9071 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9072 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9073 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9074 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9075 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9076 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9077 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9078 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9079 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9080 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9081 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9082 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9083 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9084 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9085 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9086 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9087 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9088 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9089 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9090 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9091 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9092 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9095 static expression_t *parse_sub_expression(precedence_t precedence)
9097 if (token.type < 0) {
9098 return expected_expression_error();
9101 expression_parser_function_t *parser
9102 = &expression_parsers[token.type];
9103 source_position_t source_position = token.source_position;
9106 if (parser->parser != NULL) {
9107 left = parser->parser();
9109 left = parse_primary_expression();
9111 assert(left != NULL);
9112 left->base.source_position = source_position;
9115 if (token.type < 0) {
9116 return expected_expression_error();
9119 parser = &expression_parsers[token.type];
9120 if (parser->infix_parser == NULL)
9122 if (parser->infix_precedence < precedence)
9125 left = parser->infix_parser(left);
9127 assert(left != NULL);
9128 assert(left->kind != EXPR_UNKNOWN);
9129 left->base.source_position = source_position;
9136 * Parse an expression.
9138 static expression_t *parse_expression(void)
9140 return parse_sub_expression(PREC_EXPRESSION);
9144 * Register a parser for a prefix-like operator.
9146 * @param parser the parser function
9147 * @param token_type the token type of the prefix token
9149 static void register_expression_parser(parse_expression_function parser,
9152 expression_parser_function_t *entry = &expression_parsers[token_type];
9154 if (entry->parser != NULL) {
9155 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9156 panic("trying to register multiple expression parsers for a token");
9158 entry->parser = parser;
9162 * Register a parser for an infix operator with given precedence.
9164 * @param parser the parser function
9165 * @param token_type the token type of the infix operator
9166 * @param precedence the precedence of the operator
9168 static void register_infix_parser(parse_expression_infix_function parser,
9169 int token_type, unsigned precedence)
9171 expression_parser_function_t *entry = &expression_parsers[token_type];
9173 if (entry->infix_parser != NULL) {
9174 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9175 panic("trying to register multiple infix expression parsers for a "
9178 entry->infix_parser = parser;
9179 entry->infix_precedence = precedence;
9183 * Initialize the expression parsers.
9185 static void init_expression_parsers(void)
9187 memset(&expression_parsers, 0, sizeof(expression_parsers));
9189 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9190 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9191 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9192 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9193 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9194 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9195 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9196 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9197 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9198 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9199 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9200 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9201 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9202 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9203 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9204 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9205 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9206 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9207 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9208 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9209 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9210 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9211 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9212 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9213 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9214 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9215 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9216 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9217 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9218 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9219 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9220 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9221 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9222 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9223 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9224 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9225 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9227 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9228 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9229 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9230 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9231 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9232 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9233 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9234 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9235 register_expression_parser(parse_sizeof, T_sizeof);
9236 register_expression_parser(parse_alignof, T___alignof__);
9237 register_expression_parser(parse_extension, T___extension__);
9238 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9239 register_expression_parser(parse_delete, T_delete);
9240 register_expression_parser(parse_throw, T_throw);
9244 * Parse a asm statement arguments specification.
9246 static asm_argument_t *parse_asm_arguments(bool is_out)
9248 asm_argument_t *result = NULL;
9249 asm_argument_t **anchor = &result;
9251 while (token.type == T_STRING_LITERAL || token.type == '[') {
9252 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9253 memset(argument, 0, sizeof(argument[0]));
9255 if (token.type == '[') {
9257 if (token.type != T_IDENTIFIER) {
9258 parse_error_expected("while parsing asm argument",
9259 T_IDENTIFIER, NULL);
9262 argument->symbol = token.v.symbol;
9267 argument->constraints = parse_string_literals();
9269 add_anchor_token(')');
9270 expression_t *expression = parse_expression();
9271 rem_anchor_token(')');
9273 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9274 * change size or type representation (e.g. int -> long is ok, but
9275 * int -> float is not) */
9276 if (expression->kind == EXPR_UNARY_CAST) {
9277 type_t *const type = expression->base.type;
9278 type_kind_t const kind = type->kind;
9279 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9282 if (kind == TYPE_ATOMIC) {
9283 atomic_type_kind_t const akind = type->atomic.akind;
9284 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9285 size = get_atomic_type_size(akind);
9287 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9288 size = get_atomic_type_size(get_intptr_kind());
9292 expression_t *const value = expression->unary.value;
9293 type_t *const value_type = value->base.type;
9294 type_kind_t const value_kind = value_type->kind;
9296 unsigned value_flags;
9297 unsigned value_size;
9298 if (value_kind == TYPE_ATOMIC) {
9299 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9300 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9301 value_size = get_atomic_type_size(value_akind);
9302 } else if (value_kind == TYPE_POINTER) {
9303 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9304 value_size = get_atomic_type_size(get_intptr_kind());
9309 if (value_flags != flags || value_size != size)
9313 } while (expression->kind == EXPR_UNARY_CAST);
9317 if (!is_lvalue(expression)) {
9318 errorf(&expression->base.source_position,
9319 "asm output argument is not an lvalue");
9322 if (argument->constraints.begin[0] == '+')
9323 mark_vars_read(expression, NULL);
9325 mark_vars_read(expression, NULL);
9327 argument->expression = expression;
9330 set_address_taken(expression, true);
9333 anchor = &argument->next;
9335 if (token.type != ',')
9346 * Parse a asm statement clobber specification.
9348 static asm_clobber_t *parse_asm_clobbers(void)
9350 asm_clobber_t *result = NULL;
9351 asm_clobber_t *last = NULL;
9353 while (token.type == T_STRING_LITERAL) {
9354 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9355 clobber->clobber = parse_string_literals();
9358 last->next = clobber;
9364 if (token.type != ',')
9373 * Parse an asm statement.
9375 static statement_t *parse_asm_statement(void)
9377 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9378 asm_statement_t *asm_statement = &statement->asms;
9382 if (token.type == T_volatile) {
9384 asm_statement->is_volatile = true;
9388 add_anchor_token(')');
9389 add_anchor_token(':');
9390 asm_statement->asm_text = parse_string_literals();
9392 if (token.type != ':') {
9393 rem_anchor_token(':');
9398 asm_statement->outputs = parse_asm_arguments(true);
9399 if (token.type != ':') {
9400 rem_anchor_token(':');
9405 asm_statement->inputs = parse_asm_arguments(false);
9406 if (token.type != ':') {
9407 rem_anchor_token(':');
9410 rem_anchor_token(':');
9413 asm_statement->clobbers = parse_asm_clobbers();
9416 rem_anchor_token(')');
9420 if (asm_statement->outputs == NULL) {
9421 /* GCC: An 'asm' instruction without any output operands will be treated
9422 * identically to a volatile 'asm' instruction. */
9423 asm_statement->is_volatile = true;
9428 return create_invalid_statement();
9432 * Parse a case statement.
9434 static statement_t *parse_case_statement(void)
9436 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9437 source_position_t *const pos = &statement->base.source_position;
9441 expression_t *const expression = parse_expression();
9442 statement->case_label.expression = expression;
9443 if (!is_constant_expression(expression)) {
9444 /* This check does not prevent the error message in all cases of an
9445 * prior error while parsing the expression. At least it catches the
9446 * common case of a mistyped enum entry. */
9447 if (is_type_valid(skip_typeref(expression->base.type))) {
9448 errorf(pos, "case label does not reduce to an integer constant");
9450 statement->case_label.is_bad = true;
9452 long const val = fold_constant(expression);
9453 statement->case_label.first_case = val;
9454 statement->case_label.last_case = val;
9458 if (token.type == T_DOTDOTDOT) {
9460 expression_t *const end_range = parse_expression();
9461 statement->case_label.end_range = end_range;
9462 if (!is_constant_expression(end_range)) {
9463 /* This check does not prevent the error message in all cases of an
9464 * prior error while parsing the expression. At least it catches the
9465 * common case of a mistyped enum entry. */
9466 if (is_type_valid(skip_typeref(end_range->base.type))) {
9467 errorf(pos, "case range does not reduce to an integer constant");
9469 statement->case_label.is_bad = true;
9471 long const val = fold_constant(end_range);
9472 statement->case_label.last_case = val;
9474 if (warning.other && val < statement->case_label.first_case) {
9475 statement->case_label.is_empty_range = true;
9476 warningf(pos, "empty range specified");
9482 PUSH_PARENT(statement);
9486 if (current_switch != NULL) {
9487 if (! statement->case_label.is_bad) {
9488 /* Check for duplicate case values */
9489 case_label_statement_t *c = &statement->case_label;
9490 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9491 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9494 if (c->last_case < l->first_case || c->first_case > l->last_case)
9497 errorf(pos, "duplicate case value (previously used %P)",
9498 &l->base.source_position);
9502 /* link all cases into the switch statement */
9503 if (current_switch->last_case == NULL) {
9504 current_switch->first_case = &statement->case_label;
9506 current_switch->last_case->next = &statement->case_label;
9508 current_switch->last_case = &statement->case_label;
9510 errorf(pos, "case label not within a switch statement");
9513 statement_t *const inner_stmt = parse_statement();
9514 statement->case_label.statement = inner_stmt;
9515 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9516 errorf(&inner_stmt->base.source_position, "declaration after case label");
9523 return create_invalid_statement();
9527 * Parse a default statement.
9529 static statement_t *parse_default_statement(void)
9531 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9535 PUSH_PARENT(statement);
9538 if (current_switch != NULL) {
9539 const case_label_statement_t *def_label = current_switch->default_label;
9540 if (def_label != NULL) {
9541 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9542 &def_label->base.source_position);
9544 current_switch->default_label = &statement->case_label;
9546 /* link all cases into the switch statement */
9547 if (current_switch->last_case == NULL) {
9548 current_switch->first_case = &statement->case_label;
9550 current_switch->last_case->next = &statement->case_label;
9552 current_switch->last_case = &statement->case_label;
9555 errorf(&statement->base.source_position,
9556 "'default' label not within a switch statement");
9559 statement_t *const inner_stmt = parse_statement();
9560 statement->case_label.statement = inner_stmt;
9561 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9562 errorf(&inner_stmt->base.source_position, "declaration after default label");
9569 return create_invalid_statement();
9573 * Parse a label statement.
9575 static statement_t *parse_label_statement(void)
9577 assert(token.type == T_IDENTIFIER);
9578 symbol_t *symbol = token.v.symbol;
9579 label_t *label = get_label(symbol);
9581 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9582 statement->label.label = label;
9586 PUSH_PARENT(statement);
9588 /* if statement is already set then the label is defined twice,
9589 * otherwise it was just mentioned in a goto/local label declaration so far
9591 if (label->statement != NULL) {
9592 errorf(HERE, "duplicate label '%Y' (declared %P)",
9593 symbol, &label->base.source_position);
9595 label->base.source_position = token.source_position;
9596 label->statement = statement;
9601 if (token.type == '}') {
9602 /* TODO only warn? */
9603 if (warning.other && false) {
9604 warningf(HERE, "label at end of compound statement");
9605 statement->label.statement = create_empty_statement();
9607 errorf(HERE, "label at end of compound statement");
9608 statement->label.statement = create_invalid_statement();
9610 } else if (token.type == ';') {
9611 /* Eat an empty statement here, to avoid the warning about an empty
9612 * statement after a label. label:; is commonly used to have a label
9613 * before a closing brace. */
9614 statement->label.statement = create_empty_statement();
9617 statement_t *const inner_stmt = parse_statement();
9618 statement->label.statement = inner_stmt;
9619 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9620 errorf(&inner_stmt->base.source_position, "declaration after label");
9624 /* remember the labels in a list for later checking */
9625 *label_anchor = &statement->label;
9626 label_anchor = &statement->label.next;
9633 * Parse an if statement.
9635 static statement_t *parse_if(void)
9637 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9641 PUSH_PARENT(statement);
9643 add_anchor_token('{');
9646 add_anchor_token(')');
9647 expression_t *const expr = parse_expression();
9648 statement->ifs.condition = expr;
9649 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9651 semantic_condition(expr, "condition of 'if'-statment");
9652 mark_vars_read(expr, NULL);
9653 rem_anchor_token(')');
9657 rem_anchor_token('{');
9659 add_anchor_token(T_else);
9660 statement->ifs.true_statement = parse_statement();
9661 rem_anchor_token(T_else);
9663 if (token.type == T_else) {
9665 statement->ifs.false_statement = parse_statement();
9673 * Check that all enums are handled in a switch.
9675 * @param statement the switch statement to check
9677 static void check_enum_cases(const switch_statement_t *statement) {
9678 const type_t *type = skip_typeref(statement->expression->base.type);
9679 if (! is_type_enum(type))
9681 const enum_type_t *enumt = &type->enumt;
9683 /* if we have a default, no warnings */
9684 if (statement->default_label != NULL)
9687 /* FIXME: calculation of value should be done while parsing */
9688 /* TODO: quadratic algorithm here. Change to an n log n one */
9689 long last_value = -1;
9690 const entity_t *entry = enumt->enume->base.next;
9691 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9692 entry = entry->base.next) {
9693 const expression_t *expression = entry->enum_value.value;
9694 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9696 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9697 if (l->expression == NULL)
9699 if (l->first_case <= value && value <= l->last_case) {
9705 warningf(&statement->base.source_position,
9706 "enumeration value '%Y' not handled in switch",
9707 entry->base.symbol);
9714 * Parse a switch statement.
9716 static statement_t *parse_switch(void)
9718 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9722 PUSH_PARENT(statement);
9725 add_anchor_token(')');
9726 expression_t *const expr = parse_expression();
9727 mark_vars_read(expr, NULL);
9728 type_t * type = skip_typeref(expr->base.type);
9729 if (is_type_integer(type)) {
9730 type = promote_integer(type);
9731 if (warning.traditional) {
9732 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9733 warningf(&expr->base.source_position,
9734 "'%T' switch expression not converted to '%T' in ISO C",
9738 } else if (is_type_valid(type)) {
9739 errorf(&expr->base.source_position,
9740 "switch quantity is not an integer, but '%T'", type);
9741 type = type_error_type;
9743 statement->switchs.expression = create_implicit_cast(expr, type);
9745 rem_anchor_token(')');
9747 switch_statement_t *rem = current_switch;
9748 current_switch = &statement->switchs;
9749 statement->switchs.body = parse_statement();
9750 current_switch = rem;
9752 if (warning.switch_default &&
9753 statement->switchs.default_label == NULL) {
9754 warningf(&statement->base.source_position, "switch has no default case");
9756 if (warning.switch_enum)
9757 check_enum_cases(&statement->switchs);
9763 return create_invalid_statement();
9766 static statement_t *parse_loop_body(statement_t *const loop)
9768 statement_t *const rem = current_loop;
9769 current_loop = loop;
9771 statement_t *const body = parse_statement();
9778 * Parse a while statement.
9780 static statement_t *parse_while(void)
9782 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9786 PUSH_PARENT(statement);
9789 add_anchor_token(')');
9790 expression_t *const cond = parse_expression();
9791 statement->whiles.condition = cond;
9792 /* §6.8.5:2 The controlling expression of an iteration statement shall
9793 * have scalar type. */
9794 semantic_condition(cond, "condition of 'while'-statement");
9795 mark_vars_read(cond, NULL);
9796 rem_anchor_token(')');
9799 statement->whiles.body = parse_loop_body(statement);
9805 return create_invalid_statement();
9809 * Parse a do statement.
9811 static statement_t *parse_do(void)
9813 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9817 PUSH_PARENT(statement);
9819 add_anchor_token(T_while);
9820 statement->do_while.body = parse_loop_body(statement);
9821 rem_anchor_token(T_while);
9825 add_anchor_token(')');
9826 expression_t *const cond = parse_expression();
9827 statement->do_while.condition = cond;
9828 /* §6.8.5:2 The controlling expression of an iteration statement shall
9829 * have scalar type. */
9830 semantic_condition(cond, "condition of 'do-while'-statement");
9831 mark_vars_read(cond, NULL);
9832 rem_anchor_token(')');
9840 return create_invalid_statement();
9844 * Parse a for statement.
9846 static statement_t *parse_for(void)
9848 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9852 PUSH_PARENT(statement);
9854 size_t const top = environment_top();
9855 scope_push(&statement->fors.scope);
9858 add_anchor_token(')');
9860 if (token.type == ';') {
9862 } else if (is_declaration_specifier(&token, false)) {
9863 parse_declaration(record_entity);
9865 add_anchor_token(';');
9866 expression_t *const init = parse_expression();
9867 statement->fors.initialisation = init;
9868 mark_vars_read(init, VAR_ANY);
9869 if (warning.unused_value && !expression_has_effect(init)) {
9870 warningf(&init->base.source_position,
9871 "initialisation of 'for'-statement has no effect");
9873 rem_anchor_token(';');
9877 if (token.type != ';') {
9878 add_anchor_token(';');
9879 expression_t *const cond = parse_expression();
9880 statement->fors.condition = cond;
9881 /* §6.8.5:2 The controlling expression of an iteration statement shall
9882 * have scalar type. */
9883 semantic_condition(cond, "condition of 'for'-statement");
9884 mark_vars_read(cond, NULL);
9885 rem_anchor_token(';');
9888 if (token.type != ')') {
9889 expression_t *const step = parse_expression();
9890 statement->fors.step = step;
9891 mark_vars_read(step, VAR_ANY);
9892 if (warning.unused_value && !expression_has_effect(step)) {
9893 warningf(&step->base.source_position,
9894 "step of 'for'-statement has no effect");
9898 rem_anchor_token(')');
9899 statement->fors.body = parse_loop_body(statement);
9901 assert(current_scope == &statement->fors.scope);
9903 environment_pop_to(top);
9910 rem_anchor_token(')');
9911 assert(current_scope == &statement->fors.scope);
9913 environment_pop_to(top);
9915 return create_invalid_statement();
9919 * Parse a goto statement.
9921 static statement_t *parse_goto(void)
9923 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9926 if (GNU_MODE && token.type == '*') {
9928 expression_t *expression = parse_expression();
9929 mark_vars_read(expression, NULL);
9931 /* Argh: although documentation says the expression must be of type void*,
9932 * gcc accepts anything that can be casted into void* without error */
9933 type_t *type = expression->base.type;
9935 if (type != type_error_type) {
9936 if (!is_type_pointer(type) && !is_type_integer(type)) {
9937 errorf(&expression->base.source_position,
9938 "cannot convert to a pointer type");
9939 } else if (warning.other && type != type_void_ptr) {
9940 warningf(&expression->base.source_position,
9941 "type of computed goto expression should be 'void*' not '%T'", type);
9943 expression = create_implicit_cast(expression, type_void_ptr);
9946 statement->gotos.expression = expression;
9948 if (token.type != T_IDENTIFIER) {
9950 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9952 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9956 symbol_t *symbol = token.v.symbol;
9959 statement->gotos.label = get_label(symbol);
9962 /* remember the goto's in a list for later checking */
9963 *goto_anchor = &statement->gotos;
9964 goto_anchor = &statement->gotos.next;
9970 return create_invalid_statement();
9974 * Parse a continue statement.
9976 static statement_t *parse_continue(void)
9978 if (current_loop == NULL) {
9979 errorf(HERE, "continue statement not within loop");
9982 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9992 * Parse a break statement.
9994 static statement_t *parse_break(void)
9996 if (current_switch == NULL && current_loop == NULL) {
9997 errorf(HERE, "break statement not within loop or switch");
10000 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10010 * Parse a __leave statement.
10012 static statement_t *parse_leave_statement(void)
10014 if (current_try == NULL) {
10015 errorf(HERE, "__leave statement not within __try");
10018 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10028 * Check if a given entity represents a local variable.
10030 static bool is_local_variable(const entity_t *entity)
10032 if (entity->kind != ENTITY_VARIABLE)
10035 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10036 case STORAGE_CLASS_AUTO:
10037 case STORAGE_CLASS_REGISTER: {
10038 const type_t *type = skip_typeref(entity->declaration.type);
10039 if (is_type_function(type)) {
10051 * Check if a given expression represents a local variable.
10053 static bool expression_is_local_variable(const expression_t *expression)
10055 if (expression->base.kind != EXPR_REFERENCE) {
10058 const entity_t *entity = expression->reference.entity;
10059 return is_local_variable(entity);
10063 * Check if a given expression represents a local variable and
10064 * return its declaration then, else return NULL.
10066 entity_t *expression_is_variable(const expression_t *expression)
10068 if (expression->base.kind != EXPR_REFERENCE) {
10071 entity_t *entity = expression->reference.entity;
10072 if (entity->kind != ENTITY_VARIABLE)
10079 * Parse a return statement.
10081 static statement_t *parse_return(void)
10085 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10087 expression_t *return_value = NULL;
10088 if (token.type != ';') {
10089 return_value = parse_expression();
10090 mark_vars_read(return_value, NULL);
10093 const type_t *const func_type = skip_typeref(current_function->base.type);
10094 assert(is_type_function(func_type));
10095 type_t *const return_type = skip_typeref(func_type->function.return_type);
10097 if (return_value != NULL) {
10098 type_t *return_value_type = skip_typeref(return_value->base.type);
10100 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10101 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10102 if (warning.other) {
10103 warningf(&statement->base.source_position,
10104 "'return' with a value, in function returning void");
10106 return_value = NULL;
10108 assign_error_t error = semantic_assign(return_type, return_value);
10109 report_assign_error(error, return_type, return_value, "'return'",
10110 &statement->base.source_position);
10111 return_value = create_implicit_cast(return_value, return_type);
10113 /* check for returning address of a local var */
10114 if (warning.other && return_value != NULL
10115 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10116 const expression_t *expression = return_value->unary.value;
10117 if (expression_is_local_variable(expression)) {
10118 warningf(&statement->base.source_position,
10119 "function returns address of local variable");
10122 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10123 warningf(&statement->base.source_position,
10124 "'return' without value, in function returning non-void");
10126 statement->returns.value = return_value;
10135 * Parse a declaration statement.
10137 static statement_t *parse_declaration_statement(void)
10139 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10141 entity_t *before = current_scope->last_entity;
10143 parse_external_declaration();
10145 parse_declaration(record_entity);
10147 if (before == NULL) {
10148 statement->declaration.declarations_begin = current_scope->entities;
10150 statement->declaration.declarations_begin = before->base.next;
10152 statement->declaration.declarations_end = current_scope->last_entity;
10158 * Parse an expression statement, ie. expr ';'.
10160 static statement_t *parse_expression_statement(void)
10162 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10164 expression_t *const expr = parse_expression();
10165 statement->expression.expression = expr;
10166 mark_vars_read(expr, VAR_ANY);
10175 * Parse a microsoft __try { } __finally { } or
10176 * __try{ } __except() { }
10178 static statement_t *parse_ms_try_statment(void)
10180 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10183 PUSH_PARENT(statement);
10185 ms_try_statement_t *rem = current_try;
10186 current_try = &statement->ms_try;
10187 statement->ms_try.try_statement = parse_compound_statement(false);
10192 if (token.type == T___except) {
10195 add_anchor_token(')');
10196 expression_t *const expr = parse_expression();
10197 mark_vars_read(expr, NULL);
10198 type_t * type = skip_typeref(expr->base.type);
10199 if (is_type_integer(type)) {
10200 type = promote_integer(type);
10201 } else if (is_type_valid(type)) {
10202 errorf(&expr->base.source_position,
10203 "__expect expression is not an integer, but '%T'", type);
10204 type = type_error_type;
10206 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10207 rem_anchor_token(')');
10209 statement->ms_try.final_statement = parse_compound_statement(false);
10210 } else if (token.type == T__finally) {
10212 statement->ms_try.final_statement = parse_compound_statement(false);
10214 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10215 return create_invalid_statement();
10219 return create_invalid_statement();
10222 static statement_t *parse_empty_statement(void)
10224 if (warning.empty_statement) {
10225 warningf(HERE, "statement is empty");
10227 statement_t *const statement = create_empty_statement();
10232 static statement_t *parse_local_label_declaration(void)
10234 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10238 entity_t *begin = NULL, *end = NULL;
10241 if (token.type != T_IDENTIFIER) {
10242 parse_error_expected("while parsing local label declaration",
10243 T_IDENTIFIER, NULL);
10246 symbol_t *symbol = token.v.symbol;
10247 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10248 if (entity != NULL && entity->base.parent_scope == current_scope) {
10249 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10250 symbol, &entity->base.source_position);
10252 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10254 entity->base.parent_scope = current_scope;
10255 entity->base.namespc = NAMESPACE_LABEL;
10256 entity->base.source_position = token.source_position;
10257 entity->base.symbol = symbol;
10260 end->base.next = entity;
10265 environment_push(entity);
10269 if (token.type != ',')
10275 statement->declaration.declarations_begin = begin;
10276 statement->declaration.declarations_end = end;
10280 static void parse_namespace_definition(void)
10284 entity_t *entity = NULL;
10285 symbol_t *symbol = NULL;
10287 if (token.type == T_IDENTIFIER) {
10288 symbol = token.v.symbol;
10291 entity = get_entity(symbol, NAMESPACE_NORMAL);
10292 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10293 && entity->base.parent_scope == current_scope) {
10294 error_redefined_as_different_kind(&token.source_position,
10295 entity, ENTITY_NAMESPACE);
10300 if (entity == NULL) {
10301 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10302 entity->base.symbol = symbol;
10303 entity->base.source_position = token.source_position;
10304 entity->base.namespc = NAMESPACE_NORMAL;
10305 entity->base.parent_scope = current_scope;
10308 if (token.type == '=') {
10309 /* TODO: parse namespace alias */
10310 panic("namespace alias definition not supported yet");
10313 environment_push(entity);
10314 append_entity(current_scope, entity);
10316 size_t const top = environment_top();
10317 scope_push(&entity->namespacee.members);
10324 assert(current_scope == &entity->namespacee.members);
10326 environment_pop_to(top);
10330 * Parse a statement.
10331 * There's also parse_statement() which additionally checks for
10332 * "statement has no effect" warnings
10334 static statement_t *intern_parse_statement(void)
10336 statement_t *statement = NULL;
10338 /* declaration or statement */
10339 add_anchor_token(';');
10340 switch (token.type) {
10341 case T_IDENTIFIER: {
10342 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10343 if (la1_type == ':') {
10344 statement = parse_label_statement();
10345 } else if (is_typedef_symbol(token.v.symbol)) {
10346 statement = parse_declaration_statement();
10348 /* it's an identifier, the grammar says this must be an
10349 * expression statement. However it is common that users mistype
10350 * declaration types, so we guess a bit here to improve robustness
10351 * for incorrect programs */
10352 switch (la1_type) {
10355 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10356 goto expression_statment;
10361 statement = parse_declaration_statement();
10365 expression_statment:
10366 statement = parse_expression_statement();
10373 case T___extension__:
10374 /* This can be a prefix to a declaration or an expression statement.
10375 * We simply eat it now and parse the rest with tail recursion. */
10378 } while (token.type == T___extension__);
10379 bool old_gcc_extension = in_gcc_extension;
10380 in_gcc_extension = true;
10381 statement = intern_parse_statement();
10382 in_gcc_extension = old_gcc_extension;
10386 statement = parse_declaration_statement();
10390 statement = parse_local_label_declaration();
10393 case ';': statement = parse_empty_statement(); break;
10394 case '{': statement = parse_compound_statement(false); break;
10395 case T___leave: statement = parse_leave_statement(); break;
10396 case T___try: statement = parse_ms_try_statment(); break;
10397 case T_asm: statement = parse_asm_statement(); break;
10398 case T_break: statement = parse_break(); break;
10399 case T_case: statement = parse_case_statement(); break;
10400 case T_continue: statement = parse_continue(); break;
10401 case T_default: statement = parse_default_statement(); break;
10402 case T_do: statement = parse_do(); break;
10403 case T_for: statement = parse_for(); break;
10404 case T_goto: statement = parse_goto(); break;
10405 case T_if: statement = parse_if(); break;
10406 case T_return: statement = parse_return(); break;
10407 case T_switch: statement = parse_switch(); break;
10408 case T_while: statement = parse_while(); break;
10411 statement = parse_expression_statement();
10415 errorf(HERE, "unexpected token %K while parsing statement", &token);
10416 statement = create_invalid_statement();
10421 rem_anchor_token(';');
10423 assert(statement != NULL
10424 && statement->base.source_position.input_name != NULL);
10430 * parse a statement and emits "statement has no effect" warning if needed
10431 * (This is really a wrapper around intern_parse_statement with check for 1
10432 * single warning. It is needed, because for statement expressions we have
10433 * to avoid the warning on the last statement)
10435 static statement_t *parse_statement(void)
10437 statement_t *statement = intern_parse_statement();
10439 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10440 expression_t *expression = statement->expression.expression;
10441 if (!expression_has_effect(expression)) {
10442 warningf(&expression->base.source_position,
10443 "statement has no effect");
10451 * Parse a compound statement.
10453 static statement_t *parse_compound_statement(bool inside_expression_statement)
10455 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10457 PUSH_PARENT(statement);
10460 add_anchor_token('}');
10462 size_t const top = environment_top();
10463 scope_push(&statement->compound.scope);
10465 statement_t **anchor = &statement->compound.statements;
10466 bool only_decls_so_far = true;
10467 while (token.type != '}') {
10468 if (token.type == T_EOF) {
10469 errorf(&statement->base.source_position,
10470 "EOF while parsing compound statement");
10473 statement_t *sub_statement = intern_parse_statement();
10474 if (is_invalid_statement(sub_statement)) {
10475 /* an error occurred. if we are at an anchor, return */
10481 if (warning.declaration_after_statement) {
10482 if (sub_statement->kind != STATEMENT_DECLARATION) {
10483 only_decls_so_far = false;
10484 } else if (!only_decls_so_far) {
10485 warningf(&sub_statement->base.source_position,
10486 "ISO C90 forbids mixed declarations and code");
10490 *anchor = sub_statement;
10492 while (sub_statement->base.next != NULL)
10493 sub_statement = sub_statement->base.next;
10495 anchor = &sub_statement->base.next;
10499 /* look over all statements again to produce no effect warnings */
10500 if (warning.unused_value) {
10501 statement_t *sub_statement = statement->compound.statements;
10502 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10503 if (sub_statement->kind != STATEMENT_EXPRESSION)
10505 /* don't emit a warning for the last expression in an expression
10506 * statement as it has always an effect */
10507 if (inside_expression_statement && sub_statement->base.next == NULL)
10510 expression_t *expression = sub_statement->expression.expression;
10511 if (!expression_has_effect(expression)) {
10512 warningf(&expression->base.source_position,
10513 "statement has no effect");
10519 rem_anchor_token('}');
10520 assert(current_scope == &statement->compound.scope);
10522 environment_pop_to(top);
10529 * Check for unused global static functions and variables
10531 static void check_unused_globals(void)
10533 if (!warning.unused_function && !warning.unused_variable)
10536 for (const entity_t *entity = file_scope->entities; entity != NULL;
10537 entity = entity->base.next) {
10538 if (!is_declaration(entity))
10541 const declaration_t *declaration = &entity->declaration;
10542 if (declaration->used ||
10543 declaration->modifiers & DM_UNUSED ||
10544 declaration->modifiers & DM_USED ||
10545 declaration->storage_class != STORAGE_CLASS_STATIC)
10548 type_t *const type = declaration->type;
10550 if (entity->kind == ENTITY_FUNCTION) {
10551 /* inhibit warning for static inline functions */
10552 if (entity->function.is_inline)
10555 s = entity->function.statement != NULL ? "defined" : "declared";
10560 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10561 type, declaration->base.symbol, s);
10565 static void parse_global_asm(void)
10567 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10572 statement->asms.asm_text = parse_string_literals();
10573 statement->base.next = unit->global_asm;
10574 unit->global_asm = statement;
10582 static void parse_linkage_specification(void)
10585 assert(token.type == T_STRING_LITERAL);
10587 const char *linkage = parse_string_literals().begin;
10589 linkage_kind_t old_linkage = current_linkage;
10590 linkage_kind_t new_linkage;
10591 if (strcmp(linkage, "C") == 0) {
10592 new_linkage = LINKAGE_C;
10593 } else if (strcmp(linkage, "C++") == 0) {
10594 new_linkage = LINKAGE_CXX;
10596 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10597 new_linkage = LINKAGE_INVALID;
10599 current_linkage = new_linkage;
10601 if (token.type == '{') {
10610 assert(current_linkage == new_linkage);
10611 current_linkage = old_linkage;
10614 static void parse_external(void)
10616 switch (token.type) {
10617 DECLARATION_START_NO_EXTERN
10619 case T___extension__:
10620 case '(': /* for function declarations with implicit return type and
10621 * parenthesized declarator, i.e. (f)(void); */
10622 parse_external_declaration();
10626 if (look_ahead(1)->type == T_STRING_LITERAL) {
10627 parse_linkage_specification();
10629 parse_external_declaration();
10634 parse_global_asm();
10638 parse_namespace_definition();
10642 if (!strict_mode) {
10644 warningf(HERE, "stray ';' outside of function");
10651 errorf(HERE, "stray %K outside of function", &token);
10652 if (token.type == '(' || token.type == '{' || token.type == '[')
10653 eat_until_matching_token(token.type);
10659 static void parse_externals(void)
10661 add_anchor_token('}');
10662 add_anchor_token(T_EOF);
10665 unsigned char token_anchor_copy[T_LAST_TOKEN];
10666 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10669 while (token.type != T_EOF && token.type != '}') {
10671 bool anchor_leak = false;
10672 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10673 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10675 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10676 anchor_leak = true;
10679 if (in_gcc_extension) {
10680 errorf(HERE, "Leaked __extension__");
10681 anchor_leak = true;
10691 rem_anchor_token(T_EOF);
10692 rem_anchor_token('}');
10696 * Parse a translation unit.
10698 static void parse_translation_unit(void)
10700 add_anchor_token(T_EOF);
10705 if (token.type == T_EOF)
10708 errorf(HERE, "stray %K outside of function", &token);
10709 if (token.type == '(' || token.type == '{' || token.type == '[')
10710 eat_until_matching_token(token.type);
10718 * @return the translation unit or NULL if errors occurred.
10720 void start_parsing(void)
10722 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10723 label_stack = NEW_ARR_F(stack_entry_t, 0);
10724 diagnostic_count = 0;
10728 type_set_output(stderr);
10729 ast_set_output(stderr);
10731 assert(unit == NULL);
10732 unit = allocate_ast_zero(sizeof(unit[0]));
10734 assert(file_scope == NULL);
10735 file_scope = &unit->scope;
10737 assert(current_scope == NULL);
10738 scope_push(&unit->scope);
10741 translation_unit_t *finish_parsing(void)
10743 /* do NOT use scope_pop() here, this will crash, will it by hand */
10744 assert(current_scope == &unit->scope);
10745 current_scope = NULL;
10747 assert(file_scope == &unit->scope);
10748 check_unused_globals();
10751 DEL_ARR_F(environment_stack);
10752 DEL_ARR_F(label_stack);
10754 translation_unit_t *result = unit;
10761 lookahead_bufpos = 0;
10762 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10765 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10766 parse_translation_unit();
10770 * Initialize the parser.
10772 void init_parser(void)
10774 sym_anonymous = symbol_table_insert("<anonymous>");
10776 if (c_mode & _MS) {
10777 /* add predefined symbols for extended-decl-modifier */
10778 sym_align = symbol_table_insert("align");
10779 sym_allocate = symbol_table_insert("allocate");
10780 sym_dllimport = symbol_table_insert("dllimport");
10781 sym_dllexport = symbol_table_insert("dllexport");
10782 sym_naked = symbol_table_insert("naked");
10783 sym_noinline = symbol_table_insert("noinline");
10784 sym_noreturn = symbol_table_insert("noreturn");
10785 sym_nothrow = symbol_table_insert("nothrow");
10786 sym_novtable = symbol_table_insert("novtable");
10787 sym_property = symbol_table_insert("property");
10788 sym_get = symbol_table_insert("get");
10789 sym_put = symbol_table_insert("put");
10790 sym_selectany = symbol_table_insert("selectany");
10791 sym_thread = symbol_table_insert("thread");
10792 sym_uuid = symbol_table_insert("uuid");
10793 sym_deprecated = symbol_table_insert("deprecated");
10794 sym_restrict = symbol_table_insert("restrict");
10795 sym_noalias = symbol_table_insert("noalias");
10797 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10799 init_expression_parsers();
10800 obstack_init(&temp_obst);
10802 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10803 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10807 * Terminate the parser.
10809 void exit_parser(void)
10811 obstack_free(&temp_obst, NULL);