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"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 //#define PRINT_TOKENS
43 #define MAX_LOOKAHEAD 2
46 declaration_t *old_declaration;
48 unsigned short namespc;
51 typedef struct declaration_specifiers_t declaration_specifiers_t;
52 struct declaration_specifiers_t {
53 source_position_t source_position;
54 unsigned char declared_storage_class;
55 unsigned char alignment; /**< Alignment, 0 if not set. */
56 unsigned int is_inline : 1;
57 unsigned int deprecated : 1;
58 decl_modifiers_t decl_modifiers; /**< MS __declspec extended modifier mask */
59 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
60 symbol_t *get_property_sym; /**< the name of the get property if set. */
61 symbol_t *put_property_sym; /**< the name of the put property if set. */
66 * An environment for parsing initializers (and compound literals).
68 typedef struct parse_initializer_env_t {
69 type_t *type; /**< the type of the initializer. In case of an
70 array type with unspecified size this gets
71 adjusted to the actual size. */
72 declaration_t *declaration; /**< the declaration that is initialized if any */
73 bool must_be_constant;
74 } parse_initializer_env_t;
76 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
79 static token_t lookahead_buffer[MAX_LOOKAHEAD];
80 static int lookahead_bufpos;
81 static stack_entry_t *environment_stack = NULL;
82 static stack_entry_t *label_stack = NULL;
83 static scope_t *global_scope = NULL;
84 static scope_t *scope = NULL;
85 static declaration_t *last_declaration = NULL;
86 static declaration_t *current_function = NULL;
87 static switch_statement_t *current_switch = NULL;
88 static statement_t *current_loop = NULL;
89 static goto_statement_t *goto_first = NULL;
90 static goto_statement_t *goto_last = NULL;
91 static label_statement_t *label_first = NULL;
92 static label_statement_t *label_last = NULL;
93 static struct obstack temp_obst;
95 /* symbols for Microsoft extended-decl-modifier */
96 static const symbol_t *sym_align = NULL;
97 static const symbol_t *sym_allocate = NULL;
98 static const symbol_t *sym_dllimport = NULL;
99 static const symbol_t *sym_dllexport = NULL;
100 static const symbol_t *sym_naked = NULL;
101 static const symbol_t *sym_noinline = NULL;
102 static const symbol_t *sym_noreturn = NULL;
103 static const symbol_t *sym_nothrow = NULL;
104 static const symbol_t *sym_novtable = NULL;
105 static const symbol_t *sym_property = NULL;
106 static const symbol_t *sym_get = NULL;
107 static const symbol_t *sym_put = NULL;
108 static const symbol_t *sym_selectany = NULL;
109 static const symbol_t *sym_thread = NULL;
110 static const symbol_t *sym_uuid = NULL;
111 static const symbol_t *sym_deprecated = NULL;
112 static const symbol_t *sym_restrict = NULL;
113 static const symbol_t *sym_noalias = NULL;
115 /** The token anchor set */
116 static unsigned char token_anchor_set[T_LAST_TOKEN];
118 /** The current source position. */
119 #define HERE token.source_position
121 static type_t *type_valist;
123 static statement_t *parse_compound_statement(void);
124 static statement_t *parse_statement(void);
126 static expression_t *parse_sub_expression(unsigned precedence);
127 static expression_t *parse_expression(void);
128 static type_t *parse_typename(void);
130 static void parse_compound_type_entries(declaration_t *compound_declaration);
131 static declaration_t *parse_declarator(
132 const declaration_specifiers_t *specifiers, bool may_be_abstract);
133 static declaration_t *record_declaration(declaration_t *declaration);
135 static void semantic_comparison(binary_expression_t *expression);
137 #define STORAGE_CLASSES \
144 #define TYPE_QUALIFIERS \
151 #ifdef PROVIDE_COMPLEX
152 #define COMPLEX_SPECIFIERS \
154 #define IMAGINARY_SPECIFIERS \
157 #define COMPLEX_SPECIFIERS
158 #define IMAGINARY_SPECIFIERS
161 #define TYPE_SPECIFIERS \
176 case T___builtin_va_list: \
181 #define DECLARATION_START \
186 #define TYPENAME_START \
191 * Allocate an AST node with given size and
192 * initialize all fields with zero.
194 static void *allocate_ast_zero(size_t size)
196 void *res = allocate_ast(size);
197 memset(res, 0, size);
201 static declaration_t *allocate_declaration_zero(void)
203 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
204 declaration->type = type_error_type;
205 declaration->alignment = 0;
210 * Returns the size of a statement node.
212 * @param kind the statement kind
214 static size_t get_statement_struct_size(statement_kind_t kind)
216 static const size_t sizes[] = {
217 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
218 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
219 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
220 [STATEMENT_RETURN] = sizeof(return_statement_t),
221 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
222 [STATEMENT_IF] = sizeof(if_statement_t),
223 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
224 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
225 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
226 [STATEMENT_BREAK] = sizeof(statement_base_t),
227 [STATEMENT_GOTO] = sizeof(goto_statement_t),
228 [STATEMENT_LABEL] = sizeof(label_statement_t),
229 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
230 [STATEMENT_WHILE] = sizeof(while_statement_t),
231 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
232 [STATEMENT_FOR] = sizeof(for_statement_t),
233 [STATEMENT_ASM] = sizeof(asm_statement_t)
235 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
236 assert(sizes[kind] != 0);
241 * Returns the size of an expression node.
243 * @param kind the expression kind
245 static size_t get_expression_struct_size(expression_kind_t kind)
247 static const size_t sizes[] = {
248 [EXPR_INVALID] = sizeof(expression_base_t),
249 [EXPR_REFERENCE] = sizeof(reference_expression_t),
250 [EXPR_CONST] = sizeof(const_expression_t),
251 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
252 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
253 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
254 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
255 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
256 [EXPR_CALL] = sizeof(call_expression_t),
257 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
258 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
259 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
260 [EXPR_SELECT] = sizeof(select_expression_t),
261 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
262 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
263 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
264 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
265 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
266 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
267 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
268 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
269 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
270 [EXPR_VA_START] = sizeof(va_start_expression_t),
271 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
272 [EXPR_STATEMENT] = sizeof(statement_expression_t),
274 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
275 return sizes[EXPR_UNARY_FIRST];
277 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
278 return sizes[EXPR_BINARY_FIRST];
280 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
281 assert(sizes[kind] != 0);
286 * Allocate a statement node of given kind and initialize all
289 static statement_t *allocate_statement_zero(statement_kind_t kind)
291 size_t size = get_statement_struct_size(kind);
292 statement_t *res = allocate_ast_zero(size);
294 res->base.kind = kind;
299 * Allocate an expression node of given kind and initialize all
302 static expression_t *allocate_expression_zero(expression_kind_t kind)
304 size_t size = get_expression_struct_size(kind);
305 expression_t *res = allocate_ast_zero(size);
307 res->base.kind = kind;
308 res->base.type = type_error_type;
313 * Creates a new invalid expression.
315 static expression_t *create_invalid_expression(void)
317 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
318 expression->base.source_position = token.source_position;
323 * Creates a new invalid statement.
325 static statement_t *create_invalid_statement(void)
327 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
328 statement->base.source_position = token.source_position;
333 * Allocate a new empty statement.
335 static statement_t *create_empty_statement(void)
337 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
338 statement->base.source_position = token.source_position;
343 * Returns the size of a type node.
345 * @param kind the type kind
347 static size_t get_type_struct_size(type_kind_t kind)
349 static const size_t sizes[] = {
350 [TYPE_ATOMIC] = sizeof(atomic_type_t),
351 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
352 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
353 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
354 [TYPE_ENUM] = sizeof(enum_type_t),
355 [TYPE_FUNCTION] = sizeof(function_type_t),
356 [TYPE_POINTER] = sizeof(pointer_type_t),
357 [TYPE_ARRAY] = sizeof(array_type_t),
358 [TYPE_BUILTIN] = sizeof(builtin_type_t),
359 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
360 [TYPE_TYPEOF] = sizeof(typeof_type_t),
362 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
363 assert(kind <= TYPE_TYPEOF);
364 assert(sizes[kind] != 0);
369 * Allocate a type node of given kind and initialize all
372 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
374 size_t size = get_type_struct_size(kind);
375 type_t *res = obstack_alloc(type_obst, size);
376 memset(res, 0, size);
378 res->base.kind = kind;
379 res->base.source_position = source_position;
384 * Returns the size of an initializer node.
386 * @param kind the initializer kind
388 static size_t get_initializer_size(initializer_kind_t kind)
390 static const size_t sizes[] = {
391 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
392 [INITIALIZER_STRING] = sizeof(initializer_string_t),
393 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
394 [INITIALIZER_LIST] = sizeof(initializer_list_t),
395 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
397 assert(kind < sizeof(sizes) / sizeof(*sizes));
398 assert(sizes[kind] != 0);
403 * Allocate an initializer node of given kind and initialize all
406 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
408 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
415 * Free a type from the type obstack.
417 static void free_type(void *type)
419 obstack_free(type_obst, type);
423 * Returns the index of the top element of the environment stack.
425 static size_t environment_top(void)
427 return ARR_LEN(environment_stack);
431 * Returns the index of the top element of the label stack.
433 static size_t label_top(void)
435 return ARR_LEN(label_stack);
439 * Return the next token.
441 static inline void next_token(void)
443 token = lookahead_buffer[lookahead_bufpos];
444 lookahead_buffer[lookahead_bufpos] = lexer_token;
447 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
450 print_token(stderr, &token);
451 fprintf(stderr, "\n");
456 * Return the next token with a given lookahead.
458 static inline const token_t *look_ahead(int num)
460 assert(num > 0 && num <= MAX_LOOKAHEAD);
461 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
462 return &lookahead_buffer[pos];
466 * Adds a token to the token anchor set (a multi-set).
468 static void add_anchor_token(int token_type) {
469 assert(0 <= token_type && token_type < T_LAST_TOKEN);
470 ++token_anchor_set[token_type];
474 * Remove a token from the token anchor set (a multi-set).
476 static void rem_anchor_token(int token_type) {
477 assert(0 <= token_type && token_type < T_LAST_TOKEN);
478 --token_anchor_set[token_type];
481 static bool at_anchor(void) {
484 return token_anchor_set[token.type];
488 * Eat tokens until a matching token is found.
490 static void eat_until_matching_token(int type) {
491 unsigned parenthesis_count = 0;
492 unsigned brace_count = 0;
493 unsigned bracket_count = 0;
494 int end_token = type;
503 while(token.type != end_token ||
504 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
508 case '(': ++parenthesis_count; break;
509 case '{': ++brace_count; break;
510 case '[': ++bracket_count; break;
512 if(parenthesis_count > 0)
520 if(bracket_count > 0)
531 * Eat input tokens until an anchor is found.
533 static void eat_until_anchor(void) {
534 if(token.type == T_EOF)
536 while(token_anchor_set[token.type] == 0) {
537 if(token.type == '(' || token.type == '{' || token.type == '[')
538 eat_until_matching_token(token.type);
539 if(token.type == T_EOF)
545 static void eat_block(void) {
546 eat_until_matching_token('{');
547 if(token.type == '}')
552 * eat all token until a ';' is reached
553 * or a stop token is found.
555 static void eat_statement(void) {
556 eat_until_matching_token(';');
557 if(token.type == ';')
561 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
564 * Report a parse error because an expected token was not found.
566 static void parse_error_expected(const char *message, ...)
568 if(message != NULL) {
569 errorf(HERE, "%s", message);
572 va_start(ap, message);
573 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
578 * Report a type error.
580 static void type_error(const char *msg, const source_position_t source_position,
583 errorf(source_position, "%s, but found type '%T'", msg, type);
587 * Report an incompatible type.
589 static void type_error_incompatible(const char *msg,
590 const source_position_t source_position, type_t *type1, type_t *type2)
592 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
596 * Expect the the current token is the expected token.
597 * If not, generate an error, eat the current statement,
598 * and goto the end_error label.
600 #define expect(expected) \
602 if(UNLIKELY(token.type != (expected))) { \
603 parse_error_expected(NULL, (expected), 0); \
604 add_anchor_token(expected); \
605 eat_until_anchor(); \
606 rem_anchor_token(expected); \
612 static void set_scope(scope_t *new_scope)
615 scope->last_declaration = last_declaration;
619 last_declaration = new_scope->last_declaration;
623 * Search a symbol in a given namespace and returns its declaration or
624 * NULL if this symbol was not found.
626 static declaration_t *get_declaration(const symbol_t *const symbol,
627 const namespace_t namespc)
629 declaration_t *declaration = symbol->declaration;
630 for( ; declaration != NULL; declaration = declaration->symbol_next) {
631 if(declaration->namespc == namespc)
639 * pushs an environment_entry on the environment stack and links the
640 * corresponding symbol to the new entry
642 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
644 symbol_t *symbol = declaration->symbol;
645 namespace_t namespc = (namespace_t) declaration->namespc;
647 /* replace/add declaration into declaration list of the symbol */
648 declaration_t *iter = symbol->declaration;
650 symbol->declaration = declaration;
652 declaration_t *iter_last = NULL;
653 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
654 /* replace an entry? */
655 if(iter->namespc == namespc) {
656 if(iter_last == NULL) {
657 symbol->declaration = declaration;
659 iter_last->symbol_next = declaration;
661 declaration->symbol_next = iter->symbol_next;
666 assert(iter_last->symbol_next == NULL);
667 iter_last->symbol_next = declaration;
671 /* remember old declaration */
673 entry.symbol = symbol;
674 entry.old_declaration = iter;
675 entry.namespc = (unsigned short) namespc;
676 ARR_APP1(stack_entry_t, *stack_ptr, entry);
679 static void environment_push(declaration_t *declaration)
681 assert(declaration->source_position.input_name != NULL);
682 assert(declaration->parent_scope != NULL);
683 stack_push(&environment_stack, declaration);
686 static void label_push(declaration_t *declaration)
688 declaration->parent_scope = ¤t_function->scope;
689 stack_push(&label_stack, declaration);
693 * pops symbols from the environment stack until @p new_top is the top element
695 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
697 stack_entry_t *stack = *stack_ptr;
698 size_t top = ARR_LEN(stack);
701 assert(new_top <= top);
705 for(i = top; i > new_top; --i) {
706 stack_entry_t *entry = &stack[i - 1];
708 declaration_t *old_declaration = entry->old_declaration;
709 symbol_t *symbol = entry->symbol;
710 namespace_t namespc = (namespace_t)entry->namespc;
712 /* replace/remove declaration */
713 declaration_t *declaration = symbol->declaration;
714 assert(declaration != NULL);
715 if(declaration->namespc == namespc) {
716 if(old_declaration == NULL) {
717 symbol->declaration = declaration->symbol_next;
719 symbol->declaration = old_declaration;
722 declaration_t *iter_last = declaration;
723 declaration_t *iter = declaration->symbol_next;
724 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
725 /* replace an entry? */
726 if(iter->namespc == namespc) {
727 assert(iter_last != NULL);
728 iter_last->symbol_next = old_declaration;
729 if(old_declaration != NULL) {
730 old_declaration->symbol_next = iter->symbol_next;
735 assert(iter != NULL);
739 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
742 static void environment_pop_to(size_t new_top)
744 stack_pop_to(&environment_stack, new_top);
747 static void label_pop_to(size_t new_top)
749 stack_pop_to(&label_stack, new_top);
753 static int get_rank(const type_t *type)
755 assert(!is_typeref(type));
756 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
757 * and esp. footnote 108). However we can't fold constants (yet), so we
758 * can't decide whether unsigned int is possible, while int always works.
759 * (unsigned int would be preferable when possible... for stuff like
760 * struct { enum { ... } bla : 4; } ) */
761 if(type->kind == TYPE_ENUM)
762 return ATOMIC_TYPE_INT;
764 assert(type->kind == TYPE_ATOMIC);
765 return type->atomic.akind;
768 static type_t *promote_integer(type_t *type)
770 if(type->kind == TYPE_BITFIELD)
771 type = type->bitfield.base;
773 if(get_rank(type) < ATOMIC_TYPE_INT)
780 * Create a cast expression.
782 * @param expression the expression to cast
783 * @param dest_type the destination type
785 static expression_t *create_cast_expression(expression_t *expression,
788 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
790 cast->unary.value = expression;
791 cast->base.type = dest_type;
797 * Check if a given expression represents the 0 pointer constant.
799 static bool is_null_pointer_constant(const expression_t *expression)
801 /* skip void* cast */
802 if(expression->kind == EXPR_UNARY_CAST
803 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
804 expression = expression->unary.value;
807 /* TODO: not correct yet, should be any constant integer expression
808 * which evaluates to 0 */
809 if (expression->kind != EXPR_CONST)
812 type_t *const type = skip_typeref(expression->base.type);
813 if (!is_type_integer(type))
816 return expression->conste.v.int_value == 0;
820 * Create an implicit cast expression.
822 * @param expression the expression to cast
823 * @param dest_type the destination type
825 static expression_t *create_implicit_cast(expression_t *expression,
828 type_t *const source_type = expression->base.type;
830 if (source_type == dest_type)
833 return create_cast_expression(expression, dest_type);
836 /** Implements the rules from § 6.5.16.1 */
837 static type_t *semantic_assign(type_t *orig_type_left,
838 const expression_t *const right,
840 source_position_t source_position)
842 type_t *const orig_type_right = right->base.type;
843 type_t *const type_left = skip_typeref(orig_type_left);
844 type_t *const type_right = skip_typeref(orig_type_right);
846 if(is_type_pointer(type_left)) {
847 if(is_null_pointer_constant(right)) {
848 return orig_type_left;
849 } else if(is_type_pointer(type_right)) {
850 type_t *points_to_left
851 = skip_typeref(type_left->pointer.points_to);
852 type_t *points_to_right
853 = skip_typeref(type_right->pointer.points_to);
855 /* the left type has all qualifiers from the right type */
856 unsigned missing_qualifiers
857 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
858 if(missing_qualifiers != 0) {
859 errorf(source_position,
860 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
861 return orig_type_left;
864 points_to_left = get_unqualified_type(points_to_left);
865 points_to_right = get_unqualified_type(points_to_right);
867 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
868 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
869 return orig_type_left;
872 if (!types_compatible(points_to_left, points_to_right)) {
873 warningf(source_position,
874 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
875 orig_type_left, context, right, orig_type_right);
878 return orig_type_left;
879 } else if(is_type_integer(type_right)) {
880 warningf(source_position,
881 "%s makes pointer '%T' from integer '%T' without a cast",
882 context, orig_type_left, orig_type_right);
883 return orig_type_left;
885 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
886 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
887 && is_type_pointer(type_right))) {
888 return orig_type_left;
889 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
890 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
891 type_t *const unqual_type_left = get_unqualified_type(type_left);
892 type_t *const unqual_type_right = get_unqualified_type(type_right);
893 if (types_compatible(unqual_type_left, unqual_type_right)) {
894 return orig_type_left;
896 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
897 warningf(source_position,
898 "%s makes integer '%T' from pointer '%T' without a cast",
899 context, orig_type_left, orig_type_right);
900 return orig_type_left;
903 if (!is_type_valid(type_left))
906 if (!is_type_valid(type_right))
907 return orig_type_right;
912 static expression_t *parse_constant_expression(void)
914 /* start parsing at precedence 7 (conditional expression) */
915 expression_t *result = parse_sub_expression(7);
917 if(!is_constant_expression(result)) {
918 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
924 static expression_t *parse_assignment_expression(void)
926 /* start parsing at precedence 2 (assignment expression) */
927 return parse_sub_expression(2);
930 static type_t *make_global_typedef(const char *name, type_t *type)
932 symbol_t *const symbol = symbol_table_insert(name);
934 declaration_t *const declaration = allocate_declaration_zero();
935 declaration->namespc = NAMESPACE_NORMAL;
936 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
937 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
938 declaration->type = type;
939 declaration->symbol = symbol;
940 declaration->source_position = builtin_source_position;
942 record_declaration(declaration);
944 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
945 typedef_type->typedeft.declaration = declaration;
950 static string_t parse_string_literals(void)
952 assert(token.type == T_STRING_LITERAL);
953 string_t result = token.v.string;
957 while (token.type == T_STRING_LITERAL) {
958 result = concat_strings(&result, &token.v.string);
965 typedef enum gnu_attribute_kind_t {
976 GNU_AK_ALWAYS_INLINE,
987 } gnu_attribute_kind_t;
989 static const char *gnu_attribute_names[GNU_AK_LAST] = {
990 [GNU_AK_CONST] = "const",
991 [GNU_AK_VOLATILE] = "volatile",
992 [GNU_AK_CDECL] = "cdecl",
993 [GNU_AK_STDCALL] = "stdcall",
994 [GNU_AK_FASTCALL] = "fastcall",
995 [GNU_AK_DEPRECATED] = "deprecated",
996 [GNU_AK_NOINLINE] = "noinline",
997 [GNU_AK_NORETURN] = "noreturn",
998 [GNU_AK_NAKED] = "naked",
999 [GNU_AK_PURE] = "pure",
1000 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1001 [GNU_AK_MALLOC] = "malloc",
1002 [GNU_AK_WEAK] = "weak",
1003 [GNU_AK_CONSTRUCTOR] = "constructor",
1004 [GNU_AK_DESTRUCTOR] = "destructor",
1005 [GNU_AK_ALIGNED] = "aligned",
1006 [GNU_AK_ALIAS] = "alias",
1007 [GNU_AK_SECTION] = "section",
1008 [GNU_AK_FORMAT] = "format",
1009 [GNU_AK_FORMAT_ARG] = "format_arg"
1013 * compare two string, ignoring double underscores on the second.
1015 static int strcmp_underscore(const char *s1, const char *s2) {
1016 if(s2[0] == '_' && s2[1] == '_') {
1018 size_t l1 = strlen(s1);
1019 if(l1 + 2 != strlen(s2)) {
1023 return strncmp(s1, s2, l1);
1025 return strcmp(s1, s2);
1028 static expression_t *parse_gnu_attribute_const_arg(void) {
1029 expression_t *expression;
1030 add_anchor_token('(');
1031 expression = parse_constant_expression();
1032 rem_anchor_token('(');
1036 return create_invalid_expression();
1039 static string_t parse_gnu_attribute_string_arg(void) {
1040 string_t string = { NULL, 0 };
1041 add_anchor_token('(');
1042 if(token.type != T_STRING_LITERAL) {
1043 parse_error_expected("while parsing attribute directive", T_STRING_LITERAL);
1046 string = parse_string_literals();
1047 rem_anchor_token('(');
1053 static const char *format_names[] = {
1061 * parse ( identifier, const expression, const expression )
1063 static void parse_gnu_attribute_format_args(void) {
1065 if(token.type != T_IDENTIFIER) {
1066 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER);
1069 const char *name = token.v.symbol->string;
1070 for(i = 0; i < 4; ++i) {
1071 if(strcmp_underscore(format_names[i], name) == 0)
1075 if(warning.attribute)
1076 warningf(HERE, "'%s' is an unrecognized format function type", name);
1081 add_anchor_token(')');
1082 add_anchor_token(',');
1083 parse_constant_expression();
1084 rem_anchor_token(',');
1085 rem_anchor_token('(');
1088 add_anchor_token(')');
1089 parse_constant_expression();
1090 rem_anchor_token('(');
1098 * Parse one GNU attribute.
1100 * Note that attribute names can be specified WITH or WITHOUT
1101 * double underscores, ie const or __const__.
1103 * The following attributes are parsed without arguments
1120 * The following attributes are parsed with arguments
1121 * aligned( const expression )
1122 * alias( string literal )
1123 * section( string literal )
1124 * format( identifier, const expression, const expression )
1125 * format_arg( const expression )
1127 static void parse_gnu_attribute(void)
1129 eat(T___attribute__);
1132 if(token.type != ')') {
1133 /* non-empty attribute list */
1136 if(token.type == T_const) {
1138 } else if(token.type == T_volatile) {
1140 } else if(token.type == T_cdecl) {
1141 /* __attribute__((cdecl)), WITH ms mode */
1143 } else if(token.type != T_IDENTIFIER) {
1144 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1147 const symbol_t *sym = token.v.symbol;
1151 gnu_attribute_kind_t kind;
1152 for(kind = 0; kind < GNU_AK_LAST; ++kind) {
1153 if(strcmp_underscore(gnu_attribute_names[kind], name) == 0)
1157 if(kind == GNU_AK_LAST) {
1158 if(warning.attribute)
1159 warningf(HERE, "'%s' attribute directive ignored", name);
1161 /* skip possible arguments */
1162 if(token.type == '(') {
1163 eat_until_matching_token(')');
1166 /* check for arguments */
1167 bool have_args = false;
1168 if(token.type == '(') {
1170 if(token.type == ')') {
1171 /* empty args are allowed */
1179 case GNU_AK_VOLATILE:
1181 case GNU_AK_STDCALL:
1182 case GNU_AK_FASTCALL:
1183 case GNU_AK_DEPRECATED:
1184 case GNU_AK_NOINLINE:
1185 case GNU_AK_NORETURN:
1188 case GNU_AK_ALWAYS_INLINE:
1191 case GNU_AK_CONSTRUCTOR:
1192 case GNU_AK_DESTRUCTOR:
1194 /* should have no arguments */
1195 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1196 eat_until_matching_token('(');
1197 /* we have already consumend '(', so we stop before ')', eat it */
1202 case GNU_AK_ALIGNED:
1203 case GNU_AK_FORMAT_ARG:
1205 /* should have arguments */
1206 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1208 parse_gnu_attribute_const_arg();
1211 case GNU_AK_SECTION:
1213 /* should have arguments */
1214 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1216 parse_gnu_attribute_string_arg();
1220 /* should have arguments */
1221 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1223 parse_gnu_attribute_format_args();
1226 /* already handled */
1230 if(token.type != ',')
1242 * Parse GNU attributes.
1244 static void parse_attributes(void)
1247 switch(token.type) {
1248 case T___attribute__: {
1249 parse_gnu_attribute();
1255 if(token.type != T_STRING_LITERAL) {
1256 parse_error_expected("while parsing assembler attribute",
1258 eat_until_matching_token('(');
1261 parse_string_literals();
1266 goto attributes_finished;
1271 attributes_finished:
1275 static designator_t *parse_designation(void)
1277 designator_t *result = NULL;
1278 designator_t *last = NULL;
1281 designator_t *designator;
1282 switch(token.type) {
1284 designator = allocate_ast_zero(sizeof(designator[0]));
1285 designator->source_position = token.source_position;
1287 add_anchor_token(']');
1288 designator->array_index = parse_constant_expression();
1289 rem_anchor_token(']');
1293 designator = allocate_ast_zero(sizeof(designator[0]));
1294 designator->source_position = token.source_position;
1296 if(token.type != T_IDENTIFIER) {
1297 parse_error_expected("while parsing designator",
1301 designator->symbol = token.v.symbol;
1309 assert(designator != NULL);
1311 last->next = designator;
1313 result = designator;
1321 static initializer_t *initializer_from_string(array_type_t *type,
1322 const string_t *const string)
1324 /* TODO: check len vs. size of array type */
1327 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1328 initializer->string.string = *string;
1333 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1334 wide_string_t *const string)
1336 /* TODO: check len vs. size of array type */
1339 initializer_t *const initializer =
1340 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1341 initializer->wide_string.string = *string;
1347 * Build an initializer from a given expression.
1349 static initializer_t *initializer_from_expression(type_t *orig_type,
1350 expression_t *expression)
1352 /* TODO check that expression is a constant expression */
1354 /* § 6.7.8.14/15 char array may be initialized by string literals */
1355 type_t *type = skip_typeref(orig_type);
1356 type_t *expr_type_orig = expression->base.type;
1357 type_t *expr_type = skip_typeref(expr_type_orig);
1358 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1359 array_type_t *const array_type = &type->array;
1360 type_t *const element_type = skip_typeref(array_type->element_type);
1362 if (element_type->kind == TYPE_ATOMIC) {
1363 atomic_type_kind_t akind = element_type->atomic.akind;
1364 switch (expression->kind) {
1365 case EXPR_STRING_LITERAL:
1366 if (akind == ATOMIC_TYPE_CHAR
1367 || akind == ATOMIC_TYPE_SCHAR
1368 || akind == ATOMIC_TYPE_UCHAR) {
1369 return initializer_from_string(array_type,
1370 &expression->string.value);
1373 case EXPR_WIDE_STRING_LITERAL: {
1374 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1375 if (get_unqualified_type(element_type) == bare_wchar_type) {
1376 return initializer_from_wide_string(array_type,
1377 &expression->wide_string.value);
1387 type_t *const res_type = semantic_assign(type, expression, "initializer",
1388 expression->base.source_position);
1389 if (res_type == NULL)
1392 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1393 result->value.value = create_implicit_cast(expression, res_type);
1399 * Checks if a given expression can be used as an constant initializer.
1401 static bool is_initializer_constant(const expression_t *expression)
1403 return is_constant_expression(expression)
1404 || is_address_constant(expression);
1408 * Parses an scalar initializer.
1410 * § 6.7.8.11; eat {} without warning
1412 static initializer_t *parse_scalar_initializer(type_t *type,
1413 bool must_be_constant)
1415 /* there might be extra {} hierarchies */
1417 while(token.type == '{') {
1420 warningf(HERE, "extra curly braces around scalar initializer");
1425 expression_t *expression = parse_assignment_expression();
1426 if(must_be_constant && !is_initializer_constant(expression)) {
1427 errorf(expression->base.source_position,
1428 "Initialisation expression '%E' is not constant\n",
1432 initializer_t *initializer = initializer_from_expression(type, expression);
1434 if(initializer == NULL) {
1435 errorf(expression->base.source_position,
1436 "expression '%E' (type '%T') doesn't match expected type '%T'",
1437 expression, expression->base.type, type);
1442 bool additional_warning_displayed = false;
1444 if(token.type == ',') {
1447 if(token.type != '}') {
1448 if(!additional_warning_displayed) {
1449 warningf(HERE, "additional elements in scalar initializer");
1450 additional_warning_displayed = true;
1461 * An entry in the type path.
1463 typedef struct type_path_entry_t type_path_entry_t;
1464 struct type_path_entry_t {
1465 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1467 size_t index; /**< For array types: the current index. */
1468 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1473 * A type path expression a position inside compound or array types.
1475 typedef struct type_path_t type_path_t;
1476 struct type_path_t {
1477 type_path_entry_t *path; /**< An flexible array containing the current path. */
1478 type_t *top_type; /**< type of the element the path points */
1479 size_t max_index; /**< largest index in outermost array */
1483 * Prints a type path for debugging.
1485 static __attribute__((unused)) void debug_print_type_path(
1486 const type_path_t *path)
1488 size_t len = ARR_LEN(path->path);
1490 for(size_t i = 0; i < len; ++i) {
1491 const type_path_entry_t *entry = & path->path[i];
1493 type_t *type = skip_typeref(entry->type);
1494 if(is_type_compound(type)) {
1495 /* in gcc mode structs can have no members */
1496 if(entry->v.compound_entry == NULL) {
1500 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1501 } else if(is_type_array(type)) {
1502 fprintf(stderr, "[%zd]", entry->v.index);
1504 fprintf(stderr, "-INVALID-");
1507 if(path->top_type != NULL) {
1508 fprintf(stderr, " (");
1509 print_type(path->top_type);
1510 fprintf(stderr, ")");
1515 * Return the top type path entry, ie. in a path
1516 * (type).a.b returns the b.
1518 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1520 size_t len = ARR_LEN(path->path);
1522 return &path->path[len-1];
1526 * Enlarge the type path by an (empty) element.
1528 static type_path_entry_t *append_to_type_path(type_path_t *path)
1530 size_t len = ARR_LEN(path->path);
1531 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1533 type_path_entry_t *result = & path->path[len];
1534 memset(result, 0, sizeof(result[0]));
1539 * Descending into a sub-type. Enter the scope of the current
1542 static void descend_into_subtype(type_path_t *path)
1544 type_t *orig_top_type = path->top_type;
1545 type_t *top_type = skip_typeref(orig_top_type);
1547 assert(is_type_compound(top_type) || is_type_array(top_type));
1549 type_path_entry_t *top = append_to_type_path(path);
1550 top->type = top_type;
1552 if(is_type_compound(top_type)) {
1553 declaration_t *declaration = top_type->compound.declaration;
1554 declaration_t *entry = declaration->scope.declarations;
1555 top->v.compound_entry = entry;
1558 path->top_type = entry->type;
1560 path->top_type = NULL;
1563 assert(is_type_array(top_type));
1566 path->top_type = top_type->array.element_type;
1571 * Pop an entry from the given type path, ie. returning from
1572 * (type).a.b to (type).a
1574 static void ascend_from_subtype(type_path_t *path)
1576 type_path_entry_t *top = get_type_path_top(path);
1578 path->top_type = top->type;
1580 size_t len = ARR_LEN(path->path);
1581 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1585 * Pop entries from the given type path until the given
1586 * path level is reached.
1588 static void ascend_to(type_path_t *path, size_t top_path_level)
1590 size_t len = ARR_LEN(path->path);
1592 while(len > top_path_level) {
1593 ascend_from_subtype(path);
1594 len = ARR_LEN(path->path);
1598 static bool walk_designator(type_path_t *path, const designator_t *designator,
1599 bool used_in_offsetof)
1601 for( ; designator != NULL; designator = designator->next) {
1602 type_path_entry_t *top = get_type_path_top(path);
1603 type_t *orig_type = top->type;
1605 type_t *type = skip_typeref(orig_type);
1607 if(designator->symbol != NULL) {
1608 symbol_t *symbol = designator->symbol;
1609 if(!is_type_compound(type)) {
1610 if(is_type_valid(type)) {
1611 errorf(designator->source_position,
1612 "'.%Y' designator used for non-compound type '%T'",
1618 declaration_t *declaration = type->compound.declaration;
1619 declaration_t *iter = declaration->scope.declarations;
1620 for( ; iter != NULL; iter = iter->next) {
1621 if(iter->symbol == symbol) {
1626 errorf(designator->source_position,
1627 "'%T' has no member named '%Y'", orig_type, symbol);
1630 if(used_in_offsetof) {
1631 type_t *real_type = skip_typeref(iter->type);
1632 if(real_type->kind == TYPE_BITFIELD) {
1633 errorf(designator->source_position,
1634 "offsetof designator '%Y' may not specify bitfield",
1640 top->type = orig_type;
1641 top->v.compound_entry = iter;
1642 orig_type = iter->type;
1644 expression_t *array_index = designator->array_index;
1645 assert(designator->array_index != NULL);
1647 if(!is_type_array(type)) {
1648 if(is_type_valid(type)) {
1649 errorf(designator->source_position,
1650 "[%E] designator used for non-array type '%T'",
1651 array_index, orig_type);
1655 if(!is_type_valid(array_index->base.type)) {
1659 long index = fold_constant(array_index);
1660 if(!used_in_offsetof) {
1662 errorf(designator->source_position,
1663 "array index [%E] must be positive", array_index);
1666 if(type->array.size_constant == true) {
1667 long array_size = type->array.size;
1668 if(index >= array_size) {
1669 errorf(designator->source_position,
1670 "designator [%E] (%d) exceeds array size %d",
1671 array_index, index, array_size);
1677 top->type = orig_type;
1678 top->v.index = (size_t) index;
1679 orig_type = type->array.element_type;
1681 path->top_type = orig_type;
1683 if(designator->next != NULL) {
1684 descend_into_subtype(path);
1693 static void advance_current_object(type_path_t *path, size_t top_path_level)
1695 type_path_entry_t *top = get_type_path_top(path);
1697 type_t *type = skip_typeref(top->type);
1698 if(is_type_union(type)) {
1699 /* in unions only the first element is initialized */
1700 top->v.compound_entry = NULL;
1701 } else if(is_type_struct(type)) {
1702 declaration_t *entry = top->v.compound_entry;
1704 entry = entry->next;
1705 top->v.compound_entry = entry;
1707 path->top_type = entry->type;
1711 assert(is_type_array(type));
1715 if(!type->array.size_constant || top->v.index < type->array.size) {
1720 /* we're past the last member of the current sub-aggregate, try if we
1721 * can ascend in the type hierarchy and continue with another subobject */
1722 size_t len = ARR_LEN(path->path);
1724 if(len > top_path_level) {
1725 ascend_from_subtype(path);
1726 advance_current_object(path, top_path_level);
1728 path->top_type = NULL;
1733 * skip until token is found.
1735 static void skip_until(int type) {
1736 while(token.type != type) {
1737 if(token.type == T_EOF)
1744 * skip any {...} blocks until a closing braket is reached.
1746 static void skip_initializers(void)
1748 if(token.type == '{')
1751 while(token.type != '}') {
1752 if(token.type == T_EOF)
1754 if(token.type == '{') {
1762 static initializer_t *create_empty_initializer(void)
1764 static initializer_t empty_initializer
1765 = { .list = { { INITIALIZER_LIST }, 0 } };
1766 return &empty_initializer;
1770 * Parse a part of an initialiser for a struct or union,
1772 static initializer_t *parse_sub_initializer(type_path_t *path,
1773 type_t *outer_type, size_t top_path_level,
1774 parse_initializer_env_t *env)
1776 if(token.type == '}') {
1777 /* empty initializer */
1778 return create_empty_initializer();
1781 type_t *orig_type = path->top_type;
1782 type_t *type = NULL;
1784 if (orig_type == NULL) {
1785 /* We are initializing an empty compound. */
1787 type = skip_typeref(orig_type);
1789 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1790 * initializers in this case. */
1791 if(!is_type_valid(type)) {
1792 skip_initializers();
1793 return create_empty_initializer();
1797 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1800 designator_t *designator = NULL;
1801 if(token.type == '.' || token.type == '[') {
1802 designator = parse_designation();
1804 /* reset path to toplevel, evaluate designator from there */
1805 ascend_to(path, top_path_level);
1806 if(!walk_designator(path, designator, false)) {
1807 /* can't continue after designation error */
1811 initializer_t *designator_initializer
1812 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1813 designator_initializer->designator.designator = designator;
1814 ARR_APP1(initializer_t*, initializers, designator_initializer);
1819 if(token.type == '{') {
1820 if(type != NULL && is_type_scalar(type)) {
1821 sub = parse_scalar_initializer(type, env->must_be_constant);
1825 if (env->declaration != NULL)
1826 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1827 env->declaration->symbol);
1829 errorf(HERE, "extra brace group at end of initializer");
1831 descend_into_subtype(path);
1833 add_anchor_token('}');
1834 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1836 rem_anchor_token('}');
1839 ascend_from_subtype(path);
1843 goto error_parse_next;
1847 /* must be an expression */
1848 expression_t *expression = parse_assignment_expression();
1850 if(env->must_be_constant && !is_initializer_constant(expression)) {
1851 errorf(expression->base.source_position,
1852 "Initialisation expression '%E' is not constant\n",
1857 /* we are already outside, ... */
1861 /* handle { "string" } special case */
1862 if((expression->kind == EXPR_STRING_LITERAL
1863 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1864 && outer_type != NULL) {
1865 sub = initializer_from_expression(outer_type, expression);
1867 if(token.type == ',') {
1870 if(token.type != '}') {
1871 warningf(HERE, "excessive elements in initializer for type '%T'",
1874 /* TODO: eat , ... */
1879 /* descend into subtypes until expression matches type */
1881 orig_type = path->top_type;
1882 type = skip_typeref(orig_type);
1884 sub = initializer_from_expression(orig_type, expression);
1888 if(!is_type_valid(type)) {
1891 if(is_type_scalar(type)) {
1892 errorf(expression->base.source_position,
1893 "expression '%E' doesn't match expected type '%T'",
1894 expression, orig_type);
1898 descend_into_subtype(path);
1902 /* update largest index of top array */
1903 const type_path_entry_t *first = &path->path[0];
1904 type_t *first_type = first->type;
1905 first_type = skip_typeref(first_type);
1906 if(is_type_array(first_type)) {
1907 size_t index = first->v.index;
1908 if(index > path->max_index)
1909 path->max_index = index;
1913 /* append to initializers list */
1914 ARR_APP1(initializer_t*, initializers, sub);
1917 if(env->declaration != NULL)
1918 warningf(HERE, "excess elements in struct initializer for '%Y'",
1919 env->declaration->symbol);
1921 warningf(HERE, "excess elements in struct initializer");
1925 if(token.type == '}') {
1929 if(token.type == '}') {
1934 /* advance to the next declaration if we are not at the end */
1935 advance_current_object(path, top_path_level);
1936 orig_type = path->top_type;
1937 if(orig_type != NULL)
1938 type = skip_typeref(orig_type);
1944 size_t len = ARR_LEN(initializers);
1945 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1946 initializer_t *result = allocate_ast_zero(size);
1947 result->kind = INITIALIZER_LIST;
1948 result->list.len = len;
1949 memcpy(&result->list.initializers, initializers,
1950 len * sizeof(initializers[0]));
1952 DEL_ARR_F(initializers);
1953 ascend_to(path, top_path_level);
1958 skip_initializers();
1959 DEL_ARR_F(initializers);
1960 ascend_to(path, top_path_level);
1965 * Parses an initializer. Parsers either a compound literal
1966 * (env->declaration == NULL) or an initializer of a declaration.
1968 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1970 type_t *type = skip_typeref(env->type);
1971 initializer_t *result = NULL;
1974 if(is_type_scalar(type)) {
1975 result = parse_scalar_initializer(type, env->must_be_constant);
1976 } else if(token.type == '{') {
1980 memset(&path, 0, sizeof(path));
1981 path.top_type = env->type;
1982 path.path = NEW_ARR_F(type_path_entry_t, 0);
1984 descend_into_subtype(&path);
1986 add_anchor_token('}');
1987 result = parse_sub_initializer(&path, env->type, 1, env);
1988 rem_anchor_token('}');
1990 max_index = path.max_index;
1991 DEL_ARR_F(path.path);
1995 /* parse_scalar_initializer() also works in this case: we simply
1996 * have an expression without {} around it */
1997 result = parse_scalar_initializer(type, env->must_be_constant);
2000 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2001 * the array type size */
2002 if(is_type_array(type) && type->array.size_expression == NULL
2003 && result != NULL) {
2005 switch (result->kind) {
2006 case INITIALIZER_LIST:
2007 size = max_index + 1;
2010 case INITIALIZER_STRING:
2011 size = result->string.string.size;
2014 case INITIALIZER_WIDE_STRING:
2015 size = result->wide_string.string.size;
2019 internal_errorf(HERE, "invalid initializer type");
2022 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2023 cnst->base.type = type_size_t;
2024 cnst->conste.v.int_value = size;
2026 type_t *new_type = duplicate_type(type);
2028 new_type->array.size_expression = cnst;
2029 new_type->array.size_constant = true;
2030 new_type->array.size = size;
2031 env->type = new_type;
2039 static declaration_t *append_declaration(declaration_t *declaration);
2041 static declaration_t *parse_compound_type_specifier(bool is_struct)
2049 symbol_t *symbol = NULL;
2050 declaration_t *declaration = NULL;
2052 if (token.type == T___attribute__) {
2057 if(token.type == T_IDENTIFIER) {
2058 symbol = token.v.symbol;
2062 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2064 declaration = get_declaration(symbol, NAMESPACE_UNION);
2066 } else if(token.type != '{') {
2068 parse_error_expected("while parsing struct type specifier",
2069 T_IDENTIFIER, '{', 0);
2071 parse_error_expected("while parsing union type specifier",
2072 T_IDENTIFIER, '{', 0);
2078 if(declaration == NULL) {
2079 declaration = allocate_declaration_zero();
2080 declaration->namespc =
2081 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2082 declaration->source_position = token.source_position;
2083 declaration->symbol = symbol;
2084 declaration->parent_scope = scope;
2085 if (symbol != NULL) {
2086 environment_push(declaration);
2088 append_declaration(declaration);
2091 if(token.type == '{') {
2092 if(declaration->init.is_defined) {
2093 assert(symbol != NULL);
2094 errorf(HERE, "multiple definitions of '%s %Y'",
2095 is_struct ? "struct" : "union", symbol);
2096 declaration->scope.declarations = NULL;
2098 declaration->init.is_defined = true;
2100 parse_compound_type_entries(declaration);
2107 static void parse_enum_entries(type_t *const enum_type)
2111 if(token.type == '}') {
2113 errorf(HERE, "empty enum not allowed");
2117 add_anchor_token('}');
2119 if(token.type != T_IDENTIFIER) {
2120 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2122 rem_anchor_token('}');
2126 declaration_t *const entry = allocate_declaration_zero();
2127 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2128 entry->type = enum_type;
2129 entry->symbol = token.v.symbol;
2130 entry->source_position = token.source_position;
2133 if(token.type == '=') {
2135 expression_t *value = parse_constant_expression();
2137 value = create_implicit_cast(value, enum_type);
2138 entry->init.enum_value = value;
2143 record_declaration(entry);
2145 if(token.type != ',')
2148 } while(token.type != '}');
2149 rem_anchor_token('}');
2157 static type_t *parse_enum_specifier(void)
2161 declaration_t *declaration;
2164 if(token.type == T_IDENTIFIER) {
2165 symbol = token.v.symbol;
2168 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2169 } else if(token.type != '{') {
2170 parse_error_expected("while parsing enum type specifier",
2171 T_IDENTIFIER, '{', 0);
2178 if(declaration == NULL) {
2179 declaration = allocate_declaration_zero();
2180 declaration->namespc = NAMESPACE_ENUM;
2181 declaration->source_position = token.source_position;
2182 declaration->symbol = symbol;
2183 declaration->parent_scope = scope;
2186 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2187 type->enumt.declaration = declaration;
2189 if(token.type == '{') {
2190 if(declaration->init.is_defined) {
2191 errorf(HERE, "multiple definitions of enum %Y", symbol);
2193 if (symbol != NULL) {
2194 environment_push(declaration);
2196 append_declaration(declaration);
2197 declaration->init.is_defined = 1;
2199 parse_enum_entries(type);
2207 * if a symbol is a typedef to another type, return true
2209 static bool is_typedef_symbol(symbol_t *symbol)
2211 const declaration_t *const declaration =
2212 get_declaration(symbol, NAMESPACE_NORMAL);
2214 declaration != NULL &&
2215 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2218 static type_t *parse_typeof(void)
2225 add_anchor_token(')');
2227 expression_t *expression = NULL;
2230 switch(token.type) {
2231 case T___extension__:
2232 /* this can be a prefix to a typename or an expression */
2233 /* we simply eat it now. */
2236 } while(token.type == T___extension__);
2240 if(is_typedef_symbol(token.v.symbol)) {
2241 type = parse_typename();
2243 expression = parse_expression();
2244 type = expression->base.type;
2249 type = parse_typename();
2253 expression = parse_expression();
2254 type = expression->base.type;
2258 rem_anchor_token(')');
2261 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2262 typeof_type->typeoft.expression = expression;
2263 typeof_type->typeoft.typeof_type = type;
2271 SPECIFIER_SIGNED = 1 << 0,
2272 SPECIFIER_UNSIGNED = 1 << 1,
2273 SPECIFIER_LONG = 1 << 2,
2274 SPECIFIER_INT = 1 << 3,
2275 SPECIFIER_DOUBLE = 1 << 4,
2276 SPECIFIER_CHAR = 1 << 5,
2277 SPECIFIER_SHORT = 1 << 6,
2278 SPECIFIER_LONG_LONG = 1 << 7,
2279 SPECIFIER_FLOAT = 1 << 8,
2280 SPECIFIER_BOOL = 1 << 9,
2281 SPECIFIER_VOID = 1 << 10,
2282 SPECIFIER_INT8 = 1 << 11,
2283 SPECIFIER_INT16 = 1 << 12,
2284 SPECIFIER_INT32 = 1 << 13,
2285 SPECIFIER_INT64 = 1 << 14,
2286 SPECIFIER_INT128 = 1 << 15,
2287 #ifdef PROVIDE_COMPLEX
2288 SPECIFIER_COMPLEX = 1 << 16,
2289 SPECIFIER_IMAGINARY = 1 << 17,
2293 static type_t *create_builtin_type(symbol_t *const symbol,
2294 type_t *const real_type)
2296 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2297 type->builtin.symbol = symbol;
2298 type->builtin.real_type = real_type;
2300 type_t *result = typehash_insert(type);
2301 if (type != result) {
2308 static type_t *get_typedef_type(symbol_t *symbol)
2310 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2311 if(declaration == NULL
2312 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2315 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2316 type->typedeft.declaration = declaration;
2322 * check for the allowed MS alignment values.
2324 static bool check_elignment_value(long long intvalue) {
2325 if(intvalue < 1 || intvalue > 8192) {
2326 errorf(HERE, "illegal alignment value");
2329 unsigned v = (unsigned)intvalue;
2330 for(unsigned i = 1; i <= 8192; i += i) {
2334 errorf(HERE, "alignment must be power of two");
2338 #define DET_MOD(name, tag) do { \
2339 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2340 *modifiers |= tag; \
2343 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2345 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2348 if(token.type == T_restrict) {
2350 DET_MOD(restrict, DM_RESTRICT);
2352 } else if(token.type != T_IDENTIFIER)
2354 symbol_t *symbol = token.v.symbol;
2355 if(symbol == sym_align) {
2358 if(token.type != T_INTEGER)
2360 if(check_elignment_value(token.v.intvalue)) {
2361 if(specifiers->alignment != 0)
2362 warningf(HERE, "align used more than once");
2363 specifiers->alignment = (unsigned char)token.v.intvalue;
2367 } else if(symbol == sym_allocate) {
2370 if(token.type != T_IDENTIFIER)
2372 (void)token.v.symbol;
2374 } else if(symbol == sym_dllimport) {
2376 DET_MOD(dllimport, DM_DLLIMPORT);
2377 } else if(symbol == sym_dllexport) {
2379 DET_MOD(dllexport, DM_DLLEXPORT);
2380 } else if(symbol == sym_thread) {
2382 DET_MOD(thread, DM_THREAD);
2383 } else if(symbol == sym_naked) {
2385 DET_MOD(naked, DM_NAKED);
2386 } else if(symbol == sym_noinline) {
2388 DET_MOD(noinline, DM_NOINLINE);
2389 } else if(symbol == sym_noreturn) {
2391 DET_MOD(noreturn, DM_NORETURN);
2392 } else if(symbol == sym_nothrow) {
2394 DET_MOD(nothrow, DM_NOTHROW);
2395 } else if(symbol == sym_novtable) {
2397 DET_MOD(novtable, DM_NOVTABLE);
2398 } else if(symbol == sym_property) {
2402 bool is_get = false;
2403 if(token.type != T_IDENTIFIER)
2405 if(token.v.symbol == sym_get) {
2407 } else if(token.v.symbol == sym_put) {
2409 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2414 if(token.type != T_IDENTIFIER)
2417 if(specifiers->get_property_sym != NULL) {
2418 errorf(HERE, "get property name already specified");
2420 specifiers->get_property_sym = token.v.symbol;
2423 if(specifiers->put_property_sym != NULL) {
2424 errorf(HERE, "put property name already specified");
2426 specifiers->put_property_sym = token.v.symbol;
2430 if(token.type == ',') {
2437 } else if(symbol == sym_selectany) {
2439 DET_MOD(selectany, DM_SELECTANY);
2440 } else if(symbol == sym_uuid) {
2443 if(token.type != T_STRING_LITERAL)
2447 } else if(symbol == sym_deprecated) {
2449 if(specifiers->deprecated != 0)
2450 warningf(HERE, "deprecated used more than once");
2451 specifiers->deprecated = 1;
2452 if(token.type == '(') {
2454 if(token.type == T_STRING_LITERAL) {
2455 specifiers->deprecated_string = token.v.string.begin;
2458 errorf(HERE, "string literal expected");
2462 } else if(symbol == sym_noalias) {
2464 DET_MOD(noalias, DM_NOALIAS);
2466 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2468 if(token.type == '(')
2472 if (token.type == ',')
2479 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2481 type_t *type = NULL;
2482 unsigned type_qualifiers = 0;
2483 unsigned type_specifiers = 0;
2486 specifiers->source_position = token.source_position;
2489 switch(token.type) {
2492 #define MATCH_STORAGE_CLASS(token, class) \
2494 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2495 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2497 specifiers->declared_storage_class = class; \
2501 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2502 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2503 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2504 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2505 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2510 add_anchor_token(')');
2511 parse_microsoft_extended_decl_modifier(specifiers);
2512 rem_anchor_token(')');
2517 switch (specifiers->declared_storage_class) {
2518 case STORAGE_CLASS_NONE:
2519 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2522 case STORAGE_CLASS_EXTERN:
2523 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2526 case STORAGE_CLASS_STATIC:
2527 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2531 errorf(HERE, "multiple storage classes in declaration specifiers");
2537 /* type qualifiers */
2538 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2540 type_qualifiers |= qualifier; \
2544 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2545 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2546 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2547 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2548 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2549 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2550 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2551 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2553 case T___extension__:
2558 /* type specifiers */
2559 #define MATCH_SPECIFIER(token, specifier, name) \
2562 if(type_specifiers & specifier) { \
2563 errorf(HERE, "multiple " name " type specifiers given"); \
2565 type_specifiers |= specifier; \
2569 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2570 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2571 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2572 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2573 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2574 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2575 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2576 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2577 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2578 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2579 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2580 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2581 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2582 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2583 #ifdef PROVIDE_COMPLEX
2584 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2585 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2587 case T__forceinline:
2588 /* only in microsoft mode */
2589 specifiers->decl_modifiers |= DM_FORCEINLINE;
2593 specifiers->is_inline = true;
2598 if(type_specifiers & SPECIFIER_LONG_LONG) {
2599 errorf(HERE, "multiple type specifiers given");
2600 } else if(type_specifiers & SPECIFIER_LONG) {
2601 type_specifiers |= SPECIFIER_LONG_LONG;
2603 type_specifiers |= SPECIFIER_LONG;
2608 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2610 type->compound.declaration = parse_compound_type_specifier(true);
2614 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2616 type->compound.declaration = parse_compound_type_specifier(false);
2620 type = parse_enum_specifier();
2623 type = parse_typeof();
2625 case T___builtin_va_list:
2626 type = duplicate_type(type_valist);
2630 case T___attribute__:
2634 case T_IDENTIFIER: {
2635 /* only parse identifier if we haven't found a type yet */
2636 if(type != NULL || type_specifiers != 0)
2637 goto finish_specifiers;
2639 type_t *typedef_type = get_typedef_type(token.v.symbol);
2641 if(typedef_type == NULL)
2642 goto finish_specifiers;
2645 type = typedef_type;
2649 /* function specifier */
2651 goto finish_specifiers;
2658 atomic_type_kind_t atomic_type;
2660 /* match valid basic types */
2661 switch(type_specifiers) {
2662 case SPECIFIER_VOID:
2663 atomic_type = ATOMIC_TYPE_VOID;
2665 case SPECIFIER_CHAR:
2666 atomic_type = ATOMIC_TYPE_CHAR;
2668 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2669 atomic_type = ATOMIC_TYPE_SCHAR;
2671 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2672 atomic_type = ATOMIC_TYPE_UCHAR;
2674 case SPECIFIER_SHORT:
2675 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2676 case SPECIFIER_SHORT | SPECIFIER_INT:
2677 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2678 atomic_type = ATOMIC_TYPE_SHORT;
2680 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2681 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2682 atomic_type = ATOMIC_TYPE_USHORT;
2685 case SPECIFIER_SIGNED:
2686 case SPECIFIER_SIGNED | SPECIFIER_INT:
2687 atomic_type = ATOMIC_TYPE_INT;
2689 case SPECIFIER_UNSIGNED:
2690 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2691 atomic_type = ATOMIC_TYPE_UINT;
2693 case SPECIFIER_LONG:
2694 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2695 case SPECIFIER_LONG | SPECIFIER_INT:
2696 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2697 atomic_type = ATOMIC_TYPE_LONG;
2699 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2700 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2701 atomic_type = ATOMIC_TYPE_ULONG;
2703 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2704 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2705 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2706 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2708 atomic_type = ATOMIC_TYPE_LONGLONG;
2710 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2711 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2713 atomic_type = ATOMIC_TYPE_ULONGLONG;
2716 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2717 atomic_type = unsigned_int8_type_kind;
2720 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2721 atomic_type = unsigned_int16_type_kind;
2724 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2725 atomic_type = unsigned_int32_type_kind;
2728 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2729 atomic_type = unsigned_int64_type_kind;
2732 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2733 atomic_type = unsigned_int128_type_kind;
2736 case SPECIFIER_INT8:
2737 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2738 atomic_type = int8_type_kind;
2741 case SPECIFIER_INT16:
2742 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2743 atomic_type = int16_type_kind;
2746 case SPECIFIER_INT32:
2747 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2748 atomic_type = int32_type_kind;
2751 case SPECIFIER_INT64:
2752 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2753 atomic_type = int64_type_kind;
2756 case SPECIFIER_INT128:
2757 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2758 atomic_type = int128_type_kind;
2761 case SPECIFIER_FLOAT:
2762 atomic_type = ATOMIC_TYPE_FLOAT;
2764 case SPECIFIER_DOUBLE:
2765 atomic_type = ATOMIC_TYPE_DOUBLE;
2767 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2768 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2770 case SPECIFIER_BOOL:
2771 atomic_type = ATOMIC_TYPE_BOOL;
2773 #ifdef PROVIDE_COMPLEX
2774 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2775 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2777 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2778 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2780 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2781 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2783 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2784 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2786 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2787 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2789 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2790 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2794 /* invalid specifier combination, give an error message */
2795 if(type_specifiers == 0) {
2796 if (! strict_mode) {
2797 if (warning.implicit_int) {
2798 warningf(HERE, "no type specifiers in declaration, using 'int'");
2800 atomic_type = ATOMIC_TYPE_INT;
2803 errorf(HERE, "no type specifiers given in declaration");
2805 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2806 (type_specifiers & SPECIFIER_UNSIGNED)) {
2807 errorf(HERE, "signed and unsigned specifiers gives");
2808 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2809 errorf(HERE, "only integer types can be signed or unsigned");
2811 errorf(HERE, "multiple datatypes in declaration");
2813 atomic_type = ATOMIC_TYPE_INVALID;
2816 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2817 type->atomic.akind = atomic_type;
2820 if(type_specifiers != 0) {
2821 errorf(HERE, "multiple datatypes in declaration");
2825 type->base.qualifiers = type_qualifiers;
2826 /* FIXME: check type qualifiers here */
2828 type_t *result = typehash_insert(type);
2829 if(newtype && result != type) {
2833 specifiers->type = result;
2838 static type_qualifiers_t parse_type_qualifiers(void)
2840 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2843 switch(token.type) {
2844 /* type qualifiers */
2845 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2846 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2847 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2848 /* microsoft extended type modifiers */
2849 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2850 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2851 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2852 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2853 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2856 return type_qualifiers;
2861 static declaration_t *parse_identifier_list(void)
2863 declaration_t *declarations = NULL;
2864 declaration_t *last_declaration = NULL;
2866 declaration_t *const declaration = allocate_declaration_zero();
2867 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2868 declaration->source_position = token.source_position;
2869 declaration->symbol = token.v.symbol;
2872 if(last_declaration != NULL) {
2873 last_declaration->next = declaration;
2875 declarations = declaration;
2877 last_declaration = declaration;
2879 if(token.type != ',')
2882 } while(token.type == T_IDENTIFIER);
2884 return declarations;
2887 static void semantic_parameter(declaration_t *declaration)
2889 /* TODO: improve error messages */
2891 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2892 errorf(HERE, "typedef not allowed in parameter list");
2893 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2894 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2895 errorf(HERE, "parameter may only have none or register storage class");
2898 type_t *const orig_type = declaration->type;
2899 type_t * type = skip_typeref(orig_type);
2901 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2902 * into a pointer. § 6.7.5.3 (7) */
2903 if (is_type_array(type)) {
2904 type_t *const element_type = type->array.element_type;
2906 type = make_pointer_type(element_type, type->base.qualifiers);
2908 declaration->type = type;
2911 if(is_type_incomplete(type)) {
2912 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2913 orig_type, declaration->symbol);
2917 static declaration_t *parse_parameter(void)
2919 declaration_specifiers_t specifiers;
2920 memset(&specifiers, 0, sizeof(specifiers));
2922 parse_declaration_specifiers(&specifiers);
2924 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2926 semantic_parameter(declaration);
2931 static declaration_t *parse_parameters(function_type_t *type)
2933 if(token.type == T_IDENTIFIER) {
2934 symbol_t *symbol = token.v.symbol;
2935 if(!is_typedef_symbol(symbol)) {
2936 type->kr_style_parameters = true;
2937 return parse_identifier_list();
2941 if(token.type == ')') {
2942 type->unspecified_parameters = 1;
2945 if(token.type == T_void && look_ahead(1)->type == ')') {
2950 declaration_t *declarations = NULL;
2951 declaration_t *declaration;
2952 declaration_t *last_declaration = NULL;
2953 function_parameter_t *parameter;
2954 function_parameter_t *last_parameter = NULL;
2957 switch(token.type) {
2961 return declarations;
2964 case T___extension__:
2966 declaration = parse_parameter();
2968 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2969 memset(parameter, 0, sizeof(parameter[0]));
2970 parameter->type = declaration->type;
2972 if(last_parameter != NULL) {
2973 last_declaration->next = declaration;
2974 last_parameter->next = parameter;
2976 type->parameters = parameter;
2977 declarations = declaration;
2979 last_parameter = parameter;
2980 last_declaration = declaration;
2984 return declarations;
2986 if(token.type != ',')
2987 return declarations;
2997 } construct_type_kind_t;
2999 typedef struct construct_type_t construct_type_t;
3000 struct construct_type_t {
3001 construct_type_kind_t kind;
3002 construct_type_t *next;
3005 typedef struct parsed_pointer_t parsed_pointer_t;
3006 struct parsed_pointer_t {
3007 construct_type_t construct_type;
3008 type_qualifiers_t type_qualifiers;
3011 typedef struct construct_function_type_t construct_function_type_t;
3012 struct construct_function_type_t {
3013 construct_type_t construct_type;
3014 type_t *function_type;
3017 typedef struct parsed_array_t parsed_array_t;
3018 struct parsed_array_t {
3019 construct_type_t construct_type;
3020 type_qualifiers_t type_qualifiers;
3026 typedef struct construct_base_type_t construct_base_type_t;
3027 struct construct_base_type_t {
3028 construct_type_t construct_type;
3032 static construct_type_t *parse_pointer_declarator(void)
3036 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3037 memset(pointer, 0, sizeof(pointer[0]));
3038 pointer->construct_type.kind = CONSTRUCT_POINTER;
3039 pointer->type_qualifiers = parse_type_qualifiers();
3041 return (construct_type_t*) pointer;
3044 static construct_type_t *parse_array_declarator(void)
3047 add_anchor_token(']');
3049 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3050 memset(array, 0, sizeof(array[0]));
3051 array->construct_type.kind = CONSTRUCT_ARRAY;
3053 if(token.type == T_static) {
3054 array->is_static = true;
3058 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3059 if(type_qualifiers != 0) {
3060 if(token.type == T_static) {
3061 array->is_static = true;
3065 array->type_qualifiers = type_qualifiers;
3067 if(token.type == '*' && look_ahead(1)->type == ']') {
3068 array->is_variable = true;
3070 } else if(token.type != ']') {
3071 array->size = parse_assignment_expression();
3074 rem_anchor_token(']');
3077 return (construct_type_t*) array;
3082 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3085 add_anchor_token(')');
3088 if(declaration != NULL) {
3089 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
3091 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
3094 declaration_t *parameters = parse_parameters(&type->function);
3095 if(declaration != NULL) {
3096 declaration->scope.declarations = parameters;
3099 construct_function_type_t *construct_function_type =
3100 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3101 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3102 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3103 construct_function_type->function_type = type;
3105 rem_anchor_token(')');
3109 return (construct_type_t*) construct_function_type;
3112 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3113 bool may_be_abstract)
3115 /* construct a single linked list of construct_type_t's which describe
3116 * how to construct the final declarator type */
3117 construct_type_t *first = NULL;
3118 construct_type_t *last = NULL;
3121 while(token.type == '*') {
3122 construct_type_t *type = parse_pointer_declarator();
3133 /* TODO: find out if this is correct */
3136 construct_type_t *inner_types = NULL;
3138 switch(token.type) {
3140 if(declaration == NULL) {
3141 errorf(HERE, "no identifier expected in typename");
3143 declaration->symbol = token.v.symbol;
3144 declaration->source_position = token.source_position;
3150 add_anchor_token(')');
3151 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3152 rem_anchor_token(')');
3158 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3159 /* avoid a loop in the outermost scope, because eat_statement doesn't
3161 if(token.type == '}' && current_function == NULL) {
3169 construct_type_t *p = last;
3172 construct_type_t *type;
3173 switch(token.type) {
3175 type = parse_function_declarator(declaration);
3178 type = parse_array_declarator();
3181 goto declarator_finished;
3184 /* insert in the middle of the list (behind p) */
3186 type->next = p->next;
3197 declarator_finished:
3200 /* append inner_types at the end of the list, we don't to set last anymore
3201 * as it's not needed anymore */
3203 assert(first == NULL);
3204 first = inner_types;
3206 last->next = inner_types;
3214 static type_t *construct_declarator_type(construct_type_t *construct_list,
3217 construct_type_t *iter = construct_list;
3218 for( ; iter != NULL; iter = iter->next) {
3219 switch(iter->kind) {
3220 case CONSTRUCT_INVALID:
3221 internal_errorf(HERE, "invalid type construction found");
3222 case CONSTRUCT_FUNCTION: {
3223 construct_function_type_t *construct_function_type
3224 = (construct_function_type_t*) iter;
3226 type_t *function_type = construct_function_type->function_type;
3228 function_type->function.return_type = type;
3230 type_t *skipped_return_type = skip_typeref(type);
3231 if (is_type_function(skipped_return_type)) {
3232 errorf(HERE, "function returning function is not allowed");
3233 type = type_error_type;
3234 } else if (is_type_array(skipped_return_type)) {
3235 errorf(HERE, "function returning array is not allowed");
3236 type = type_error_type;
3238 type = function_type;
3243 case CONSTRUCT_POINTER: {
3244 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3245 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3246 pointer_type->pointer.points_to = type;
3247 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3249 type = pointer_type;
3253 case CONSTRUCT_ARRAY: {
3254 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3255 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3257 expression_t *size_expression = parsed_array->size;
3258 if(size_expression != NULL) {
3260 = create_implicit_cast(size_expression, type_size_t);
3263 array_type->base.qualifiers = parsed_array->type_qualifiers;
3264 array_type->array.element_type = type;
3265 array_type->array.is_static = parsed_array->is_static;
3266 array_type->array.is_variable = parsed_array->is_variable;
3267 array_type->array.size_expression = size_expression;
3269 if(size_expression != NULL) {
3270 if(is_constant_expression(size_expression)) {
3271 array_type->array.size_constant = true;
3272 array_type->array.size
3273 = fold_constant(size_expression);
3275 array_type->array.is_vla = true;
3279 type_t *skipped_type = skip_typeref(type);
3280 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3281 errorf(HERE, "array of void is not allowed");
3282 type = type_error_type;
3290 type_t *hashed_type = typehash_insert(type);
3291 if(hashed_type != type) {
3292 /* the function type was constructed earlier freeing it here will
3293 * destroy other types... */
3294 if(iter->kind != CONSTRUCT_FUNCTION) {
3304 static declaration_t *parse_declarator(
3305 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3307 declaration_t *const declaration = allocate_declaration_zero();
3308 declaration->declared_storage_class = specifiers->declared_storage_class;
3309 declaration->modifiers = specifiers->decl_modifiers;
3310 declaration->deprecated = specifiers->deprecated;
3311 declaration->deprecated_string = specifiers->deprecated_string;
3312 declaration->get_property_sym = specifiers->get_property_sym;
3313 declaration->put_property_sym = specifiers->put_property_sym;
3314 declaration->is_inline = specifiers->is_inline;
3316 declaration->storage_class = specifiers->declared_storage_class;
3317 if(declaration->storage_class == STORAGE_CLASS_NONE
3318 && scope != global_scope) {
3319 declaration->storage_class = STORAGE_CLASS_AUTO;
3322 if(specifiers->alignment != 0) {
3323 /* TODO: add checks here */
3324 declaration->alignment = specifiers->alignment;
3327 construct_type_t *construct_type
3328 = parse_inner_declarator(declaration, may_be_abstract);
3329 type_t *const type = specifiers->type;
3330 declaration->type = construct_declarator_type(construct_type, type);
3332 if(construct_type != NULL) {
3333 obstack_free(&temp_obst, construct_type);
3339 static type_t *parse_abstract_declarator(type_t *base_type)
3341 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3343 type_t *result = construct_declarator_type(construct_type, base_type);
3344 if(construct_type != NULL) {
3345 obstack_free(&temp_obst, construct_type);
3351 static declaration_t *append_declaration(declaration_t* const declaration)
3353 if (last_declaration != NULL) {
3354 last_declaration->next = declaration;
3356 scope->declarations = declaration;
3358 last_declaration = declaration;
3363 * Check if the declaration of main is suspicious. main should be a
3364 * function with external linkage, returning int, taking either zero
3365 * arguments, two, or three arguments of appropriate types, ie.
3367 * int main([ int argc, char **argv [, char **env ] ]).
3369 * @param decl the declaration to check
3370 * @param type the function type of the declaration
3372 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3374 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3375 warningf(decl->source_position, "'main' is normally a non-static function");
3377 if (skip_typeref(func_type->return_type) != type_int) {
3378 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3380 const function_parameter_t *parm = func_type->parameters;
3382 type_t *const first_type = parm->type;
3383 if (!types_compatible(skip_typeref(first_type), type_int)) {
3384 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3388 type_t *const second_type = parm->type;
3389 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3390 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3394 type_t *const third_type = parm->type;
3395 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3396 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3400 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3404 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3410 * Check if a symbol is the equal to "main".
3412 static bool is_sym_main(const symbol_t *const sym)
3414 return strcmp(sym->string, "main") == 0;
3417 static declaration_t *internal_record_declaration(
3418 declaration_t *const declaration,
3419 const bool is_function_definition)
3421 const symbol_t *const symbol = declaration->symbol;
3422 const namespace_t namespc = (namespace_t)declaration->namespc;
3424 type_t *const orig_type = declaration->type;
3425 type_t *const type = skip_typeref(orig_type);
3426 if (is_type_function(type) &&
3427 type->function.unspecified_parameters &&
3428 warning.strict_prototypes) {
3429 warningf(declaration->source_position,
3430 "function declaration '%#T' is not a prototype",
3431 orig_type, declaration->symbol);
3434 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3435 check_type_of_main(declaration, &type->function);
3438 assert(declaration->symbol != NULL);
3439 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3441 assert(declaration != previous_declaration);
3442 if (previous_declaration != NULL) {
3443 if (previous_declaration->parent_scope == scope) {
3444 /* can happen for K&R style declarations */
3445 if(previous_declaration->type == NULL) {
3446 previous_declaration->type = declaration->type;
3449 const type_t *prev_type = skip_typeref(previous_declaration->type);
3450 if (!types_compatible(type, prev_type)) {
3451 errorf(declaration->source_position,
3452 "declaration '%#T' is incompatible with "
3453 "previous declaration '%#T'",
3454 orig_type, symbol, previous_declaration->type, symbol);
3455 errorf(previous_declaration->source_position,
3456 "previous declaration of '%Y' was here", symbol);
3458 unsigned old_storage_class = previous_declaration->storage_class;
3459 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3460 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3461 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3462 return previous_declaration;
3465 unsigned new_storage_class = declaration->storage_class;
3467 if(is_type_incomplete(prev_type)) {
3468 previous_declaration->type = type;
3472 /* pretend no storage class means extern for function
3473 * declarations (except if the previous declaration is neither
3474 * none nor extern) */
3475 if (is_type_function(type)) {
3476 switch (old_storage_class) {
3477 case STORAGE_CLASS_NONE:
3478 old_storage_class = STORAGE_CLASS_EXTERN;
3480 case STORAGE_CLASS_EXTERN:
3481 if (is_function_definition) {
3482 if (warning.missing_prototypes &&
3483 prev_type->function.unspecified_parameters &&
3484 !is_sym_main(symbol)) {
3485 warningf(declaration->source_position,
3486 "no previous prototype for '%#T'",
3489 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3490 new_storage_class = STORAGE_CLASS_EXTERN;
3498 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3499 new_storage_class == STORAGE_CLASS_EXTERN) {
3500 warn_redundant_declaration:
3501 if (warning.redundant_decls) {
3502 warningf(declaration->source_position,
3503 "redundant declaration for '%Y'", symbol);
3504 warningf(previous_declaration->source_position,
3505 "previous declaration of '%Y' was here",
3508 } else if (current_function == NULL) {
3509 if (old_storage_class != STORAGE_CLASS_STATIC &&
3510 new_storage_class == STORAGE_CLASS_STATIC) {
3511 errorf(declaration->source_position,
3512 "static declaration of '%Y' follows non-static declaration",
3514 errorf(previous_declaration->source_position,
3515 "previous declaration of '%Y' was here", symbol);
3517 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3518 goto warn_redundant_declaration;
3520 if (new_storage_class == STORAGE_CLASS_NONE) {
3521 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3522 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3526 if (old_storage_class == new_storage_class) {
3527 errorf(declaration->source_position,
3528 "redeclaration of '%Y'", symbol);
3530 errorf(declaration->source_position,
3531 "redeclaration of '%Y' with different linkage",
3534 errorf(previous_declaration->source_position,
3535 "previous declaration of '%Y' was here", symbol);
3538 return previous_declaration;
3540 } else if (is_function_definition) {
3541 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3542 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3543 warningf(declaration->source_position,
3544 "no previous prototype for '%#T'", orig_type, symbol);
3545 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3546 warningf(declaration->source_position,
3547 "no previous declaration for '%#T'", orig_type,
3551 } else if (warning.missing_declarations &&
3552 scope == global_scope &&
3553 !is_type_function(type) && (
3554 declaration->storage_class == STORAGE_CLASS_NONE ||
3555 declaration->storage_class == STORAGE_CLASS_THREAD
3557 warningf(declaration->source_position,
3558 "no previous declaration for '%#T'", orig_type, symbol);
3561 assert(declaration->parent_scope == NULL);
3562 assert(scope != NULL);
3564 declaration->parent_scope = scope;
3566 environment_push(declaration);
3567 return append_declaration(declaration);
3570 static declaration_t *record_declaration(declaration_t *declaration)
3572 return internal_record_declaration(declaration, false);
3575 static declaration_t *record_function_definition(declaration_t *declaration)
3577 return internal_record_declaration(declaration, true);
3580 static void parser_error_multiple_definition(declaration_t *declaration,
3581 const source_position_t source_position)
3583 errorf(source_position, "multiple definition of symbol '%Y'",
3584 declaration->symbol);
3585 errorf(declaration->source_position,
3586 "this is the location of the previous definition.");
3589 static bool is_declaration_specifier(const token_t *token,
3590 bool only_type_specifiers)
3592 switch(token->type) {
3596 return is_typedef_symbol(token->v.symbol);
3598 case T___extension__:
3601 return !only_type_specifiers;
3608 static void parse_init_declarator_rest(declaration_t *declaration)
3612 type_t *orig_type = declaration->type;
3613 type_t *type = skip_typeref(orig_type);
3615 if(declaration->init.initializer != NULL) {
3616 parser_error_multiple_definition(declaration, token.source_position);
3619 bool must_be_constant = false;
3620 if(declaration->storage_class == STORAGE_CLASS_STATIC
3621 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3622 || declaration->parent_scope == global_scope) {
3623 must_be_constant = true;
3626 parse_initializer_env_t env;
3627 env.type = orig_type;
3628 env.must_be_constant = must_be_constant;
3629 env.declaration = declaration;
3631 initializer_t *initializer = parse_initializer(&env);
3633 if(env.type != orig_type) {
3634 orig_type = env.type;
3635 type = skip_typeref(orig_type);
3636 declaration->type = env.type;
3639 if(is_type_function(type)) {
3640 errorf(declaration->source_position,
3641 "initializers not allowed for function types at declator '%Y' (type '%T')",
3642 declaration->symbol, orig_type);
3644 declaration->init.initializer = initializer;
3648 /* parse rest of a declaration without any declarator */
3649 static void parse_anonymous_declaration_rest(
3650 const declaration_specifiers_t *specifiers,
3651 parsed_declaration_func finished_declaration)
3655 declaration_t *const declaration = allocate_declaration_zero();
3656 declaration->type = specifiers->type;
3657 declaration->declared_storage_class = specifiers->declared_storage_class;
3658 declaration->source_position = specifiers->source_position;
3659 declaration->modifiers = specifiers->decl_modifiers;
3661 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3662 warningf(declaration->source_position, "useless storage class in empty declaration");
3664 declaration->storage_class = STORAGE_CLASS_NONE;
3666 type_t *type = declaration->type;
3667 switch (type->kind) {
3668 case TYPE_COMPOUND_STRUCT:
3669 case TYPE_COMPOUND_UNION: {
3670 if (type->compound.declaration->symbol == NULL) {
3671 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3680 warningf(declaration->source_position, "empty declaration");
3684 finished_declaration(declaration);
3687 static void parse_declaration_rest(declaration_t *ndeclaration,
3688 const declaration_specifiers_t *specifiers,
3689 parsed_declaration_func finished_declaration)
3691 add_anchor_token(';');
3692 add_anchor_token('=');
3693 add_anchor_token(',');
3695 declaration_t *declaration = finished_declaration(ndeclaration);
3697 type_t *orig_type = declaration->type;
3698 type_t *type = skip_typeref(orig_type);
3700 if (type->kind != TYPE_FUNCTION &&
3701 declaration->is_inline &&
3702 is_type_valid(type)) {
3703 warningf(declaration->source_position,
3704 "variable '%Y' declared 'inline'\n", declaration->symbol);
3707 if(token.type == '=') {
3708 parse_init_declarator_rest(declaration);
3711 if(token.type != ',')
3715 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3720 rem_anchor_token(';');
3721 rem_anchor_token('=');
3722 rem_anchor_token(',');
3725 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3727 symbol_t *symbol = declaration->symbol;
3728 if(symbol == NULL) {
3729 errorf(HERE, "anonymous declaration not valid as function parameter");
3732 namespace_t namespc = (namespace_t) declaration->namespc;
3733 if(namespc != NAMESPACE_NORMAL) {
3734 return record_declaration(declaration);
3737 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3738 if(previous_declaration == NULL ||
3739 previous_declaration->parent_scope != scope) {
3740 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3745 if(previous_declaration->type == NULL) {
3746 previous_declaration->type = declaration->type;
3747 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3748 previous_declaration->storage_class = declaration->storage_class;
3749 previous_declaration->parent_scope = scope;
3750 return previous_declaration;
3752 return record_declaration(declaration);
3756 static void parse_declaration(parsed_declaration_func finished_declaration)
3758 declaration_specifiers_t specifiers;
3759 memset(&specifiers, 0, sizeof(specifiers));
3760 parse_declaration_specifiers(&specifiers);
3762 if(token.type == ';') {
3763 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3765 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3766 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3770 static void parse_kr_declaration_list(declaration_t *declaration)
3772 type_t *type = skip_typeref(declaration->type);
3773 if(!is_type_function(type))
3776 if(!type->function.kr_style_parameters)
3779 /* push function parameters */
3780 int top = environment_top();
3781 scope_t *last_scope = scope;
3782 set_scope(&declaration->scope);
3784 declaration_t *parameter = declaration->scope.declarations;
3785 for( ; parameter != NULL; parameter = parameter->next) {
3786 assert(parameter->parent_scope == NULL);
3787 parameter->parent_scope = scope;
3788 environment_push(parameter);
3791 /* parse declaration list */
3792 while(is_declaration_specifier(&token, false)) {
3793 parse_declaration(finished_kr_declaration);
3796 /* pop function parameters */
3797 assert(scope == &declaration->scope);
3798 set_scope(last_scope);
3799 environment_pop_to(top);
3801 /* update function type */
3802 type_t *new_type = duplicate_type(type);
3803 new_type->function.kr_style_parameters = false;
3805 function_parameter_t *parameters = NULL;
3806 function_parameter_t *last_parameter = NULL;
3808 declaration_t *parameter_declaration = declaration->scope.declarations;
3809 for( ; parameter_declaration != NULL;
3810 parameter_declaration = parameter_declaration->next) {
3811 type_t *parameter_type = parameter_declaration->type;
3812 if(parameter_type == NULL) {
3814 errorf(HERE, "no type specified for function parameter '%Y'",
3815 parameter_declaration->symbol);
3817 if (warning.implicit_int) {
3818 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3819 parameter_declaration->symbol);
3821 parameter_type = type_int;
3822 parameter_declaration->type = parameter_type;
3826 semantic_parameter(parameter_declaration);
3827 parameter_type = parameter_declaration->type;
3829 function_parameter_t *function_parameter
3830 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3831 memset(function_parameter, 0, sizeof(function_parameter[0]));
3833 function_parameter->type = parameter_type;
3834 if(last_parameter != NULL) {
3835 last_parameter->next = function_parameter;
3837 parameters = function_parameter;
3839 last_parameter = function_parameter;
3841 new_type->function.parameters = parameters;
3843 type = typehash_insert(new_type);
3844 if(type != new_type) {
3845 obstack_free(type_obst, new_type);
3848 declaration->type = type;
3851 static bool first_err = true;
3854 * When called with first_err set, prints the name of the current function,
3857 static void print_in_function(void) {
3860 diagnosticf("%s: In function '%Y':\n",
3861 current_function->source_position.input_name,
3862 current_function->symbol);
3867 * Check if all labels are defined in the current function.
3868 * Check if all labels are used in the current function.
3870 static void check_labels(void)
3872 for (const goto_statement_t *goto_statement = goto_first;
3873 goto_statement != NULL;
3874 goto_statement = goto_statement->next) {
3875 declaration_t *label = goto_statement->label;
3878 if (label->source_position.input_name == NULL) {
3879 print_in_function();
3880 errorf(goto_statement->base.source_position,
3881 "label '%Y' used but not defined", label->symbol);
3884 goto_first = goto_last = NULL;
3886 if (warning.unused_label) {
3887 for (const label_statement_t *label_statement = label_first;
3888 label_statement != NULL;
3889 label_statement = label_statement->next) {
3890 const declaration_t *label = label_statement->label;
3892 if (! label->used) {
3893 print_in_function();
3894 warningf(label_statement->base.source_position,
3895 "label '%Y' defined but not used", label->symbol);
3899 label_first = label_last = NULL;
3903 * Check declarations of current_function for unused entities.
3905 static void check_declarations(void)
3907 if (warning.unused_parameter) {
3908 const scope_t *scope = ¤t_function->scope;
3910 const declaration_t *parameter = scope->declarations;
3911 for (; parameter != NULL; parameter = parameter->next) {
3912 if (! parameter->used) {
3913 print_in_function();
3914 warningf(parameter->source_position,
3915 "unused parameter '%Y'", parameter->symbol);
3919 if (warning.unused_variable) {
3923 static void parse_external_declaration(void)
3925 /* function-definitions and declarations both start with declaration
3927 declaration_specifiers_t specifiers;
3928 memset(&specifiers, 0, sizeof(specifiers));
3930 add_anchor_token(';');
3931 parse_declaration_specifiers(&specifiers);
3932 rem_anchor_token(';');
3934 /* must be a declaration */
3935 if(token.type == ';') {
3936 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3940 add_anchor_token(',');
3941 add_anchor_token('=');
3942 rem_anchor_token(';');
3944 /* declarator is common to both function-definitions and declarations */
3945 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3947 rem_anchor_token(',');
3948 rem_anchor_token('=');
3949 rem_anchor_token(';');
3951 /* must be a declaration */
3952 if(token.type == ',' || token.type == '=' || token.type == ';') {
3953 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3957 /* must be a function definition */
3958 parse_kr_declaration_list(ndeclaration);
3960 if(token.type != '{') {
3961 parse_error_expected("while parsing function definition", '{', 0);
3962 eat_until_matching_token(';');
3966 type_t *type = ndeclaration->type;
3968 /* note that we don't skip typerefs: the standard doesn't allow them here
3969 * (so we can't use is_type_function here) */
3970 if(type->kind != TYPE_FUNCTION) {
3971 if (is_type_valid(type)) {
3972 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3973 type, ndeclaration->symbol);
3979 /* § 6.7.5.3 (14) a function definition with () means no
3980 * parameters (and not unspecified parameters) */
3981 if(type->function.unspecified_parameters) {
3982 type_t *duplicate = duplicate_type(type);
3983 duplicate->function.unspecified_parameters = false;
3985 type = typehash_insert(duplicate);
3986 if(type != duplicate) {
3987 obstack_free(type_obst, duplicate);
3989 ndeclaration->type = type;
3992 declaration_t *const declaration = record_function_definition(ndeclaration);
3993 if(ndeclaration != declaration) {
3994 declaration->scope = ndeclaration->scope;
3996 type = skip_typeref(declaration->type);
3998 /* push function parameters and switch scope */
3999 int top = environment_top();
4000 scope_t *last_scope = scope;
4001 set_scope(&declaration->scope);
4003 declaration_t *parameter = declaration->scope.declarations;
4004 for( ; parameter != NULL; parameter = parameter->next) {
4005 if(parameter->parent_scope == &ndeclaration->scope) {
4006 parameter->parent_scope = scope;
4008 assert(parameter->parent_scope == NULL
4009 || parameter->parent_scope == scope);
4010 parameter->parent_scope = scope;
4011 environment_push(parameter);
4014 if(declaration->init.statement != NULL) {
4015 parser_error_multiple_definition(declaration, token.source_position);
4017 goto end_of_parse_external_declaration;
4019 /* parse function body */
4020 int label_stack_top = label_top();
4021 declaration_t *old_current_function = current_function;
4022 current_function = declaration;
4024 declaration->init.statement = parse_compound_statement();
4027 check_declarations();
4029 assert(current_function == declaration);
4030 current_function = old_current_function;
4031 label_pop_to(label_stack_top);
4034 end_of_parse_external_declaration:
4035 assert(scope == &declaration->scope);
4036 set_scope(last_scope);
4037 environment_pop_to(top);
4040 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4041 source_position_t source_position)
4043 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4044 type->bitfield.base = base;
4045 type->bitfield.size = size;
4050 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4053 declaration_t *iter = compound_declaration->scope.declarations;
4054 for( ; iter != NULL; iter = iter->next) {
4055 if(iter->namespc != NAMESPACE_NORMAL)
4058 if(iter->symbol == NULL) {
4059 type_t *type = skip_typeref(iter->type);
4060 if(is_type_compound(type)) {
4061 declaration_t *result
4062 = find_compound_entry(type->compound.declaration, symbol);
4069 if(iter->symbol == symbol) {
4077 static void parse_compound_declarators(declaration_t *struct_declaration,
4078 const declaration_specifiers_t *specifiers)
4080 declaration_t *last_declaration = struct_declaration->scope.declarations;
4081 if(last_declaration != NULL) {
4082 while(last_declaration->next != NULL) {
4083 last_declaration = last_declaration->next;
4088 declaration_t *declaration;
4090 if(token.type == ':') {
4091 source_position_t source_position = HERE;
4094 type_t *base_type = specifiers->type;
4095 expression_t *size = parse_constant_expression();
4097 if(!is_type_integer(skip_typeref(base_type))) {
4098 errorf(HERE, "bitfield base type '%T' is not an integer type",
4102 type_t *type = make_bitfield_type(base_type, size, source_position);
4104 declaration = allocate_declaration_zero();
4105 declaration->namespc = NAMESPACE_NORMAL;
4106 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4107 declaration->storage_class = STORAGE_CLASS_NONE;
4108 declaration->source_position = source_position;
4109 declaration->modifiers = specifiers->decl_modifiers;
4110 declaration->type = type;
4112 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4114 type_t *orig_type = declaration->type;
4115 type_t *type = skip_typeref(orig_type);
4117 if(token.type == ':') {
4118 source_position_t source_position = HERE;
4120 expression_t *size = parse_constant_expression();
4122 if(!is_type_integer(type)) {
4123 errorf(HERE, "bitfield base type '%T' is not an "
4124 "integer type", orig_type);
4127 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
4128 declaration->type = bitfield_type;
4130 /* TODO we ignore arrays for now... what is missing is a check
4131 * that they're at the end of the struct */
4132 if(is_type_incomplete(type) && !is_type_array(type)) {
4134 "compound member '%Y' has incomplete type '%T'",
4135 declaration->symbol, orig_type);
4136 } else if(is_type_function(type)) {
4137 errorf(HERE, "compound member '%Y' must not have function "
4138 "type '%T'", declaration->symbol, orig_type);
4143 /* make sure we don't define a symbol multiple times */
4144 symbol_t *symbol = declaration->symbol;
4145 if(symbol != NULL) {
4146 declaration_t *prev_decl
4147 = find_compound_entry(struct_declaration, symbol);
4149 if(prev_decl != NULL) {
4150 assert(prev_decl->symbol == symbol);
4151 errorf(declaration->source_position,
4152 "multiple declarations of symbol '%Y'", symbol);
4153 errorf(prev_decl->source_position,
4154 "previous declaration of '%Y' was here", symbol);
4158 /* append declaration */
4159 if(last_declaration != NULL) {
4160 last_declaration->next = declaration;
4162 struct_declaration->scope.declarations = declaration;
4164 last_declaration = declaration;
4166 if(token.type != ',')
4176 static void parse_compound_type_entries(declaration_t *compound_declaration)
4179 add_anchor_token('}');
4181 while(token.type != '}' && token.type != T_EOF) {
4182 declaration_specifiers_t specifiers;
4183 memset(&specifiers, 0, sizeof(specifiers));
4184 parse_declaration_specifiers(&specifiers);
4186 parse_compound_declarators(compound_declaration, &specifiers);
4188 rem_anchor_token('}');
4190 if(token.type == T_EOF) {
4191 errorf(HERE, "EOF while parsing struct");
4196 static type_t *parse_typename(void)
4198 declaration_specifiers_t specifiers;
4199 memset(&specifiers, 0, sizeof(specifiers));
4200 parse_declaration_specifiers(&specifiers);
4201 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4202 /* TODO: improve error message, user does probably not know what a
4203 * storage class is...
4205 errorf(HERE, "typename may not have a storage class");
4208 type_t *result = parse_abstract_declarator(specifiers.type);
4216 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4217 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4218 expression_t *left);
4220 typedef struct expression_parser_function_t expression_parser_function_t;
4221 struct expression_parser_function_t {
4222 unsigned precedence;
4223 parse_expression_function parser;
4224 unsigned infix_precedence;
4225 parse_expression_infix_function infix_parser;
4228 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4231 * Prints an error message if an expression was expected but not read
4233 static expression_t *expected_expression_error(void)
4235 /* skip the error message if the error token was read */
4236 if (token.type != T_ERROR) {
4237 errorf(HERE, "expected expression, got token '%K'", &token);
4241 return create_invalid_expression();
4245 * Parse a string constant.
4247 static expression_t *parse_string_const(void)
4250 if (token.type == T_STRING_LITERAL) {
4251 string_t res = token.v.string;
4253 while (token.type == T_STRING_LITERAL) {
4254 res = concat_strings(&res, &token.v.string);
4257 if (token.type != T_WIDE_STRING_LITERAL) {
4258 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4259 /* note: that we use type_char_ptr here, which is already the
4260 * automatic converted type. revert_automatic_type_conversion
4261 * will construct the array type */
4262 cnst->base.type = type_char_ptr;
4263 cnst->string.value = res;
4267 wres = concat_string_wide_string(&res, &token.v.wide_string);
4269 wres = token.v.wide_string;
4274 switch (token.type) {
4275 case T_WIDE_STRING_LITERAL:
4276 wres = concat_wide_strings(&wres, &token.v.wide_string);
4279 case T_STRING_LITERAL:
4280 wres = concat_wide_string_string(&wres, &token.v.string);
4284 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4285 cnst->base.type = type_wchar_t_ptr;
4286 cnst->wide_string.value = wres;
4295 * Parse an integer constant.
4297 static expression_t *parse_int_const(void)
4299 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4300 cnst->base.source_position = HERE;
4301 cnst->base.type = token.datatype;
4302 cnst->conste.v.int_value = token.v.intvalue;
4310 * Parse a character constant.
4312 static expression_t *parse_character_constant(void)
4314 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4316 cnst->base.source_position = HERE;
4317 cnst->base.type = token.datatype;
4318 cnst->conste.v.character = token.v.string;
4320 if (cnst->conste.v.character.size != 1) {
4321 if (warning.multichar && (c_mode & _GNUC)) {
4323 warningf(HERE, "multi-character character constant");
4325 errorf(HERE, "more than 1 characters in character constant");
4334 * Parse a wide character constant.
4336 static expression_t *parse_wide_character_constant(void)
4338 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4340 cnst->base.source_position = HERE;
4341 cnst->base.type = token.datatype;
4342 cnst->conste.v.wide_character = token.v.wide_string;
4344 if (cnst->conste.v.wide_character.size != 1) {
4345 if (warning.multichar && (c_mode & _GNUC)) {
4347 warningf(HERE, "multi-character character constant");
4349 errorf(HERE, "more than 1 characters in character constant");
4358 * Parse a float constant.
4360 static expression_t *parse_float_const(void)
4362 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4363 cnst->base.type = token.datatype;
4364 cnst->conste.v.float_value = token.v.floatvalue;
4371 static declaration_t *create_implicit_function(symbol_t *symbol,
4372 const source_position_t source_position)
4374 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4375 ntype->function.return_type = type_int;
4376 ntype->function.unspecified_parameters = true;
4378 type_t *type = typehash_insert(ntype);
4383 declaration_t *const declaration = allocate_declaration_zero();
4384 declaration->storage_class = STORAGE_CLASS_EXTERN;
4385 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4386 declaration->type = type;
4387 declaration->symbol = symbol;
4388 declaration->source_position = source_position;
4389 declaration->parent_scope = global_scope;
4391 scope_t *old_scope = scope;
4392 set_scope(global_scope);
4394 environment_push(declaration);
4395 /* prepends the declaration to the global declarations list */
4396 declaration->next = scope->declarations;
4397 scope->declarations = declaration;
4399 assert(scope == global_scope);
4400 set_scope(old_scope);
4406 * Creates a return_type (func)(argument_type) function type if not
4409 * @param return_type the return type
4410 * @param argument_type the argument type
4412 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4414 function_parameter_t *parameter
4415 = obstack_alloc(type_obst, sizeof(parameter[0]));
4416 memset(parameter, 0, sizeof(parameter[0]));
4417 parameter->type = argument_type;
4419 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4420 type->function.return_type = return_type;
4421 type->function.parameters = parameter;
4423 type_t *result = typehash_insert(type);
4424 if(result != type) {
4432 * Creates a function type for some function like builtins.
4434 * @param symbol the symbol describing the builtin
4436 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4438 switch(symbol->ID) {
4439 case T___builtin_alloca:
4440 return make_function_1_type(type_void_ptr, type_size_t);
4441 case T___builtin_nan:
4442 return make_function_1_type(type_double, type_char_ptr);
4443 case T___builtin_nanf:
4444 return make_function_1_type(type_float, type_char_ptr);
4445 case T___builtin_nand:
4446 return make_function_1_type(type_long_double, type_char_ptr);
4447 case T___builtin_va_end:
4448 return make_function_1_type(type_void, type_valist);
4450 internal_errorf(HERE, "not implemented builtin symbol found");
4455 * Performs automatic type cast as described in § 6.3.2.1.
4457 * @param orig_type the original type
4459 static type_t *automatic_type_conversion(type_t *orig_type)
4461 type_t *type = skip_typeref(orig_type);
4462 if(is_type_array(type)) {
4463 array_type_t *array_type = &type->array;
4464 type_t *element_type = array_type->element_type;
4465 unsigned qualifiers = array_type->type.qualifiers;
4467 return make_pointer_type(element_type, qualifiers);
4470 if(is_type_function(type)) {
4471 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4478 * reverts the automatic casts of array to pointer types and function
4479 * to function-pointer types as defined § 6.3.2.1
4481 type_t *revert_automatic_type_conversion(const expression_t *expression)
4483 switch (expression->kind) {
4484 case EXPR_REFERENCE: return expression->reference.declaration->type;
4485 case EXPR_SELECT: return expression->select.compound_entry->type;
4487 case EXPR_UNARY_DEREFERENCE: {
4488 const expression_t *const value = expression->unary.value;
4489 type_t *const type = skip_typeref(value->base.type);
4490 assert(is_type_pointer(type));
4491 return type->pointer.points_to;
4494 case EXPR_BUILTIN_SYMBOL:
4495 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4497 case EXPR_ARRAY_ACCESS: {
4498 const expression_t *array_ref = expression->array_access.array_ref;
4499 type_t *type_left = skip_typeref(array_ref->base.type);
4500 if (!is_type_valid(type_left))
4502 assert(is_type_pointer(type_left));
4503 return type_left->pointer.points_to;
4506 case EXPR_STRING_LITERAL: {
4507 size_t size = expression->string.value.size;
4508 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4511 case EXPR_WIDE_STRING_LITERAL: {
4512 size_t size = expression->wide_string.value.size;
4513 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4516 case EXPR_COMPOUND_LITERAL:
4517 return expression->compound_literal.type;
4522 return expression->base.type;
4525 static expression_t *parse_reference(void)
4527 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4529 reference_expression_t *ref = &expression->reference;
4530 ref->symbol = token.v.symbol;
4532 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4534 source_position_t source_position = token.source_position;
4537 if(declaration == NULL) {
4538 if (! strict_mode && token.type == '(') {
4539 /* an implicitly defined function */
4540 if (warning.implicit_function_declaration) {
4541 warningf(HERE, "implicit declaration of function '%Y'",
4545 declaration = create_implicit_function(ref->symbol,
4548 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4549 return create_invalid_expression();
4553 type_t *type = declaration->type;
4555 /* we always do the auto-type conversions; the & and sizeof parser contains
4556 * code to revert this! */
4557 type = automatic_type_conversion(type);
4559 ref->declaration = declaration;
4560 ref->base.type = type;
4562 /* this declaration is used */
4563 declaration->used = true;
4565 /* check for deprecated functions */
4566 if(declaration->deprecated != 0) {
4567 const char *prefix = "";
4568 if (is_type_function(declaration->type))
4569 prefix = "function ";
4571 if (declaration->deprecated_string != NULL) {
4572 warningf(source_position,
4573 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4574 declaration->deprecated_string);
4576 warningf(source_position,
4577 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4584 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4588 /* TODO check if explicit cast is allowed and issue warnings/errors */
4591 static expression_t *parse_compound_literal(type_t *type)
4593 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4595 parse_initializer_env_t env;
4597 env.declaration = NULL;
4598 env.must_be_constant = false;
4599 initializer_t *initializer = parse_initializer(&env);
4602 expression->compound_literal.initializer = initializer;
4603 expression->compound_literal.type = type;
4604 expression->base.type = automatic_type_conversion(type);
4610 * Parse a cast expression.
4612 static expression_t *parse_cast(void)
4614 source_position_t source_position = token.source_position;
4616 type_t *type = parse_typename();
4618 /* matching add_anchor_token() is at call site */
4619 rem_anchor_token(')');
4622 if(token.type == '{') {
4623 return parse_compound_literal(type);
4626 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4627 cast->base.source_position = source_position;
4629 expression_t *value = parse_sub_expression(20);
4631 check_cast_allowed(value, type);
4633 cast->base.type = type;
4634 cast->unary.value = value;
4638 return create_invalid_expression();
4642 * Parse a statement expression.
4644 static expression_t *parse_statement_expression(void)
4646 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4648 statement_t *statement = parse_compound_statement();
4649 expression->statement.statement = statement;
4650 expression->base.source_position = statement->base.source_position;
4652 /* find last statement and use its type */
4653 type_t *type = type_void;
4654 const statement_t *stmt = statement->compound.statements;
4656 while (stmt->base.next != NULL)
4657 stmt = stmt->base.next;
4659 if (stmt->kind == STATEMENT_EXPRESSION) {
4660 type = stmt->expression.expression->base.type;
4663 warningf(expression->base.source_position, "empty statement expression ({})");
4665 expression->base.type = type;
4671 return create_invalid_expression();
4675 * Parse a braced expression.
4677 static expression_t *parse_brace_expression(void)
4680 add_anchor_token(')');
4682 switch(token.type) {
4684 /* gcc extension: a statement expression */
4685 return parse_statement_expression();
4689 return parse_cast();
4691 if(is_typedef_symbol(token.v.symbol)) {
4692 return parse_cast();
4696 expression_t *result = parse_expression();
4697 rem_anchor_token(')');
4702 return create_invalid_expression();
4705 static expression_t *parse_function_keyword(void)
4710 if (current_function == NULL) {
4711 errorf(HERE, "'__func__' used outside of a function");
4714 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4715 expression->base.type = type_char_ptr;
4716 expression->funcname.kind = FUNCNAME_FUNCTION;
4721 static expression_t *parse_pretty_function_keyword(void)
4723 eat(T___PRETTY_FUNCTION__);
4725 if (current_function == NULL) {
4726 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4729 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4730 expression->base.type = type_char_ptr;
4731 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
4736 static expression_t *parse_funcsig_keyword(void)
4740 if (current_function == NULL) {
4741 errorf(HERE, "'__FUNCSIG__' used outside of a function");
4744 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4745 expression->base.type = type_char_ptr;
4746 expression->funcname.kind = FUNCNAME_FUNCSIG;
4751 static expression_t *parse_funcdname_keyword(void)
4753 eat(T___FUNCDNAME__);
4755 if (current_function == NULL) {
4756 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
4759 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4760 expression->base.type = type_char_ptr;
4761 expression->funcname.kind = FUNCNAME_FUNCDNAME;
4766 static designator_t *parse_designator(void)
4768 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4769 result->source_position = HERE;
4771 if(token.type != T_IDENTIFIER) {
4772 parse_error_expected("while parsing member designator",
4776 result->symbol = token.v.symbol;
4779 designator_t *last_designator = result;
4781 if(token.type == '.') {
4783 if(token.type != T_IDENTIFIER) {
4784 parse_error_expected("while parsing member designator",
4788 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4789 designator->source_position = HERE;
4790 designator->symbol = token.v.symbol;
4793 last_designator->next = designator;
4794 last_designator = designator;
4797 if(token.type == '[') {
4799 add_anchor_token(']');
4800 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4801 designator->source_position = HERE;
4802 designator->array_index = parse_expression();
4803 rem_anchor_token(']');
4805 if(designator->array_index == NULL) {
4809 last_designator->next = designator;
4810 last_designator = designator;
4822 * Parse the __builtin_offsetof() expression.
4824 static expression_t *parse_offsetof(void)
4826 eat(T___builtin_offsetof);
4828 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4829 expression->base.type = type_size_t;
4832 add_anchor_token(',');
4833 type_t *type = parse_typename();
4834 rem_anchor_token(',');
4836 add_anchor_token(')');
4837 designator_t *designator = parse_designator();
4838 rem_anchor_token(')');
4841 expression->offsetofe.type = type;
4842 expression->offsetofe.designator = designator;
4845 memset(&path, 0, sizeof(path));
4846 path.top_type = type;
4847 path.path = NEW_ARR_F(type_path_entry_t, 0);
4849 descend_into_subtype(&path);
4851 if(!walk_designator(&path, designator, true)) {
4852 return create_invalid_expression();
4855 DEL_ARR_F(path.path);
4859 return create_invalid_expression();
4863 * Parses a _builtin_va_start() expression.
4865 static expression_t *parse_va_start(void)
4867 eat(T___builtin_va_start);
4869 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4872 add_anchor_token(',');
4873 expression->va_starte.ap = parse_assignment_expression();
4874 rem_anchor_token(',');
4876 expression_t *const expr = parse_assignment_expression();
4877 if (expr->kind == EXPR_REFERENCE) {
4878 declaration_t *const decl = expr->reference.declaration;
4880 return create_invalid_expression();
4881 if (decl->parent_scope == ¤t_function->scope &&
4882 decl->next == NULL) {
4883 expression->va_starte.parameter = decl;
4888 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4890 return create_invalid_expression();
4894 * Parses a _builtin_va_arg() expression.
4896 static expression_t *parse_va_arg(void)
4898 eat(T___builtin_va_arg);
4900 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4903 expression->va_arge.ap = parse_assignment_expression();
4905 expression->base.type = parse_typename();
4910 return create_invalid_expression();
4913 static expression_t *parse_builtin_symbol(void)
4915 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4917 symbol_t *symbol = token.v.symbol;
4919 expression->builtin_symbol.symbol = symbol;
4922 type_t *type = get_builtin_symbol_type(symbol);
4923 type = automatic_type_conversion(type);
4925 expression->base.type = type;
4930 * Parses a __builtin_constant() expression.
4932 static expression_t *parse_builtin_constant(void)
4934 eat(T___builtin_constant_p);
4936 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4939 add_anchor_token(')');
4940 expression->builtin_constant.value = parse_assignment_expression();
4941 rem_anchor_token(')');
4943 expression->base.type = type_int;
4947 return create_invalid_expression();
4951 * Parses a __builtin_prefetch() expression.
4953 static expression_t *parse_builtin_prefetch(void)
4955 eat(T___builtin_prefetch);
4957 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4960 add_anchor_token(')');
4961 expression->builtin_prefetch.adr = parse_assignment_expression();
4962 if (token.type == ',') {
4964 expression->builtin_prefetch.rw = parse_assignment_expression();
4966 if (token.type == ',') {
4968 expression->builtin_prefetch.locality = parse_assignment_expression();
4970 rem_anchor_token(')');
4972 expression->base.type = type_void;
4976 return create_invalid_expression();
4980 * Parses a __builtin_is_*() compare expression.
4982 static expression_t *parse_compare_builtin(void)
4984 expression_t *expression;
4986 switch(token.type) {
4987 case T___builtin_isgreater:
4988 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4990 case T___builtin_isgreaterequal:
4991 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4993 case T___builtin_isless:
4994 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4996 case T___builtin_islessequal:
4997 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4999 case T___builtin_islessgreater:
5000 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5002 case T___builtin_isunordered:
5003 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5006 internal_errorf(HERE, "invalid compare builtin found");
5009 expression->base.source_position = HERE;
5013 expression->binary.left = parse_assignment_expression();
5015 expression->binary.right = parse_assignment_expression();
5018 type_t *const orig_type_left = expression->binary.left->base.type;
5019 type_t *const orig_type_right = expression->binary.right->base.type;
5021 type_t *const type_left = skip_typeref(orig_type_left);
5022 type_t *const type_right = skip_typeref(orig_type_right);
5023 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5024 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5025 type_error_incompatible("invalid operands in comparison",
5026 expression->base.source_position, orig_type_left, orig_type_right);
5029 semantic_comparison(&expression->binary);
5034 return create_invalid_expression();
5038 * Parses a __builtin_expect() expression.
5040 static expression_t *parse_builtin_expect(void)
5042 eat(T___builtin_expect);
5044 expression_t *expression
5045 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5048 expression->binary.left = parse_assignment_expression();
5050 expression->binary.right = parse_constant_expression();
5053 expression->base.type = expression->binary.left->base.type;
5057 return create_invalid_expression();
5061 * Parses a MS assume() expression.
5063 static expression_t *parse_assume(void) {
5066 expression_t *expression
5067 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5070 add_anchor_token(')');
5071 expression->unary.value = parse_assignment_expression();
5072 rem_anchor_token(')');
5075 expression->base.type = type_void;
5078 return create_invalid_expression();
5082 * Parse a microsoft __noop expression.
5084 static expression_t *parse_noop_expression(void) {
5085 source_position_t source_position = HERE;
5088 if (token.type == '(') {
5089 /* parse arguments */
5091 add_anchor_token(')');
5092 add_anchor_token(',');
5094 if(token.type != ')') {
5096 (void)parse_assignment_expression();
5097 if(token.type != ',')
5103 rem_anchor_token(',');
5104 rem_anchor_token(')');
5107 /* the result is a (int)0 */
5108 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5109 cnst->base.source_position = source_position;
5110 cnst->base.type = type_int;
5111 cnst->conste.v.int_value = 0;
5112 cnst->conste.is_ms_noop = true;
5117 return create_invalid_expression();
5121 * Parses a primary expression.
5123 static expression_t *parse_primary_expression(void)
5125 switch (token.type) {
5126 case T_INTEGER: return parse_int_const();
5127 case T_CHARACTER_CONSTANT: return parse_character_constant();
5128 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5129 case T_FLOATINGPOINT: return parse_float_const();
5130 case T_STRING_LITERAL:
5131 case T_WIDE_STRING_LITERAL: return parse_string_const();
5132 case T_IDENTIFIER: return parse_reference();
5133 case T___FUNCTION__:
5134 case T___func__: return parse_function_keyword();
5135 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5136 case T___FUNCSIG__: return parse_funcsig_keyword();
5137 case T___FUNCDNAME__: return parse_funcdname_keyword();
5138 case T___builtin_offsetof: return parse_offsetof();
5139 case T___builtin_va_start: return parse_va_start();
5140 case T___builtin_va_arg: return parse_va_arg();
5141 case T___builtin_expect: return parse_builtin_expect();
5142 case T___builtin_alloca:
5143 case T___builtin_nan:
5144 case T___builtin_nand:
5145 case T___builtin_nanf:
5146 case T___builtin_va_end: return parse_builtin_symbol();
5147 case T___builtin_isgreater:
5148 case T___builtin_isgreaterequal:
5149 case T___builtin_isless:
5150 case T___builtin_islessequal:
5151 case T___builtin_islessgreater:
5152 case T___builtin_isunordered: return parse_compare_builtin();
5153 case T___builtin_constant_p: return parse_builtin_constant();
5154 case T___builtin_prefetch: return parse_builtin_prefetch();
5155 case T__assume: return parse_assume();
5157 case '(': return parse_brace_expression();
5158 case T___noop: return parse_noop_expression();
5161 errorf(HERE, "unexpected token %K, expected an expression", &token);
5162 return create_invalid_expression();
5166 * Check if the expression has the character type and issue a warning then.
5168 static void check_for_char_index_type(const expression_t *expression) {
5169 type_t *const type = expression->base.type;
5170 const type_t *const base_type = skip_typeref(type);
5172 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5173 warning.char_subscripts) {
5174 warningf(expression->base.source_position,
5175 "array subscript has type '%T'", type);
5179 static expression_t *parse_array_expression(unsigned precedence,
5185 add_anchor_token(']');
5187 expression_t *inside = parse_expression();
5189 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5191 array_access_expression_t *array_access = &expression->array_access;
5193 type_t *const orig_type_left = left->base.type;
5194 type_t *const orig_type_inside = inside->base.type;
5196 type_t *const type_left = skip_typeref(orig_type_left);
5197 type_t *const type_inside = skip_typeref(orig_type_inside);
5199 type_t *return_type;
5200 if (is_type_pointer(type_left)) {
5201 return_type = type_left->pointer.points_to;
5202 array_access->array_ref = left;
5203 array_access->index = inside;
5204 check_for_char_index_type(inside);
5205 } else if (is_type_pointer(type_inside)) {
5206 return_type = type_inside->pointer.points_to;
5207 array_access->array_ref = inside;
5208 array_access->index = left;
5209 array_access->flipped = true;
5210 check_for_char_index_type(left);
5212 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5214 "array access on object with non-pointer types '%T', '%T'",
5215 orig_type_left, orig_type_inside);
5217 return_type = type_error_type;
5218 array_access->array_ref = create_invalid_expression();
5221 rem_anchor_token(']');
5222 if(token.type != ']') {
5223 parse_error_expected("Problem while parsing array access", ']', 0);
5228 return_type = automatic_type_conversion(return_type);
5229 expression->base.type = return_type;
5234 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5236 expression_t *tp_expression = allocate_expression_zero(kind);
5237 tp_expression->base.type = type_size_t;
5239 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5241 add_anchor_token(')');
5242 tp_expression->typeprop.type = parse_typename();
5243 rem_anchor_token(')');
5246 expression_t *expression = parse_sub_expression(precedence);
5247 expression->base.type = revert_automatic_type_conversion(expression);
5249 tp_expression->typeprop.type = expression->base.type;
5250 tp_expression->typeprop.tp_expression = expression;
5253 return tp_expression;
5255 return create_invalid_expression();
5258 static expression_t *parse_sizeof(unsigned precedence)
5261 return parse_typeprop(EXPR_SIZEOF, precedence);
5264 static expression_t *parse_alignof(unsigned precedence)
5267 return parse_typeprop(EXPR_SIZEOF, precedence);
5270 static expression_t *parse_select_expression(unsigned precedence,
5271 expression_t *compound)
5274 assert(token.type == '.' || token.type == T_MINUSGREATER);
5276 bool is_pointer = (token.type == T_MINUSGREATER);
5279 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5280 select->select.compound = compound;
5282 if(token.type != T_IDENTIFIER) {
5283 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5286 symbol_t *symbol = token.v.symbol;
5287 select->select.symbol = symbol;
5290 type_t *const orig_type = compound->base.type;
5291 type_t *const type = skip_typeref(orig_type);
5293 type_t *type_left = type;
5295 if (!is_type_pointer(type)) {
5296 if (is_type_valid(type)) {
5297 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5299 return create_invalid_expression();
5301 type_left = type->pointer.points_to;
5303 type_left = skip_typeref(type_left);
5305 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5306 type_left->kind != TYPE_COMPOUND_UNION) {
5307 if (is_type_valid(type_left)) {
5308 errorf(HERE, "request for member '%Y' in something not a struct or "
5309 "union, but '%T'", symbol, type_left);
5311 return create_invalid_expression();
5314 declaration_t *const declaration = type_left->compound.declaration;
5316 if(!declaration->init.is_defined) {
5317 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5319 return create_invalid_expression();
5322 declaration_t *iter = find_compound_entry(declaration, symbol);
5324 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5325 return create_invalid_expression();
5328 /* we always do the auto-type conversions; the & and sizeof parser contains
5329 * code to revert this! */
5330 type_t *expression_type = automatic_type_conversion(iter->type);
5332 select->select.compound_entry = iter;
5333 select->base.type = expression_type;
5335 if(expression_type->kind == TYPE_BITFIELD) {
5336 expression_t *extract
5337 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5338 extract->unary.value = select;
5339 extract->base.type = expression_type->bitfield.base;
5348 * Parse a call expression, ie. expression '( ... )'.
5350 * @param expression the function address
5352 static expression_t *parse_call_expression(unsigned precedence,
5353 expression_t *expression)
5356 expression_t *result = allocate_expression_zero(EXPR_CALL);
5357 result->base.source_position = expression->base.source_position;
5359 call_expression_t *call = &result->call;
5360 call->function = expression;
5362 type_t *const orig_type = expression->base.type;
5363 type_t *const type = skip_typeref(orig_type);
5365 function_type_t *function_type = NULL;
5366 if (is_type_pointer(type)) {
5367 type_t *const to_type = skip_typeref(type->pointer.points_to);
5369 if (is_type_function(to_type)) {
5370 function_type = &to_type->function;
5371 call->base.type = function_type->return_type;
5375 if (function_type == NULL && is_type_valid(type)) {
5376 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5379 /* parse arguments */
5381 add_anchor_token(')');
5382 add_anchor_token(',');
5384 if(token.type != ')') {
5385 call_argument_t *last_argument = NULL;
5388 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5390 argument->expression = parse_assignment_expression();
5391 if(last_argument == NULL) {
5392 call->arguments = argument;
5394 last_argument->next = argument;
5396 last_argument = argument;
5398 if(token.type != ',')
5403 rem_anchor_token(',');
5404 rem_anchor_token(')');
5407 if(function_type != NULL) {
5408 function_parameter_t *parameter = function_type->parameters;
5409 call_argument_t *argument = call->arguments;
5410 for( ; parameter != NULL && argument != NULL;
5411 parameter = parameter->next, argument = argument->next) {
5412 type_t *expected_type = parameter->type;
5413 /* TODO report scope in error messages */
5414 expression_t *const arg_expr = argument->expression;
5415 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call", arg_expr->base.source_position);
5416 if (res_type == NULL) {
5417 /* TODO improve error message */
5418 errorf(arg_expr->base.source_position,
5419 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5420 arg_expr, arg_expr->base.type, expected_type);
5422 argument->expression = create_implicit_cast(argument->expression, expected_type);
5425 /* too few parameters */
5426 if(parameter != NULL) {
5427 errorf(HERE, "too few arguments to function '%E'", expression);
5428 } else if(argument != NULL) {
5429 /* too many parameters */
5430 if(!function_type->variadic
5431 && !function_type->unspecified_parameters) {
5432 errorf(HERE, "too many arguments to function '%E'", expression);
5434 /* do default promotion */
5435 for( ; argument != NULL; argument = argument->next) {
5436 type_t *type = argument->expression->base.type;
5438 type = skip_typeref(type);
5439 if(is_type_integer(type)) {
5440 type = promote_integer(type);
5441 } else if(type == type_float) {
5445 argument->expression
5446 = create_implicit_cast(argument->expression, type);
5449 check_format(&result->call);
5452 check_format(&result->call);
5458 return create_invalid_expression();
5461 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5463 static bool same_compound_type(const type_t *type1, const type_t *type2)
5466 is_type_compound(type1) &&
5467 type1->kind == type2->kind &&
5468 type1->compound.declaration == type2->compound.declaration;
5472 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5474 * @param expression the conditional expression
5476 static expression_t *parse_conditional_expression(unsigned precedence,
5477 expression_t *expression)
5480 add_anchor_token(':');
5482 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5484 conditional_expression_t *conditional = &result->conditional;
5485 conditional->condition = expression;
5488 type_t *const condition_type_orig = expression->base.type;
5489 type_t *const condition_type = skip_typeref(condition_type_orig);
5490 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5491 type_error("expected a scalar type in conditional condition",
5492 expression->base.source_position, condition_type_orig);
5495 expression_t *true_expression = parse_expression();
5496 rem_anchor_token(':');
5498 expression_t *false_expression = parse_sub_expression(precedence);
5500 type_t *const orig_true_type = true_expression->base.type;
5501 type_t *const orig_false_type = false_expression->base.type;
5502 type_t *const true_type = skip_typeref(orig_true_type);
5503 type_t *const false_type = skip_typeref(orig_false_type);
5506 type_t *result_type;
5507 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5508 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5509 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5510 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5511 warningf(expression->base.source_position,
5512 "ISO C forbids conditional expression with only one void side");
5514 result_type = type_void;
5515 } else if (is_type_arithmetic(true_type)
5516 && is_type_arithmetic(false_type)) {
5517 result_type = semantic_arithmetic(true_type, false_type);
5519 true_expression = create_implicit_cast(true_expression, result_type);
5520 false_expression = create_implicit_cast(false_expression, result_type);
5522 conditional->true_expression = true_expression;
5523 conditional->false_expression = false_expression;
5524 conditional->base.type = result_type;
5525 } else if (same_compound_type(true_type, false_type)) {
5526 /* just take 1 of the 2 types */
5527 result_type = true_type;
5528 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5529 type_t *pointer_type;
5531 expression_t *other_expression;
5532 if (is_type_pointer(true_type)) {
5533 pointer_type = true_type;
5534 other_type = false_type;
5535 other_expression = false_expression;
5537 pointer_type = false_type;
5538 other_type = true_type;
5539 other_expression = true_expression;
5542 if(is_type_pointer(other_type)) {
5543 if(!pointers_compatible(true_type, false_type)) {
5544 warningf(expression->base.source_position,
5545 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5547 result_type = true_type;
5548 } else if(is_null_pointer_constant(other_expression)) {
5549 result_type = pointer_type;
5550 } else if(is_type_integer(other_type)) {
5551 warningf(expression->base.source_position,
5552 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5553 result_type = pointer_type;
5555 type_error_incompatible("while parsing conditional",
5556 expression->base.source_position, true_type, false_type);
5557 result_type = type_error_type;
5560 /* TODO: one pointer to void*, other some pointer */
5562 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5563 type_error_incompatible("while parsing conditional",
5564 expression->base.source_position, true_type,
5567 result_type = type_error_type;
5570 conditional->true_expression
5571 = create_implicit_cast(true_expression, result_type);
5572 conditional->false_expression
5573 = create_implicit_cast(false_expression, result_type);
5574 conditional->base.type = result_type;
5577 return create_invalid_expression();
5581 * Parse an extension expression.
5583 static expression_t *parse_extension(unsigned precedence)
5585 eat(T___extension__);
5587 /* TODO enable extensions */
5588 expression_t *expression = parse_sub_expression(precedence);
5589 /* TODO disable extensions */
5594 * Parse a __builtin_classify_type() expression.
5596 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5598 eat(T___builtin_classify_type);
5600 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5601 result->base.type = type_int;
5604 add_anchor_token(')');
5605 expression_t *expression = parse_sub_expression(precedence);
5606 rem_anchor_token(')');
5608 result->classify_type.type_expression = expression;
5612 return create_invalid_expression();
5615 static void semantic_incdec(unary_expression_t *expression)
5617 type_t *const orig_type = expression->value->base.type;
5618 type_t *const type = skip_typeref(orig_type);
5619 /* TODO !is_type_real && !is_type_pointer */
5620 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5621 if (is_type_valid(type)) {
5622 /* TODO: improve error message */
5623 errorf(HERE, "operation needs an arithmetic or pointer type");
5628 expression->base.type = orig_type;
5631 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5633 type_t *const orig_type = expression->value->base.type;
5634 type_t *const type = skip_typeref(orig_type);
5635 if(!is_type_arithmetic(type)) {
5636 if (is_type_valid(type)) {
5637 /* TODO: improve error message */
5638 errorf(HERE, "operation needs an arithmetic type");
5643 expression->base.type = orig_type;
5646 static void semantic_unexpr_scalar(unary_expression_t *expression)
5648 type_t *const orig_type = expression->value->base.type;
5649 type_t *const type = skip_typeref(orig_type);
5650 if (!is_type_scalar(type)) {
5651 if (is_type_valid(type)) {
5652 errorf(HERE, "operand of ! must be of scalar type");
5657 expression->base.type = orig_type;
5660 static void semantic_unexpr_integer(unary_expression_t *expression)
5662 type_t *const orig_type = expression->value->base.type;
5663 type_t *const type = skip_typeref(orig_type);
5664 if (!is_type_integer(type)) {
5665 if (is_type_valid(type)) {
5666 errorf(HERE, "operand of ~ must be of integer type");
5671 expression->base.type = orig_type;
5674 static void semantic_dereference(unary_expression_t *expression)
5676 type_t *const orig_type = expression->value->base.type;
5677 type_t *const type = skip_typeref(orig_type);
5678 if(!is_type_pointer(type)) {
5679 if (is_type_valid(type)) {
5680 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5685 type_t *result_type = type->pointer.points_to;
5686 result_type = automatic_type_conversion(result_type);
5687 expression->base.type = result_type;
5691 * Check the semantic of the address taken expression.
5693 static void semantic_take_addr(unary_expression_t *expression)
5695 expression_t *value = expression->value;
5696 value->base.type = revert_automatic_type_conversion(value);
5698 type_t *orig_type = value->base.type;
5699 if(!is_type_valid(orig_type))
5702 if(value->kind == EXPR_REFERENCE) {
5703 declaration_t *const declaration = value->reference.declaration;
5704 if(declaration != NULL) {
5705 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5706 errorf(expression->base.source_position,
5707 "address of register variable '%Y' requested",
5708 declaration->symbol);
5710 declaration->address_taken = 1;
5714 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5717 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5718 static expression_t *parse_##unexpression_type(unsigned precedence) \
5722 expression_t *unary_expression \
5723 = allocate_expression_zero(unexpression_type); \
5724 unary_expression->base.source_position = HERE; \
5725 unary_expression->unary.value = parse_sub_expression(precedence); \
5727 sfunc(&unary_expression->unary); \
5729 return unary_expression; \
5732 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5733 semantic_unexpr_arithmetic)
5734 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5735 semantic_unexpr_arithmetic)
5736 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5737 semantic_unexpr_scalar)
5738 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5739 semantic_dereference)
5740 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5742 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5743 semantic_unexpr_integer)
5744 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5746 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5749 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5751 static expression_t *parse_##unexpression_type(unsigned precedence, \
5752 expression_t *left) \
5754 (void) precedence; \
5757 expression_t *unary_expression \
5758 = allocate_expression_zero(unexpression_type); \
5759 unary_expression->unary.value = left; \
5761 sfunc(&unary_expression->unary); \
5763 return unary_expression; \
5766 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5767 EXPR_UNARY_POSTFIX_INCREMENT,
5769 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5770 EXPR_UNARY_POSTFIX_DECREMENT,
5773 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5775 /* TODO: handle complex + imaginary types */
5777 /* § 6.3.1.8 Usual arithmetic conversions */
5778 if(type_left == type_long_double || type_right == type_long_double) {
5779 return type_long_double;
5780 } else if(type_left == type_double || type_right == type_double) {
5782 } else if(type_left == type_float || type_right == type_float) {
5786 type_right = promote_integer(type_right);
5787 type_left = promote_integer(type_left);
5789 if(type_left == type_right)
5792 bool signed_left = is_type_signed(type_left);
5793 bool signed_right = is_type_signed(type_right);
5794 int rank_left = get_rank(type_left);
5795 int rank_right = get_rank(type_right);
5796 if(rank_left < rank_right) {
5797 if(signed_left == signed_right || !signed_right) {
5803 if(signed_left == signed_right || !signed_left) {
5812 * Check the semantic restrictions for a binary expression.
5814 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5816 expression_t *const left = expression->left;
5817 expression_t *const right = expression->right;
5818 type_t *const orig_type_left = left->base.type;
5819 type_t *const orig_type_right = right->base.type;
5820 type_t *const type_left = skip_typeref(orig_type_left);
5821 type_t *const type_right = skip_typeref(orig_type_right);
5823 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5824 /* TODO: improve error message */
5825 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5826 errorf(HERE, "operation needs arithmetic types");
5831 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5832 expression->left = create_implicit_cast(left, arithmetic_type);
5833 expression->right = create_implicit_cast(right, arithmetic_type);
5834 expression->base.type = arithmetic_type;
5837 static void semantic_shift_op(binary_expression_t *expression)
5839 expression_t *const left = expression->left;
5840 expression_t *const right = expression->right;
5841 type_t *const orig_type_left = left->base.type;
5842 type_t *const orig_type_right = right->base.type;
5843 type_t * type_left = skip_typeref(orig_type_left);
5844 type_t * type_right = skip_typeref(orig_type_right);
5846 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5847 /* TODO: improve error message */
5848 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5849 errorf(HERE, "operation needs integer types");
5854 type_left = promote_integer(type_left);
5855 type_right = promote_integer(type_right);
5857 expression->left = create_implicit_cast(left, type_left);
5858 expression->right = create_implicit_cast(right, type_right);
5859 expression->base.type = type_left;
5862 static void semantic_add(binary_expression_t *expression)
5864 expression_t *const left = expression->left;
5865 expression_t *const right = expression->right;
5866 type_t *const orig_type_left = left->base.type;
5867 type_t *const orig_type_right = right->base.type;
5868 type_t *const type_left = skip_typeref(orig_type_left);
5869 type_t *const type_right = skip_typeref(orig_type_right);
5872 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5873 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5874 expression->left = create_implicit_cast(left, arithmetic_type);
5875 expression->right = create_implicit_cast(right, arithmetic_type);
5876 expression->base.type = arithmetic_type;
5878 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5879 expression->base.type = type_left;
5880 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5881 expression->base.type = type_right;
5882 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5883 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5887 static void semantic_sub(binary_expression_t *expression)
5889 expression_t *const left = expression->left;
5890 expression_t *const right = expression->right;
5891 type_t *const orig_type_left = left->base.type;
5892 type_t *const orig_type_right = right->base.type;
5893 type_t *const type_left = skip_typeref(orig_type_left);
5894 type_t *const type_right = skip_typeref(orig_type_right);
5897 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5898 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5899 expression->left = create_implicit_cast(left, arithmetic_type);
5900 expression->right = create_implicit_cast(right, arithmetic_type);
5901 expression->base.type = arithmetic_type;
5903 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5904 expression->base.type = type_left;
5905 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5906 if(!pointers_compatible(type_left, type_right)) {
5908 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5909 orig_type_left, orig_type_right);
5911 expression->base.type = type_ptrdiff_t;
5913 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5914 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5915 orig_type_left, orig_type_right);
5920 * Check the semantics of comparison expressions.
5922 * @param expression The expression to check.
5924 static void semantic_comparison(binary_expression_t *expression)
5926 expression_t *left = expression->left;
5927 expression_t *right = expression->right;
5928 type_t *orig_type_left = left->base.type;
5929 type_t *orig_type_right = right->base.type;
5931 type_t *type_left = skip_typeref(orig_type_left);
5932 type_t *type_right = skip_typeref(orig_type_right);
5934 /* TODO non-arithmetic types */
5935 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5936 if (warning.sign_compare &&
5937 (expression->base.kind != EXPR_BINARY_EQUAL &&
5938 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5939 (is_type_signed(type_left) != is_type_signed(type_right))) {
5940 warningf(expression->base.source_position,
5941 "comparison between signed and unsigned");
5943 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5944 expression->left = create_implicit_cast(left, arithmetic_type);
5945 expression->right = create_implicit_cast(right, arithmetic_type);
5946 expression->base.type = arithmetic_type;
5947 if (warning.float_equal &&
5948 (expression->base.kind == EXPR_BINARY_EQUAL ||
5949 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5950 is_type_float(arithmetic_type)) {
5951 warningf(expression->base.source_position,
5952 "comparing floating point with == or != is unsafe");
5954 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5955 /* TODO check compatibility */
5956 } else if (is_type_pointer(type_left)) {
5957 expression->right = create_implicit_cast(right, type_left);
5958 } else if (is_type_pointer(type_right)) {
5959 expression->left = create_implicit_cast(left, type_right);
5960 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5961 type_error_incompatible("invalid operands in comparison",
5962 expression->base.source_position,
5963 type_left, type_right);
5965 expression->base.type = type_int;
5968 static void semantic_arithmetic_assign(binary_expression_t *expression)
5970 expression_t *left = expression->left;
5971 expression_t *right = expression->right;
5972 type_t *orig_type_left = left->base.type;
5973 type_t *orig_type_right = right->base.type;
5975 type_t *type_left = skip_typeref(orig_type_left);
5976 type_t *type_right = skip_typeref(orig_type_right);
5978 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5979 /* TODO: improve error message */
5980 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5981 errorf(HERE, "operation needs arithmetic types");
5986 /* combined instructions are tricky. We can't create an implicit cast on
5987 * the left side, because we need the uncasted form for the store.
5988 * The ast2firm pass has to know that left_type must be right_type
5989 * for the arithmetic operation and create a cast by itself */
5990 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5991 expression->right = create_implicit_cast(right, arithmetic_type);
5992 expression->base.type = type_left;
5995 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5997 expression_t *const left = expression->left;
5998 expression_t *const right = expression->right;
5999 type_t *const orig_type_left = left->base.type;
6000 type_t *const orig_type_right = right->base.type;
6001 type_t *const type_left = skip_typeref(orig_type_left);
6002 type_t *const type_right = skip_typeref(orig_type_right);
6004 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6005 /* combined instructions are tricky. We can't create an implicit cast on
6006 * the left side, because we need the uncasted form for the store.
6007 * The ast2firm pass has to know that left_type must be right_type
6008 * for the arithmetic operation and create a cast by itself */
6009 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6010 expression->right = create_implicit_cast(right, arithmetic_type);
6011 expression->base.type = type_left;
6012 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6013 expression->base.type = type_left;
6014 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6015 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6020 * Check the semantic restrictions of a logical expression.
6022 static void semantic_logical_op(binary_expression_t *expression)
6024 expression_t *const left = expression->left;
6025 expression_t *const right = expression->right;
6026 type_t *const orig_type_left = left->base.type;
6027 type_t *const orig_type_right = right->base.type;
6028 type_t *const type_left = skip_typeref(orig_type_left);
6029 type_t *const type_right = skip_typeref(orig_type_right);
6031 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6032 /* TODO: improve error message */
6033 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6034 errorf(HERE, "operation needs scalar types");
6039 expression->base.type = type_int;
6043 * Checks if a compound type has constant fields.
6045 static bool has_const_fields(const compound_type_t *type)
6047 const scope_t *scope = &type->declaration->scope;
6048 const declaration_t *declaration = scope->declarations;
6050 for (; declaration != NULL; declaration = declaration->next) {
6051 if (declaration->namespc != NAMESPACE_NORMAL)
6054 const type_t *decl_type = skip_typeref(declaration->type);
6055 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6063 * Check the semantic restrictions of a binary assign expression.
6065 static void semantic_binexpr_assign(binary_expression_t *expression)
6067 expression_t *left = expression->left;
6068 type_t *orig_type_left = left->base.type;
6070 type_t *type_left = revert_automatic_type_conversion(left);
6071 type_left = skip_typeref(orig_type_left);
6073 /* must be a modifiable lvalue */
6074 if (is_type_array(type_left)) {
6075 errorf(HERE, "cannot assign to arrays ('%E')", left);
6078 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6079 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6083 if(is_type_incomplete(type_left)) {
6085 "left-hand side of assignment '%E' has incomplete type '%T'",
6086 left, orig_type_left);
6089 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6090 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6091 left, orig_type_left);
6095 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6096 "assignment", left->base.source_position);
6097 if (res_type == NULL) {
6098 errorf(expression->base.source_position,
6099 "cannot assign to '%T' from '%T'",
6100 orig_type_left, expression->right->base.type);
6102 expression->right = create_implicit_cast(expression->right, res_type);
6105 expression->base.type = orig_type_left;
6109 * Determine if the outermost operation (or parts thereof) of the given
6110 * expression has no effect in order to generate a warning about this fact.
6111 * Therefore in some cases this only examines some of the operands of the
6112 * expression (see comments in the function and examples below).
6114 * f() + 23; // warning, because + has no effect
6115 * x || f(); // no warning, because x controls execution of f()
6116 * x ? y : f(); // warning, because y has no effect
6117 * (void)x; // no warning to be able to suppress the warning
6118 * This function can NOT be used for an "expression has definitely no effect"-
6120 static bool expression_has_effect(const expression_t *const expr)
6122 switch (expr->kind) {
6123 case EXPR_UNKNOWN: break;
6124 case EXPR_INVALID: return true; /* do NOT warn */
6125 case EXPR_REFERENCE: return false;
6126 /* suppress the warning for microsoft __noop operations */
6127 case EXPR_CONST: return expr->conste.is_ms_noop;
6128 case EXPR_CHARACTER_CONSTANT: return false;
6129 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6130 case EXPR_STRING_LITERAL: return false;
6131 case EXPR_WIDE_STRING_LITERAL: return false;
6134 const call_expression_t *const call = &expr->call;
6135 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6138 switch (call->function->builtin_symbol.symbol->ID) {
6139 case T___builtin_va_end: return true;
6140 default: return false;
6144 /* Generate the warning if either the left or right hand side of a
6145 * conditional expression has no effect */
6146 case EXPR_CONDITIONAL: {
6147 const conditional_expression_t *const cond = &expr->conditional;
6149 expression_has_effect(cond->true_expression) &&
6150 expression_has_effect(cond->false_expression);
6153 case EXPR_SELECT: return false;
6154 case EXPR_ARRAY_ACCESS: return false;
6155 case EXPR_SIZEOF: return false;
6156 case EXPR_CLASSIFY_TYPE: return false;
6157 case EXPR_ALIGNOF: return false;
6159 case EXPR_FUNCNAME: return false;
6160 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6161 case EXPR_BUILTIN_CONSTANT_P: return false;
6162 case EXPR_BUILTIN_PREFETCH: return true;
6163 case EXPR_OFFSETOF: return false;
6164 case EXPR_VA_START: return true;
6165 case EXPR_VA_ARG: return true;
6166 case EXPR_STATEMENT: return true; // TODO
6167 case EXPR_COMPOUND_LITERAL: return false;
6169 case EXPR_UNARY_NEGATE: return false;
6170 case EXPR_UNARY_PLUS: return false;
6171 case EXPR_UNARY_BITWISE_NEGATE: return false;
6172 case EXPR_UNARY_NOT: return false;
6173 case EXPR_UNARY_DEREFERENCE: return false;
6174 case EXPR_UNARY_TAKE_ADDRESS: return false;
6175 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6176 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6177 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6178 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6180 /* Treat void casts as if they have an effect in order to being able to
6181 * suppress the warning */
6182 case EXPR_UNARY_CAST: {
6183 type_t *const type = skip_typeref(expr->base.type);
6184 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6187 case EXPR_UNARY_CAST_IMPLICIT: return true;
6188 case EXPR_UNARY_ASSUME: return true;
6189 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6191 case EXPR_BINARY_ADD: return false;
6192 case EXPR_BINARY_SUB: return false;
6193 case EXPR_BINARY_MUL: return false;
6194 case EXPR_BINARY_DIV: return false;
6195 case EXPR_BINARY_MOD: return false;
6196 case EXPR_BINARY_EQUAL: return false;
6197 case EXPR_BINARY_NOTEQUAL: return false;
6198 case EXPR_BINARY_LESS: return false;
6199 case EXPR_BINARY_LESSEQUAL: return false;
6200 case EXPR_BINARY_GREATER: return false;
6201 case EXPR_BINARY_GREATEREQUAL: return false;
6202 case EXPR_BINARY_BITWISE_AND: return false;
6203 case EXPR_BINARY_BITWISE_OR: return false;
6204 case EXPR_BINARY_BITWISE_XOR: return false;
6205 case EXPR_BINARY_SHIFTLEFT: return false;
6206 case EXPR_BINARY_SHIFTRIGHT: return false;
6207 case EXPR_BINARY_ASSIGN: return true;
6208 case EXPR_BINARY_MUL_ASSIGN: return true;
6209 case EXPR_BINARY_DIV_ASSIGN: return true;
6210 case EXPR_BINARY_MOD_ASSIGN: return true;
6211 case EXPR_BINARY_ADD_ASSIGN: return true;
6212 case EXPR_BINARY_SUB_ASSIGN: return true;
6213 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6214 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6215 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6216 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6217 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6219 /* Only examine the right hand side of && and ||, because the left hand
6220 * side already has the effect of controlling the execution of the right
6222 case EXPR_BINARY_LOGICAL_AND:
6223 case EXPR_BINARY_LOGICAL_OR:
6224 /* Only examine the right hand side of a comma expression, because the left
6225 * hand side has a separate warning */
6226 case EXPR_BINARY_COMMA:
6227 return expression_has_effect(expr->binary.right);
6229 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6230 case EXPR_BINARY_ISGREATER: return false;
6231 case EXPR_BINARY_ISGREATEREQUAL: return false;
6232 case EXPR_BINARY_ISLESS: return false;
6233 case EXPR_BINARY_ISLESSEQUAL: return false;
6234 case EXPR_BINARY_ISLESSGREATER: return false;
6235 case EXPR_BINARY_ISUNORDERED: return false;
6238 internal_errorf(HERE, "unexpected expression");
6241 static void semantic_comma(binary_expression_t *expression)
6243 if (warning.unused_value) {
6244 const expression_t *const left = expression->left;
6245 if (!expression_has_effect(left)) {
6246 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6249 expression->base.type = expression->right->base.type;
6252 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6253 static expression_t *parse_##binexpression_type(unsigned precedence, \
6254 expression_t *left) \
6257 source_position_t pos = HERE; \
6259 expression_t *right = parse_sub_expression(precedence + lr); \
6261 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6262 binexpr->base.source_position = pos; \
6263 binexpr->binary.left = left; \
6264 binexpr->binary.right = right; \
6265 sfunc(&binexpr->binary); \
6270 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6271 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6272 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6273 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6274 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6275 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6276 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6277 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6278 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6280 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6281 semantic_comparison, 1)
6282 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6283 semantic_comparison, 1)
6284 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6285 semantic_comparison, 1)
6286 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6287 semantic_comparison, 1)
6289 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6290 semantic_binexpr_arithmetic, 1)
6291 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6292 semantic_binexpr_arithmetic, 1)
6293 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6294 semantic_binexpr_arithmetic, 1)
6295 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6296 semantic_logical_op, 1)
6297 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6298 semantic_logical_op, 1)
6299 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6300 semantic_shift_op, 1)
6301 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6302 semantic_shift_op, 1)
6303 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6304 semantic_arithmetic_addsubb_assign, 0)
6305 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6306 semantic_arithmetic_addsubb_assign, 0)
6307 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6308 semantic_arithmetic_assign, 0)
6309 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6310 semantic_arithmetic_assign, 0)
6311 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6312 semantic_arithmetic_assign, 0)
6313 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6314 semantic_arithmetic_assign, 0)
6315 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6316 semantic_arithmetic_assign, 0)
6317 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6318 semantic_arithmetic_assign, 0)
6319 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6320 semantic_arithmetic_assign, 0)
6321 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6322 semantic_arithmetic_assign, 0)
6324 static expression_t *parse_sub_expression(unsigned precedence)
6326 if(token.type < 0) {
6327 return expected_expression_error();
6330 expression_parser_function_t *parser
6331 = &expression_parsers[token.type];
6332 source_position_t source_position = token.source_position;
6335 if(parser->parser != NULL) {
6336 left = parser->parser(parser->precedence);
6338 left = parse_primary_expression();
6340 assert(left != NULL);
6341 left->base.source_position = source_position;
6344 if(token.type < 0) {
6345 return expected_expression_error();
6348 parser = &expression_parsers[token.type];
6349 if(parser->infix_parser == NULL)
6351 if(parser->infix_precedence < precedence)
6354 left = parser->infix_parser(parser->infix_precedence, left);
6356 assert(left != NULL);
6357 assert(left->kind != EXPR_UNKNOWN);
6358 left->base.source_position = source_position;
6365 * Parse an expression.
6367 static expression_t *parse_expression(void)
6369 return parse_sub_expression(1);
6373 * Register a parser for a prefix-like operator with given precedence.
6375 * @param parser the parser function
6376 * @param token_type the token type of the prefix token
6377 * @param precedence the precedence of the operator
6379 static void register_expression_parser(parse_expression_function parser,
6380 int token_type, unsigned precedence)
6382 expression_parser_function_t *entry = &expression_parsers[token_type];
6384 if(entry->parser != NULL) {
6385 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6386 panic("trying to register multiple expression parsers for a token");
6388 entry->parser = parser;
6389 entry->precedence = precedence;
6393 * Register a parser for an infix operator with given precedence.
6395 * @param parser the parser function
6396 * @param token_type the token type of the infix operator
6397 * @param precedence the precedence of the operator
6399 static void register_infix_parser(parse_expression_infix_function parser,
6400 int token_type, unsigned precedence)
6402 expression_parser_function_t *entry = &expression_parsers[token_type];
6404 if(entry->infix_parser != NULL) {
6405 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6406 panic("trying to register multiple infix expression parsers for a "
6409 entry->infix_parser = parser;
6410 entry->infix_precedence = precedence;
6414 * Initialize the expression parsers.
6416 static void init_expression_parsers(void)
6418 memset(&expression_parsers, 0, sizeof(expression_parsers));
6420 register_infix_parser(parse_array_expression, '[', 30);
6421 register_infix_parser(parse_call_expression, '(', 30);
6422 register_infix_parser(parse_select_expression, '.', 30);
6423 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6424 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6426 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6429 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6430 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6431 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6432 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6433 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6434 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6435 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6436 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6437 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6438 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6439 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6440 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6441 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6442 T_EXCLAMATIONMARKEQUAL, 13);
6443 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6444 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6445 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6446 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6447 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6448 register_infix_parser(parse_conditional_expression, '?', 7);
6449 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6450 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6451 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6452 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6453 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6454 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6455 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6456 T_LESSLESSEQUAL, 2);
6457 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6458 T_GREATERGREATEREQUAL, 2);
6459 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6461 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6463 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6466 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6468 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6469 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6470 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6471 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6472 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6473 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6474 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6476 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6478 register_expression_parser(parse_sizeof, T_sizeof, 25);
6479 register_expression_parser(parse_alignof, T___alignof__, 25);
6480 register_expression_parser(parse_extension, T___extension__, 25);
6481 register_expression_parser(parse_builtin_classify_type,
6482 T___builtin_classify_type, 25);
6486 * Parse a asm statement constraints specification.
6488 static asm_constraint_t *parse_asm_constraints(void)
6490 asm_constraint_t *result = NULL;
6491 asm_constraint_t *last = NULL;
6493 while(token.type == T_STRING_LITERAL || token.type == '[') {
6494 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6495 memset(constraint, 0, sizeof(constraint[0]));
6497 if(token.type == '[') {
6499 if(token.type != T_IDENTIFIER) {
6500 parse_error_expected("while parsing asm constraint",
6504 constraint->symbol = token.v.symbol;
6509 constraint->constraints = parse_string_literals();
6511 constraint->expression = parse_expression();
6515 last->next = constraint;
6517 result = constraint;
6521 if(token.type != ',')
6532 * Parse a asm statement clobber specification.
6534 static asm_clobber_t *parse_asm_clobbers(void)
6536 asm_clobber_t *result = NULL;
6537 asm_clobber_t *last = NULL;
6539 while(token.type == T_STRING_LITERAL) {
6540 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6541 clobber->clobber = parse_string_literals();
6544 last->next = clobber;
6550 if(token.type != ',')
6559 * Parse an asm statement.
6561 static statement_t *parse_asm_statement(void)
6565 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6566 statement->base.source_position = token.source_position;
6568 asm_statement_t *asm_statement = &statement->asms;
6570 if(token.type == T_volatile) {
6572 asm_statement->is_volatile = true;
6576 add_anchor_token(')');
6577 add_anchor_token(':');
6578 asm_statement->asm_text = parse_string_literals();
6580 if(token.type != ':') {
6581 rem_anchor_token(':');
6586 asm_statement->inputs = parse_asm_constraints();
6587 if(token.type != ':') {
6588 rem_anchor_token(':');
6593 asm_statement->outputs = parse_asm_constraints();
6594 if(token.type != ':') {
6595 rem_anchor_token(':');
6598 rem_anchor_token(':');
6601 asm_statement->clobbers = parse_asm_clobbers();
6604 rem_anchor_token(')');
6609 return create_invalid_statement();
6613 * Parse a case statement.
6615 static statement_t *parse_case_statement(void)
6619 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6621 statement->base.source_position = token.source_position;
6622 statement->case_label.expression = parse_expression();
6624 if (c_mode & _GNUC) {
6625 if (token.type == T_DOTDOTDOT) {
6627 statement->case_label.end_range = parse_expression();
6633 if (! is_constant_expression(statement->case_label.expression)) {
6634 errorf(statement->base.source_position,
6635 "case label does not reduce to an integer constant");
6637 /* TODO: check if the case label is already known */
6638 if (current_switch != NULL) {
6639 /* link all cases into the switch statement */
6640 if (current_switch->last_case == NULL) {
6641 current_switch->first_case =
6642 current_switch->last_case = &statement->case_label;
6644 current_switch->last_case->next = &statement->case_label;
6647 errorf(statement->base.source_position,
6648 "case label not within a switch statement");
6651 statement->case_label.statement = parse_statement();
6655 return create_invalid_statement();
6659 * Finds an existing default label of a switch statement.
6661 static case_label_statement_t *
6662 find_default_label(const switch_statement_t *statement)
6664 case_label_statement_t *label = statement->first_case;
6665 for ( ; label != NULL; label = label->next) {
6666 if (label->expression == NULL)
6673 * Parse a default statement.
6675 static statement_t *parse_default_statement(void)
6679 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6681 statement->base.source_position = token.source_position;
6684 if (current_switch != NULL) {
6685 const case_label_statement_t *def_label = find_default_label(current_switch);
6686 if (def_label != NULL) {
6687 errorf(HERE, "multiple default labels in one switch");
6688 errorf(def_label->base.source_position,
6689 "this is the first default label");
6691 /* link all cases into the switch statement */
6692 if (current_switch->last_case == NULL) {
6693 current_switch->first_case =
6694 current_switch->last_case = &statement->case_label;
6696 current_switch->last_case->next = &statement->case_label;
6700 errorf(statement->base.source_position,
6701 "'default' label not within a switch statement");
6703 statement->case_label.statement = parse_statement();
6707 return create_invalid_statement();
6711 * Return the declaration for a given label symbol or create a new one.
6713 static declaration_t *get_label(symbol_t *symbol)
6715 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6716 assert(current_function != NULL);
6717 /* if we found a label in the same function, then we already created the
6719 if(candidate != NULL
6720 && candidate->parent_scope == ¤t_function->scope) {
6724 /* otherwise we need to create a new one */
6725 declaration_t *const declaration = allocate_declaration_zero();
6726 declaration->namespc = NAMESPACE_LABEL;
6727 declaration->symbol = symbol;
6729 label_push(declaration);
6735 * Parse a label statement.
6737 static statement_t *parse_label_statement(void)
6739 assert(token.type == T_IDENTIFIER);
6740 symbol_t *symbol = token.v.symbol;
6743 declaration_t *label = get_label(symbol);
6745 /* if source position is already set then the label is defined twice,
6746 * otherwise it was just mentioned in a goto so far */
6747 if(label->source_position.input_name != NULL) {
6748 errorf(HERE, "duplicate label '%Y'", symbol);
6749 errorf(label->source_position, "previous definition of '%Y' was here",
6752 label->source_position = token.source_position;
6755 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6757 statement->base.source_position = token.source_position;
6758 statement->label.label = label;
6762 if(token.type == '}') {
6763 /* TODO only warn? */
6765 warningf(HERE, "label at end of compound statement");
6766 statement->label.statement = create_empty_statement();
6768 errorf(HERE, "label at end of compound statement");
6769 statement->label.statement = create_invalid_statement();
6773 if (token.type == ';') {
6774 /* eat an empty statement here, to avoid the warning about an empty
6775 * after a label. label:; is commonly used to have a label before
6777 statement->label.statement = create_empty_statement();
6780 statement->label.statement = parse_statement();
6784 /* remember the labels's in a list for later checking */
6785 if (label_last == NULL) {
6786 label_first = &statement->label;
6788 label_last->next = &statement->label;
6790 label_last = &statement->label;
6796 * Parse an if statement.
6798 static statement_t *parse_if(void)
6802 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6803 statement->base.source_position = token.source_position;
6806 add_anchor_token(')');
6807 statement->ifs.condition = parse_expression();
6808 rem_anchor_token(')');
6811 add_anchor_token(T_else);
6812 statement->ifs.true_statement = parse_statement();
6813 rem_anchor_token(T_else);
6815 if(token.type == T_else) {
6817 statement->ifs.false_statement = parse_statement();
6822 return create_invalid_statement();
6826 * Parse a switch statement.
6828 static statement_t *parse_switch(void)
6832 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6833 statement->base.source_position = token.source_position;
6836 expression_t *const expr = parse_expression();
6837 type_t * type = skip_typeref(expr->base.type);
6838 if (is_type_integer(type)) {
6839 type = promote_integer(type);
6840 } else if (is_type_valid(type)) {
6841 errorf(expr->base.source_position,
6842 "switch quantity is not an integer, but '%T'", type);
6843 type = type_error_type;
6845 statement->switchs.expression = create_implicit_cast(expr, type);
6848 switch_statement_t *rem = current_switch;
6849 current_switch = &statement->switchs;
6850 statement->switchs.body = parse_statement();
6851 current_switch = rem;
6853 if (warning.switch_default
6854 && find_default_label(&statement->switchs) == NULL) {
6855 warningf(statement->base.source_position, "switch has no default case");
6860 return create_invalid_statement();
6863 static statement_t *parse_loop_body(statement_t *const loop)
6865 statement_t *const rem = current_loop;
6866 current_loop = loop;
6868 statement_t *const body = parse_statement();
6875 * Parse a while statement.
6877 static statement_t *parse_while(void)
6881 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6882 statement->base.source_position = token.source_position;
6885 add_anchor_token(')');
6886 statement->whiles.condition = parse_expression();
6887 rem_anchor_token(')');
6890 statement->whiles.body = parse_loop_body(statement);
6894 return create_invalid_statement();
6898 * Parse a do statement.
6900 static statement_t *parse_do(void)
6904 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6906 statement->base.source_position = token.source_position;
6908 add_anchor_token(T_while);
6909 statement->do_while.body = parse_loop_body(statement);
6910 rem_anchor_token(T_while);
6914 add_anchor_token(')');
6915 statement->do_while.condition = parse_expression();
6916 rem_anchor_token(')');
6922 return create_invalid_statement();
6926 * Parse a for statement.
6928 static statement_t *parse_for(void)
6932 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6933 statement->base.source_position = token.source_position;
6935 int top = environment_top();
6936 scope_t *last_scope = scope;
6937 set_scope(&statement->fors.scope);
6940 add_anchor_token(')');
6942 if(token.type != ';') {
6943 if(is_declaration_specifier(&token, false)) {
6944 parse_declaration(record_declaration);
6946 expression_t *const init = parse_expression();
6947 statement->fors.initialisation = init;
6948 if (warning.unused_value && !expression_has_effect(init)) {
6949 warningf(init->base.source_position,
6950 "initialisation of 'for'-statement has no effect");
6958 if(token.type != ';') {
6959 statement->fors.condition = parse_expression();
6962 if(token.type != ')') {
6963 expression_t *const step = parse_expression();
6964 statement->fors.step = step;
6965 if (warning.unused_value && !expression_has_effect(step)) {
6966 warningf(step->base.source_position,
6967 "step of 'for'-statement has no effect");
6970 rem_anchor_token(')');
6972 statement->fors.body = parse_loop_body(statement);
6974 assert(scope == &statement->fors.scope);
6975 set_scope(last_scope);
6976 environment_pop_to(top);
6981 rem_anchor_token(')');
6982 assert(scope == &statement->fors.scope);
6983 set_scope(last_scope);
6984 environment_pop_to(top);
6986 return create_invalid_statement();
6990 * Parse a goto statement.
6992 static statement_t *parse_goto(void)
6996 if(token.type != T_IDENTIFIER) {
6997 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
7001 symbol_t *symbol = token.v.symbol;
7004 declaration_t *label = get_label(symbol);
7006 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7007 statement->base.source_position = token.source_position;
7009 statement->gotos.label = label;
7011 /* remember the goto's in a list for later checking */
7012 if (goto_last == NULL) {
7013 goto_first = &statement->gotos;
7015 goto_last->next = &statement->gotos;
7017 goto_last = &statement->gotos;
7023 return create_invalid_statement();
7027 * Parse a continue statement.
7029 static statement_t *parse_continue(void)
7031 statement_t *statement;
7032 if (current_loop == NULL) {
7033 errorf(HERE, "continue statement not within loop");
7036 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7038 statement->base.source_position = token.source_position;
7046 return create_invalid_statement();
7050 * Parse a break statement.
7052 static statement_t *parse_break(void)
7054 statement_t *statement;
7055 if (current_switch == NULL && current_loop == NULL) {
7056 errorf(HERE, "break statement not within loop or switch");
7059 statement = allocate_statement_zero(STATEMENT_BREAK);
7061 statement->base.source_position = token.source_position;
7069 return create_invalid_statement();
7073 * Check if a given declaration represents a local variable.
7075 static bool is_local_var_declaration(const declaration_t *declaration) {
7076 switch ((storage_class_tag_t) declaration->storage_class) {
7077 case STORAGE_CLASS_AUTO:
7078 case STORAGE_CLASS_REGISTER: {
7079 const type_t *type = skip_typeref(declaration->type);
7080 if(is_type_function(type)) {
7092 * Check if a given declaration represents a variable.
7094 static bool is_var_declaration(const declaration_t *declaration) {
7095 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7098 const type_t *type = skip_typeref(declaration->type);
7099 return !is_type_function(type);
7103 * Check if a given expression represents a local variable.
7105 static bool is_local_variable(const expression_t *expression)
7107 if (expression->base.kind != EXPR_REFERENCE) {
7110 const declaration_t *declaration = expression->reference.declaration;
7111 return is_local_var_declaration(declaration);
7115 * Check if a given expression represents a local variable and
7116 * return its declaration then, else return NULL.
7118 declaration_t *expr_is_variable(const expression_t *expression)
7120 if (expression->base.kind != EXPR_REFERENCE) {
7123 declaration_t *declaration = expression->reference.declaration;
7124 if (is_var_declaration(declaration))
7130 * Parse a return statement.
7132 static statement_t *parse_return(void)
7134 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7135 statement->base.source_position = token.source_position;
7139 expression_t *return_value = NULL;
7140 if(token.type != ';') {
7141 return_value = parse_expression();
7145 const type_t *const func_type = current_function->type;
7146 assert(is_type_function(func_type));
7147 type_t *const return_type = skip_typeref(func_type->function.return_type);
7149 if(return_value != NULL) {
7150 type_t *return_value_type = skip_typeref(return_value->base.type);
7152 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7153 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7154 warningf(statement->base.source_position,
7155 "'return' with a value, in function returning void");
7156 return_value = NULL;
7158 type_t *const res_type = semantic_assign(return_type,
7159 return_value, "'return'", statement->base.source_position);
7160 if (res_type == NULL) {
7161 errorf(statement->base.source_position,
7162 "cannot return something of type '%T' in function returning '%T'",
7163 return_value->base.type, return_type);
7165 return_value = create_implicit_cast(return_value, res_type);
7168 /* check for returning address of a local var */
7169 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7170 const expression_t *expression = return_value->unary.value;
7171 if (is_local_variable(expression)) {
7172 warningf(statement->base.source_position,
7173 "function returns address of local variable");
7177 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7178 warningf(statement->base.source_position,
7179 "'return' without value, in function returning non-void");
7182 statement->returns.value = return_value;
7186 return create_invalid_statement();
7190 * Parse a declaration statement.
7192 static statement_t *parse_declaration_statement(void)
7194 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7196 statement->base.source_position = token.source_position;
7198 declaration_t *before = last_declaration;
7199 parse_declaration(record_declaration);
7201 if(before == NULL) {
7202 statement->declaration.declarations_begin = scope->declarations;
7204 statement->declaration.declarations_begin = before->next;
7206 statement->declaration.declarations_end = last_declaration;
7212 * Parse an expression statement, ie. expr ';'.
7214 static statement_t *parse_expression_statement(void)
7216 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7218 statement->base.source_position = token.source_position;
7219 expression_t *const expr = parse_expression();
7220 statement->expression.expression = expr;
7222 if (warning.unused_value && !expression_has_effect(expr)) {
7223 warningf(expr->base.source_position, "statement has no effect");
7230 return create_invalid_statement();
7234 * Parse a statement.
7236 static statement_t *parse_statement(void)
7238 statement_t *statement = NULL;
7240 /* declaration or statement */
7241 add_anchor_token(';');
7242 switch(token.type) {
7244 statement = parse_asm_statement();
7248 statement = parse_case_statement();
7252 statement = parse_default_statement();
7256 statement = parse_compound_statement();
7260 statement = parse_if();
7264 statement = parse_switch();
7268 statement = parse_while();
7272 statement = parse_do();
7276 statement = parse_for();
7280 statement = parse_goto();
7284 statement = parse_continue();
7288 statement = parse_break();
7292 statement = parse_return();
7296 if(warning.empty_statement) {
7297 warningf(HERE, "statement is empty");
7299 statement = create_empty_statement();
7304 if(look_ahead(1)->type == ':') {
7305 statement = parse_label_statement();
7309 if(is_typedef_symbol(token.v.symbol)) {
7310 statement = parse_declaration_statement();
7314 statement = parse_expression_statement();
7317 case T___extension__:
7318 /* this can be a prefix to a declaration or an expression statement */
7319 /* we simply eat it now and parse the rest with tail recursion */
7322 } while(token.type == T___extension__);
7323 statement = parse_statement();
7327 statement = parse_declaration_statement();
7331 statement = parse_expression_statement();
7334 rem_anchor_token(';');
7336 assert(statement != NULL
7337 && statement->base.source_position.input_name != NULL);
7343 * Parse a compound statement.
7345 static statement_t *parse_compound_statement(void)
7347 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7349 statement->base.source_position = token.source_position;
7352 add_anchor_token('}');
7354 int top = environment_top();
7355 scope_t *last_scope = scope;
7356 set_scope(&statement->compound.scope);
7358 statement_t *last_statement = NULL;
7360 while(token.type != '}' && token.type != T_EOF) {
7361 statement_t *sub_statement = parse_statement();
7362 if(is_invalid_statement(sub_statement)) {
7363 /* an error occurred. if we are at an anchor, return */
7369 if(last_statement != NULL) {
7370 last_statement->base.next = sub_statement;
7372 statement->compound.statements = sub_statement;
7375 while(sub_statement->base.next != NULL)
7376 sub_statement = sub_statement->base.next;
7378 last_statement = sub_statement;
7381 if(token.type == '}') {
7384 errorf(statement->base.source_position,
7385 "end of file while looking for closing '}'");
7389 rem_anchor_token('}');
7390 assert(scope == &statement->compound.scope);
7391 set_scope(last_scope);
7392 environment_pop_to(top);
7398 * Initialize builtin types.
7400 static void initialize_builtin_types(void)
7402 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7403 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7404 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7405 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7406 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7407 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7408 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7409 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7411 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7412 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7413 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7414 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7418 * Check for unused global static functions and variables
7420 static void check_unused_globals(void)
7422 if (!warning.unused_function && !warning.unused_variable)
7425 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7426 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7429 type_t *const type = decl->type;
7431 if (is_type_function(skip_typeref(type))) {
7432 if (!warning.unused_function || decl->is_inline)
7435 s = (decl->init.statement != NULL ? "defined" : "declared");
7437 if (!warning.unused_variable)
7443 warningf(decl->source_position, "'%#T' %s but not used",
7444 type, decl->symbol, s);
7449 * Parse a translation unit.
7451 static translation_unit_t *parse_translation_unit(void)
7453 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7455 assert(global_scope == NULL);
7456 global_scope = &unit->scope;
7458 assert(scope == NULL);
7459 set_scope(&unit->scope);
7461 initialize_builtin_types();
7463 while(token.type != T_EOF) {
7464 if (token.type == ';') {
7465 /* TODO error in strict mode */
7466 warningf(HERE, "stray ';' outside of function");
7469 parse_external_declaration();
7473 assert(scope == &unit->scope);
7475 last_declaration = NULL;
7477 assert(global_scope == &unit->scope);
7478 check_unused_globals();
7479 global_scope = NULL;
7487 * @return the translation unit or NULL if errors occurred.
7489 translation_unit_t *parse(void)
7491 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7492 label_stack = NEW_ARR_F(stack_entry_t, 0);
7493 diagnostic_count = 0;
7497 type_set_output(stderr);
7498 ast_set_output(stderr);
7500 lookahead_bufpos = 0;
7501 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7504 translation_unit_t *unit = parse_translation_unit();
7506 DEL_ARR_F(environment_stack);
7507 DEL_ARR_F(label_stack);
7513 * Initialize the parser.
7515 void init_parser(void)
7518 /* add predefined symbols for extended-decl-modifier */
7519 sym_align = symbol_table_insert("align");
7520 sym_allocate = symbol_table_insert("allocate");
7521 sym_dllimport = symbol_table_insert("dllimport");
7522 sym_dllexport = symbol_table_insert("dllexport");
7523 sym_naked = symbol_table_insert("naked");
7524 sym_noinline = symbol_table_insert("noinline");
7525 sym_noreturn = symbol_table_insert("noreturn");
7526 sym_nothrow = symbol_table_insert("nothrow");
7527 sym_novtable = symbol_table_insert("novtable");
7528 sym_property = symbol_table_insert("property");
7529 sym_get = symbol_table_insert("get");
7530 sym_put = symbol_table_insert("put");
7531 sym_selectany = symbol_table_insert("selectany");
7532 sym_thread = symbol_table_insert("thread");
7533 sym_uuid = symbol_table_insert("uuid");
7534 sym_deprecated = symbol_table_insert("deprecated");
7535 sym_restrict = symbol_table_insert("restrict");
7536 sym_noalias = symbol_table_insert("noalias");
7538 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7540 init_expression_parsers();
7541 obstack_init(&temp_obst);
7543 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7544 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7548 * Terminate the parser.
7550 void exit_parser(void)
7552 obstack_free(&temp_obst, NULL);