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,
990 } gnu_attribute_kind_t;
992 static const char *gnu_attribute_names[GNU_AK_LAST] = {
993 [GNU_AK_CONST] = "const",
994 [GNU_AK_VOLATILE] = "volatile",
995 [GNU_AK_CDECL] = "cdecl",
996 [GNU_AK_STDCALL] = "stdcall",
997 [GNU_AK_FASTCALL] = "fastcall",
998 [GNU_AK_DEPRECATED] = "deprecated",
999 [GNU_AK_NOINLINE] = "noinline",
1000 [GNU_AK_NORETURN] = "noreturn",
1001 [GNU_AK_NAKED] = "naked",
1002 [GNU_AK_PURE] = "pure",
1003 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1004 [GNU_AK_MALLOC] = "malloc",
1005 [GNU_AK_WEAK] = "weak",
1006 [GNU_AK_CONSTRUCTOR] = "constructor",
1007 [GNU_AK_DESTRUCTOR] = "destructor",
1008 [GNU_AK_NOTHROW] = "nothrow",
1009 [GNU_AK_ALIGNED] = "aligned",
1010 [GNU_AK_ALIAS] = "alias",
1011 [GNU_AK_SECTION] = "section",
1012 [GNU_AK_FORMAT] = "format",
1013 [GNU_AK_FORMAT_ARG] = "format_arg",
1014 [GNU_AK_WEAKREF] = "weakref",
1015 [GNU_AK_NONNULL] = "nonnull"
1019 * compare two string, ignoring double underscores on the second.
1021 static int strcmp_underscore(const char *s1, const char *s2) {
1022 if(s2[0] == '_' && s2[1] == '_') {
1024 size_t l1 = strlen(s1);
1025 if(l1 + 2 != strlen(s2)) {
1029 return strncmp(s1, s2, l1);
1031 return strcmp(s1, s2);
1035 * parse one constant expression argument.
1037 static expression_t *parse_gnu_attribute_const_arg(void) {
1038 expression_t *expression;
1039 add_anchor_token(')');
1040 expression = parse_constant_expression();
1041 rem_anchor_token(')');
1045 return create_invalid_expression();
1049 * parse a list of constant expressions argumnets.
1051 static expression_t *parse_gnu_attribute_const_arg_list(void) {
1052 expression_t *expression;
1053 add_anchor_token(')');
1054 add_anchor_token(',');
1056 expression = parse_constant_expression();
1057 if(token.type != ',')
1061 rem_anchor_token(',');
1062 rem_anchor_token(')');
1066 return create_invalid_expression();
1070 * parse one string literal argument.
1072 static string_t parse_gnu_attribute_string_arg(void) {
1073 string_t string = { NULL, 0 };
1074 add_anchor_token('(');
1075 if(token.type != T_STRING_LITERAL) {
1076 parse_error_expected("while parsing attribute directive", T_STRING_LITERAL);
1079 string = parse_string_literals();
1080 rem_anchor_token('(');
1087 * parse ( identifier, const expression, const expression )
1089 static void parse_gnu_attribute_format_args(void) {
1090 static const char *format_names[] = {
1098 if(token.type != T_IDENTIFIER) {
1099 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER);
1102 const char *name = token.v.symbol->string;
1103 for(i = 0; i < 4; ++i) {
1104 if(strcmp_underscore(format_names[i], name) == 0)
1108 if(warning.attribute)
1109 warningf(HERE, "'%s' is an unrecognized format function type", name);
1114 add_anchor_token(')');
1115 add_anchor_token(',');
1116 parse_constant_expression();
1117 rem_anchor_token(',');
1118 rem_anchor_token('(');
1121 add_anchor_token(')');
1122 parse_constant_expression();
1123 rem_anchor_token('(');
1131 * Parse one GNU attribute.
1133 * Note that attribute names can be specified WITH or WITHOUT
1134 * double underscores, ie const or __const__.
1136 * The following attributes are parsed without arguments
1154 * The following attributes are parsed with arguments
1155 * aligned( const expression )
1156 * alias( string literal )
1157 * section( string literal )
1158 * format( identifier, const expression, const expression )
1159 * format_arg( const expression )
1161 * The following attributes might have arguments
1162 * weak_ref( string literal )
1163 * non_null( const expression // ',' )
1165 static void parse_gnu_attribute(void)
1167 eat(T___attribute__);
1170 if(token.type != ')') {
1171 /* non-empty attribute list */
1174 if(token.type == T_const) {
1176 } else if(token.type == T_volatile) {
1178 } else if(token.type == T_cdecl) {
1179 /* __attribute__((cdecl)), WITH ms mode */
1181 } else if(token.type != T_IDENTIFIER) {
1182 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1185 const symbol_t *sym = token.v.symbol;
1189 gnu_attribute_kind_t kind;
1190 for(kind = 0; kind < GNU_AK_LAST; ++kind) {
1191 if(strcmp_underscore(gnu_attribute_names[kind], name) == 0)
1195 if(kind == GNU_AK_LAST) {
1196 if(warning.attribute)
1197 warningf(HERE, "'%s' attribute directive ignored", name);
1199 /* skip possible arguments */
1200 if(token.type == '(') {
1201 eat_until_matching_token(')');
1204 /* check for arguments */
1205 bool have_args = false;
1206 if(token.type == '(') {
1208 if(token.type == ')') {
1209 /* empty args are allowed */
1217 case GNU_AK_VOLATILE:
1219 case GNU_AK_STDCALL:
1220 case GNU_AK_FASTCALL:
1221 case GNU_AK_DEPRECATED:
1222 case GNU_AK_NOINLINE:
1223 case GNU_AK_NORETURN:
1226 case GNU_AK_ALWAYS_INLINE:
1229 case GNU_AK_CONSTRUCTOR:
1230 case GNU_AK_DESTRUCTOR:
1231 case GNU_AK_NOTHROW:
1233 /* should have no arguments */
1234 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1235 eat_until_matching_token('(');
1236 /* we have already consumend '(', so we stop before ')', eat it */
1241 case GNU_AK_ALIGNED:
1242 case GNU_AK_FORMAT_ARG:
1244 /* should have arguments */
1245 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1247 parse_gnu_attribute_const_arg();
1250 case GNU_AK_SECTION:
1252 /* should have arguments */
1253 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1255 parse_gnu_attribute_string_arg();
1259 /* should have arguments */
1260 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1262 parse_gnu_attribute_format_args();
1264 case GNU_AK_WEAKREF:
1265 /* may have one string argument */
1267 parse_gnu_attribute_string_arg();
1269 case GNU_AK_NONNULL:
1271 parse_gnu_attribute_const_arg_list();
1273 /* already handled */
1277 if(token.type != ',')
1289 * Parse GNU attributes.
1291 static void parse_attributes(void)
1294 switch(token.type) {
1295 case T___attribute__: {
1296 parse_gnu_attribute();
1302 if(token.type != T_STRING_LITERAL) {
1303 parse_error_expected("while parsing assembler attribute",
1305 eat_until_matching_token('(');
1308 parse_string_literals();
1313 goto attributes_finished;
1318 attributes_finished:
1322 static designator_t *parse_designation(void)
1324 designator_t *result = NULL;
1325 designator_t *last = NULL;
1328 designator_t *designator;
1329 switch(token.type) {
1331 designator = allocate_ast_zero(sizeof(designator[0]));
1332 designator->source_position = token.source_position;
1334 add_anchor_token(']');
1335 designator->array_index = parse_constant_expression();
1336 rem_anchor_token(']');
1340 designator = allocate_ast_zero(sizeof(designator[0]));
1341 designator->source_position = token.source_position;
1343 if(token.type != T_IDENTIFIER) {
1344 parse_error_expected("while parsing designator",
1348 designator->symbol = token.v.symbol;
1356 assert(designator != NULL);
1358 last->next = designator;
1360 result = designator;
1368 static initializer_t *initializer_from_string(array_type_t *type,
1369 const string_t *const string)
1371 /* TODO: check len vs. size of array type */
1374 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1375 initializer->string.string = *string;
1380 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1381 wide_string_t *const string)
1383 /* TODO: check len vs. size of array type */
1386 initializer_t *const initializer =
1387 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1388 initializer->wide_string.string = *string;
1394 * Build an initializer from a given expression.
1396 static initializer_t *initializer_from_expression(type_t *orig_type,
1397 expression_t *expression)
1399 /* TODO check that expression is a constant expression */
1401 /* § 6.7.8.14/15 char array may be initialized by string literals */
1402 type_t *type = skip_typeref(orig_type);
1403 type_t *expr_type_orig = expression->base.type;
1404 type_t *expr_type = skip_typeref(expr_type_orig);
1405 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1406 array_type_t *const array_type = &type->array;
1407 type_t *const element_type = skip_typeref(array_type->element_type);
1409 if (element_type->kind == TYPE_ATOMIC) {
1410 atomic_type_kind_t akind = element_type->atomic.akind;
1411 switch (expression->kind) {
1412 case EXPR_STRING_LITERAL:
1413 if (akind == ATOMIC_TYPE_CHAR
1414 || akind == ATOMIC_TYPE_SCHAR
1415 || akind == ATOMIC_TYPE_UCHAR) {
1416 return initializer_from_string(array_type,
1417 &expression->string.value);
1420 case EXPR_WIDE_STRING_LITERAL: {
1421 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1422 if (get_unqualified_type(element_type) == bare_wchar_type) {
1423 return initializer_from_wide_string(array_type,
1424 &expression->wide_string.value);
1434 type_t *const res_type = semantic_assign(type, expression, "initializer",
1435 expression->base.source_position);
1436 if (res_type == NULL)
1439 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1440 result->value.value = create_implicit_cast(expression, res_type);
1446 * Checks if a given expression can be used as an constant initializer.
1448 static bool is_initializer_constant(const expression_t *expression)
1450 return is_constant_expression(expression)
1451 || is_address_constant(expression);
1455 * Parses an scalar initializer.
1457 * § 6.7.8.11; eat {} without warning
1459 static initializer_t *parse_scalar_initializer(type_t *type,
1460 bool must_be_constant)
1462 /* there might be extra {} hierarchies */
1464 while(token.type == '{') {
1467 warningf(HERE, "extra curly braces around scalar initializer");
1472 expression_t *expression = parse_assignment_expression();
1473 if(must_be_constant && !is_initializer_constant(expression)) {
1474 errorf(expression->base.source_position,
1475 "Initialisation expression '%E' is not constant\n",
1479 initializer_t *initializer = initializer_from_expression(type, expression);
1481 if(initializer == NULL) {
1482 errorf(expression->base.source_position,
1483 "expression '%E' (type '%T') doesn't match expected type '%T'",
1484 expression, expression->base.type, type);
1489 bool additional_warning_displayed = false;
1491 if(token.type == ',') {
1494 if(token.type != '}') {
1495 if(!additional_warning_displayed) {
1496 warningf(HERE, "additional elements in scalar initializer");
1497 additional_warning_displayed = true;
1508 * An entry in the type path.
1510 typedef struct type_path_entry_t type_path_entry_t;
1511 struct type_path_entry_t {
1512 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1514 size_t index; /**< For array types: the current index. */
1515 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1520 * A type path expression a position inside compound or array types.
1522 typedef struct type_path_t type_path_t;
1523 struct type_path_t {
1524 type_path_entry_t *path; /**< An flexible array containing the current path. */
1525 type_t *top_type; /**< type of the element the path points */
1526 size_t max_index; /**< largest index in outermost array */
1530 * Prints a type path for debugging.
1532 static __attribute__((unused)) void debug_print_type_path(
1533 const type_path_t *path)
1535 size_t len = ARR_LEN(path->path);
1537 for(size_t i = 0; i < len; ++i) {
1538 const type_path_entry_t *entry = & path->path[i];
1540 type_t *type = skip_typeref(entry->type);
1541 if(is_type_compound(type)) {
1542 /* in gcc mode structs can have no members */
1543 if(entry->v.compound_entry == NULL) {
1547 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1548 } else if(is_type_array(type)) {
1549 fprintf(stderr, "[%zd]", entry->v.index);
1551 fprintf(stderr, "-INVALID-");
1554 if(path->top_type != NULL) {
1555 fprintf(stderr, " (");
1556 print_type(path->top_type);
1557 fprintf(stderr, ")");
1562 * Return the top type path entry, ie. in a path
1563 * (type).a.b returns the b.
1565 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1567 size_t len = ARR_LEN(path->path);
1569 return &path->path[len-1];
1573 * Enlarge the type path by an (empty) element.
1575 static type_path_entry_t *append_to_type_path(type_path_t *path)
1577 size_t len = ARR_LEN(path->path);
1578 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1580 type_path_entry_t *result = & path->path[len];
1581 memset(result, 0, sizeof(result[0]));
1586 * Descending into a sub-type. Enter the scope of the current
1589 static void descend_into_subtype(type_path_t *path)
1591 type_t *orig_top_type = path->top_type;
1592 type_t *top_type = skip_typeref(orig_top_type);
1594 assert(is_type_compound(top_type) || is_type_array(top_type));
1596 type_path_entry_t *top = append_to_type_path(path);
1597 top->type = top_type;
1599 if(is_type_compound(top_type)) {
1600 declaration_t *declaration = top_type->compound.declaration;
1601 declaration_t *entry = declaration->scope.declarations;
1602 top->v.compound_entry = entry;
1605 path->top_type = entry->type;
1607 path->top_type = NULL;
1610 assert(is_type_array(top_type));
1613 path->top_type = top_type->array.element_type;
1618 * Pop an entry from the given type path, ie. returning from
1619 * (type).a.b to (type).a
1621 static void ascend_from_subtype(type_path_t *path)
1623 type_path_entry_t *top = get_type_path_top(path);
1625 path->top_type = top->type;
1627 size_t len = ARR_LEN(path->path);
1628 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1632 * Pop entries from the given type path until the given
1633 * path level is reached.
1635 static void ascend_to(type_path_t *path, size_t top_path_level)
1637 size_t len = ARR_LEN(path->path);
1639 while(len > top_path_level) {
1640 ascend_from_subtype(path);
1641 len = ARR_LEN(path->path);
1645 static bool walk_designator(type_path_t *path, const designator_t *designator,
1646 bool used_in_offsetof)
1648 for( ; designator != NULL; designator = designator->next) {
1649 type_path_entry_t *top = get_type_path_top(path);
1650 type_t *orig_type = top->type;
1652 type_t *type = skip_typeref(orig_type);
1654 if(designator->symbol != NULL) {
1655 symbol_t *symbol = designator->symbol;
1656 if(!is_type_compound(type)) {
1657 if(is_type_valid(type)) {
1658 errorf(designator->source_position,
1659 "'.%Y' designator used for non-compound type '%T'",
1665 declaration_t *declaration = type->compound.declaration;
1666 declaration_t *iter = declaration->scope.declarations;
1667 for( ; iter != NULL; iter = iter->next) {
1668 if(iter->symbol == symbol) {
1673 errorf(designator->source_position,
1674 "'%T' has no member named '%Y'", orig_type, symbol);
1677 if(used_in_offsetof) {
1678 type_t *real_type = skip_typeref(iter->type);
1679 if(real_type->kind == TYPE_BITFIELD) {
1680 errorf(designator->source_position,
1681 "offsetof designator '%Y' may not specify bitfield",
1687 top->type = orig_type;
1688 top->v.compound_entry = iter;
1689 orig_type = iter->type;
1691 expression_t *array_index = designator->array_index;
1692 assert(designator->array_index != NULL);
1694 if(!is_type_array(type)) {
1695 if(is_type_valid(type)) {
1696 errorf(designator->source_position,
1697 "[%E] designator used for non-array type '%T'",
1698 array_index, orig_type);
1702 if(!is_type_valid(array_index->base.type)) {
1706 long index = fold_constant(array_index);
1707 if(!used_in_offsetof) {
1709 errorf(designator->source_position,
1710 "array index [%E] must be positive", array_index);
1713 if(type->array.size_constant == true) {
1714 long array_size = type->array.size;
1715 if(index >= array_size) {
1716 errorf(designator->source_position,
1717 "designator [%E] (%d) exceeds array size %d",
1718 array_index, index, array_size);
1724 top->type = orig_type;
1725 top->v.index = (size_t) index;
1726 orig_type = type->array.element_type;
1728 path->top_type = orig_type;
1730 if(designator->next != NULL) {
1731 descend_into_subtype(path);
1740 static void advance_current_object(type_path_t *path, size_t top_path_level)
1742 type_path_entry_t *top = get_type_path_top(path);
1744 type_t *type = skip_typeref(top->type);
1745 if(is_type_union(type)) {
1746 /* in unions only the first element is initialized */
1747 top->v.compound_entry = NULL;
1748 } else if(is_type_struct(type)) {
1749 declaration_t *entry = top->v.compound_entry;
1751 entry = entry->next;
1752 top->v.compound_entry = entry;
1754 path->top_type = entry->type;
1758 assert(is_type_array(type));
1762 if(!type->array.size_constant || top->v.index < type->array.size) {
1767 /* we're past the last member of the current sub-aggregate, try if we
1768 * can ascend in the type hierarchy and continue with another subobject */
1769 size_t len = ARR_LEN(path->path);
1771 if(len > top_path_level) {
1772 ascend_from_subtype(path);
1773 advance_current_object(path, top_path_level);
1775 path->top_type = NULL;
1780 * skip until token is found.
1782 static void skip_until(int type) {
1783 while(token.type != type) {
1784 if(token.type == T_EOF)
1791 * skip any {...} blocks until a closing braket is reached.
1793 static void skip_initializers(void)
1795 if(token.type == '{')
1798 while(token.type != '}') {
1799 if(token.type == T_EOF)
1801 if(token.type == '{') {
1809 static initializer_t *create_empty_initializer(void)
1811 static initializer_t empty_initializer
1812 = { .list = { { INITIALIZER_LIST }, 0 } };
1813 return &empty_initializer;
1817 * Parse a part of an initialiser for a struct or union,
1819 static initializer_t *parse_sub_initializer(type_path_t *path,
1820 type_t *outer_type, size_t top_path_level,
1821 parse_initializer_env_t *env)
1823 if(token.type == '}') {
1824 /* empty initializer */
1825 return create_empty_initializer();
1828 type_t *orig_type = path->top_type;
1829 type_t *type = NULL;
1831 if (orig_type == NULL) {
1832 /* We are initializing an empty compound. */
1834 type = skip_typeref(orig_type);
1836 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1837 * initializers in this case. */
1838 if(!is_type_valid(type)) {
1839 skip_initializers();
1840 return create_empty_initializer();
1844 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1847 designator_t *designator = NULL;
1848 if(token.type == '.' || token.type == '[') {
1849 designator = parse_designation();
1851 /* reset path to toplevel, evaluate designator from there */
1852 ascend_to(path, top_path_level);
1853 if(!walk_designator(path, designator, false)) {
1854 /* can't continue after designation error */
1858 initializer_t *designator_initializer
1859 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1860 designator_initializer->designator.designator = designator;
1861 ARR_APP1(initializer_t*, initializers, designator_initializer);
1866 if(token.type == '{') {
1867 if(type != NULL && is_type_scalar(type)) {
1868 sub = parse_scalar_initializer(type, env->must_be_constant);
1872 if (env->declaration != NULL)
1873 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1874 env->declaration->symbol);
1876 errorf(HERE, "extra brace group at end of initializer");
1878 descend_into_subtype(path);
1880 add_anchor_token('}');
1881 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1883 rem_anchor_token('}');
1886 ascend_from_subtype(path);
1890 goto error_parse_next;
1894 /* must be an expression */
1895 expression_t *expression = parse_assignment_expression();
1897 if(env->must_be_constant && !is_initializer_constant(expression)) {
1898 errorf(expression->base.source_position,
1899 "Initialisation expression '%E' is not constant\n",
1904 /* we are already outside, ... */
1908 /* handle { "string" } special case */
1909 if((expression->kind == EXPR_STRING_LITERAL
1910 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1911 && outer_type != NULL) {
1912 sub = initializer_from_expression(outer_type, expression);
1914 if(token.type == ',') {
1917 if(token.type != '}') {
1918 warningf(HERE, "excessive elements in initializer for type '%T'",
1921 /* TODO: eat , ... */
1926 /* descend into subtypes until expression matches type */
1928 orig_type = path->top_type;
1929 type = skip_typeref(orig_type);
1931 sub = initializer_from_expression(orig_type, expression);
1935 if(!is_type_valid(type)) {
1938 if(is_type_scalar(type)) {
1939 errorf(expression->base.source_position,
1940 "expression '%E' doesn't match expected type '%T'",
1941 expression, orig_type);
1945 descend_into_subtype(path);
1949 /* update largest index of top array */
1950 const type_path_entry_t *first = &path->path[0];
1951 type_t *first_type = first->type;
1952 first_type = skip_typeref(first_type);
1953 if(is_type_array(first_type)) {
1954 size_t index = first->v.index;
1955 if(index > path->max_index)
1956 path->max_index = index;
1960 /* append to initializers list */
1961 ARR_APP1(initializer_t*, initializers, sub);
1964 if(env->declaration != NULL)
1965 warningf(HERE, "excess elements in struct initializer for '%Y'",
1966 env->declaration->symbol);
1968 warningf(HERE, "excess elements in struct initializer");
1972 if(token.type == '}') {
1976 if(token.type == '}') {
1981 /* advance to the next declaration if we are not at the end */
1982 advance_current_object(path, top_path_level);
1983 orig_type = path->top_type;
1984 if(orig_type != NULL)
1985 type = skip_typeref(orig_type);
1991 size_t len = ARR_LEN(initializers);
1992 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1993 initializer_t *result = allocate_ast_zero(size);
1994 result->kind = INITIALIZER_LIST;
1995 result->list.len = len;
1996 memcpy(&result->list.initializers, initializers,
1997 len * sizeof(initializers[0]));
1999 DEL_ARR_F(initializers);
2000 ascend_to(path, top_path_level);
2005 skip_initializers();
2006 DEL_ARR_F(initializers);
2007 ascend_to(path, top_path_level);
2012 * Parses an initializer. Parsers either a compound literal
2013 * (env->declaration == NULL) or an initializer of a declaration.
2015 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2017 type_t *type = skip_typeref(env->type);
2018 initializer_t *result = NULL;
2021 if(is_type_scalar(type)) {
2022 result = parse_scalar_initializer(type, env->must_be_constant);
2023 } else if(token.type == '{') {
2027 memset(&path, 0, sizeof(path));
2028 path.top_type = env->type;
2029 path.path = NEW_ARR_F(type_path_entry_t, 0);
2031 descend_into_subtype(&path);
2033 add_anchor_token('}');
2034 result = parse_sub_initializer(&path, env->type, 1, env);
2035 rem_anchor_token('}');
2037 max_index = path.max_index;
2038 DEL_ARR_F(path.path);
2042 /* parse_scalar_initializer() also works in this case: we simply
2043 * have an expression without {} around it */
2044 result = parse_scalar_initializer(type, env->must_be_constant);
2047 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2048 * the array type size */
2049 if(is_type_array(type) && type->array.size_expression == NULL
2050 && result != NULL) {
2052 switch (result->kind) {
2053 case INITIALIZER_LIST:
2054 size = max_index + 1;
2057 case INITIALIZER_STRING:
2058 size = result->string.string.size;
2061 case INITIALIZER_WIDE_STRING:
2062 size = result->wide_string.string.size;
2066 internal_errorf(HERE, "invalid initializer type");
2069 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2070 cnst->base.type = type_size_t;
2071 cnst->conste.v.int_value = size;
2073 type_t *new_type = duplicate_type(type);
2075 new_type->array.size_expression = cnst;
2076 new_type->array.size_constant = true;
2077 new_type->array.size = size;
2078 env->type = new_type;
2086 static declaration_t *append_declaration(declaration_t *declaration);
2088 static declaration_t *parse_compound_type_specifier(bool is_struct)
2096 symbol_t *symbol = NULL;
2097 declaration_t *declaration = NULL;
2099 if (token.type == T___attribute__) {
2104 if(token.type == T_IDENTIFIER) {
2105 symbol = token.v.symbol;
2109 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2111 declaration = get_declaration(symbol, NAMESPACE_UNION);
2113 } else if(token.type != '{') {
2115 parse_error_expected("while parsing struct type specifier",
2116 T_IDENTIFIER, '{', 0);
2118 parse_error_expected("while parsing union type specifier",
2119 T_IDENTIFIER, '{', 0);
2125 if(declaration == NULL) {
2126 declaration = allocate_declaration_zero();
2127 declaration->namespc =
2128 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2129 declaration->source_position = token.source_position;
2130 declaration->symbol = symbol;
2131 declaration->parent_scope = scope;
2132 if (symbol != NULL) {
2133 environment_push(declaration);
2135 append_declaration(declaration);
2138 if(token.type == '{') {
2139 if(declaration->init.is_defined) {
2140 assert(symbol != NULL);
2141 errorf(HERE, "multiple definitions of '%s %Y'",
2142 is_struct ? "struct" : "union", symbol);
2143 declaration->scope.declarations = NULL;
2145 declaration->init.is_defined = true;
2147 parse_compound_type_entries(declaration);
2154 static void parse_enum_entries(type_t *const enum_type)
2158 if(token.type == '}') {
2160 errorf(HERE, "empty enum not allowed");
2164 add_anchor_token('}');
2166 if(token.type != T_IDENTIFIER) {
2167 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2169 rem_anchor_token('}');
2173 declaration_t *const entry = allocate_declaration_zero();
2174 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2175 entry->type = enum_type;
2176 entry->symbol = token.v.symbol;
2177 entry->source_position = token.source_position;
2180 if(token.type == '=') {
2182 expression_t *value = parse_constant_expression();
2184 value = create_implicit_cast(value, enum_type);
2185 entry->init.enum_value = value;
2190 record_declaration(entry);
2192 if(token.type != ',')
2195 } while(token.type != '}');
2196 rem_anchor_token('}');
2204 static type_t *parse_enum_specifier(void)
2208 declaration_t *declaration;
2211 if(token.type == T_IDENTIFIER) {
2212 symbol = token.v.symbol;
2215 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2216 } else if(token.type != '{') {
2217 parse_error_expected("while parsing enum type specifier",
2218 T_IDENTIFIER, '{', 0);
2225 if(declaration == NULL) {
2226 declaration = allocate_declaration_zero();
2227 declaration->namespc = NAMESPACE_ENUM;
2228 declaration->source_position = token.source_position;
2229 declaration->symbol = symbol;
2230 declaration->parent_scope = scope;
2233 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2234 type->enumt.declaration = declaration;
2236 if(token.type == '{') {
2237 if(declaration->init.is_defined) {
2238 errorf(HERE, "multiple definitions of enum %Y", symbol);
2240 if (symbol != NULL) {
2241 environment_push(declaration);
2243 append_declaration(declaration);
2244 declaration->init.is_defined = 1;
2246 parse_enum_entries(type);
2254 * if a symbol is a typedef to another type, return true
2256 static bool is_typedef_symbol(symbol_t *symbol)
2258 const declaration_t *const declaration =
2259 get_declaration(symbol, NAMESPACE_NORMAL);
2261 declaration != NULL &&
2262 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2265 static type_t *parse_typeof(void)
2272 add_anchor_token(')');
2274 expression_t *expression = NULL;
2277 switch(token.type) {
2278 case T___extension__:
2279 /* this can be a prefix to a typename or an expression */
2280 /* we simply eat it now. */
2283 } while(token.type == T___extension__);
2287 if(is_typedef_symbol(token.v.symbol)) {
2288 type = parse_typename();
2290 expression = parse_expression();
2291 type = expression->base.type;
2296 type = parse_typename();
2300 expression = parse_expression();
2301 type = expression->base.type;
2305 rem_anchor_token(')');
2308 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2309 typeof_type->typeoft.expression = expression;
2310 typeof_type->typeoft.typeof_type = type;
2318 SPECIFIER_SIGNED = 1 << 0,
2319 SPECIFIER_UNSIGNED = 1 << 1,
2320 SPECIFIER_LONG = 1 << 2,
2321 SPECIFIER_INT = 1 << 3,
2322 SPECIFIER_DOUBLE = 1 << 4,
2323 SPECIFIER_CHAR = 1 << 5,
2324 SPECIFIER_SHORT = 1 << 6,
2325 SPECIFIER_LONG_LONG = 1 << 7,
2326 SPECIFIER_FLOAT = 1 << 8,
2327 SPECIFIER_BOOL = 1 << 9,
2328 SPECIFIER_VOID = 1 << 10,
2329 SPECIFIER_INT8 = 1 << 11,
2330 SPECIFIER_INT16 = 1 << 12,
2331 SPECIFIER_INT32 = 1 << 13,
2332 SPECIFIER_INT64 = 1 << 14,
2333 SPECIFIER_INT128 = 1 << 15,
2334 #ifdef PROVIDE_COMPLEX
2335 SPECIFIER_COMPLEX = 1 << 16,
2336 SPECIFIER_IMAGINARY = 1 << 17,
2340 static type_t *create_builtin_type(symbol_t *const symbol,
2341 type_t *const real_type)
2343 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2344 type->builtin.symbol = symbol;
2345 type->builtin.real_type = real_type;
2347 type_t *result = typehash_insert(type);
2348 if (type != result) {
2355 static type_t *get_typedef_type(symbol_t *symbol)
2357 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2358 if(declaration == NULL
2359 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2362 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2363 type->typedeft.declaration = declaration;
2369 * check for the allowed MS alignment values.
2371 static bool check_elignment_value(long long intvalue) {
2372 if(intvalue < 1 || intvalue > 8192) {
2373 errorf(HERE, "illegal alignment value");
2376 unsigned v = (unsigned)intvalue;
2377 for(unsigned i = 1; i <= 8192; i += i) {
2381 errorf(HERE, "alignment must be power of two");
2385 #define DET_MOD(name, tag) do { \
2386 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2387 *modifiers |= tag; \
2390 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2392 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2395 if(token.type == T_restrict) {
2397 DET_MOD(restrict, DM_RESTRICT);
2399 } else if(token.type != T_IDENTIFIER)
2401 symbol_t *symbol = token.v.symbol;
2402 if(symbol == sym_align) {
2405 if(token.type != T_INTEGER)
2407 if(check_elignment_value(token.v.intvalue)) {
2408 if(specifiers->alignment != 0)
2409 warningf(HERE, "align used more than once");
2410 specifiers->alignment = (unsigned char)token.v.intvalue;
2414 } else if(symbol == sym_allocate) {
2417 if(token.type != T_IDENTIFIER)
2419 (void)token.v.symbol;
2421 } else if(symbol == sym_dllimport) {
2423 DET_MOD(dllimport, DM_DLLIMPORT);
2424 } else if(symbol == sym_dllexport) {
2426 DET_MOD(dllexport, DM_DLLEXPORT);
2427 } else if(symbol == sym_thread) {
2429 DET_MOD(thread, DM_THREAD);
2430 } else if(symbol == sym_naked) {
2432 DET_MOD(naked, DM_NAKED);
2433 } else if(symbol == sym_noinline) {
2435 DET_MOD(noinline, DM_NOINLINE);
2436 } else if(symbol == sym_noreturn) {
2438 DET_MOD(noreturn, DM_NORETURN);
2439 } else if(symbol == sym_nothrow) {
2441 DET_MOD(nothrow, DM_NOTHROW);
2442 } else if(symbol == sym_novtable) {
2444 DET_MOD(novtable, DM_NOVTABLE);
2445 } else if(symbol == sym_property) {
2449 bool is_get = false;
2450 if(token.type != T_IDENTIFIER)
2452 if(token.v.symbol == sym_get) {
2454 } else if(token.v.symbol == sym_put) {
2456 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2461 if(token.type != T_IDENTIFIER)
2464 if(specifiers->get_property_sym != NULL) {
2465 errorf(HERE, "get property name already specified");
2467 specifiers->get_property_sym = token.v.symbol;
2470 if(specifiers->put_property_sym != NULL) {
2471 errorf(HERE, "put property name already specified");
2473 specifiers->put_property_sym = token.v.symbol;
2477 if(token.type == ',') {
2484 } else if(symbol == sym_selectany) {
2486 DET_MOD(selectany, DM_SELECTANY);
2487 } else if(symbol == sym_uuid) {
2490 if(token.type != T_STRING_LITERAL)
2494 } else if(symbol == sym_deprecated) {
2496 if(specifiers->deprecated != 0)
2497 warningf(HERE, "deprecated used more than once");
2498 specifiers->deprecated = 1;
2499 if(token.type == '(') {
2501 if(token.type == T_STRING_LITERAL) {
2502 specifiers->deprecated_string = token.v.string.begin;
2505 errorf(HERE, "string literal expected");
2509 } else if(symbol == sym_noalias) {
2511 DET_MOD(noalias, DM_NOALIAS);
2513 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2515 if(token.type == '(')
2519 if (token.type == ',')
2526 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2528 type_t *type = NULL;
2529 unsigned type_qualifiers = 0;
2530 unsigned type_specifiers = 0;
2533 specifiers->source_position = token.source_position;
2536 switch(token.type) {
2539 #define MATCH_STORAGE_CLASS(token, class) \
2541 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2542 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2544 specifiers->declared_storage_class = class; \
2548 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2549 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2550 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2551 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2552 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2557 add_anchor_token(')');
2558 parse_microsoft_extended_decl_modifier(specifiers);
2559 rem_anchor_token(')');
2564 switch (specifiers->declared_storage_class) {
2565 case STORAGE_CLASS_NONE:
2566 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2569 case STORAGE_CLASS_EXTERN:
2570 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2573 case STORAGE_CLASS_STATIC:
2574 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2578 errorf(HERE, "multiple storage classes in declaration specifiers");
2584 /* type qualifiers */
2585 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2587 type_qualifiers |= qualifier; \
2591 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2592 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2593 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2594 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2595 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2596 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2597 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2598 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2600 case T___extension__:
2605 /* type specifiers */
2606 #define MATCH_SPECIFIER(token, specifier, name) \
2609 if(type_specifiers & specifier) { \
2610 errorf(HERE, "multiple " name " type specifiers given"); \
2612 type_specifiers |= specifier; \
2616 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2617 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2618 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2619 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2620 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2621 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2622 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2623 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2624 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2625 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2626 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2627 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2628 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2629 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2630 #ifdef PROVIDE_COMPLEX
2631 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2632 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2634 case T__forceinline:
2635 /* only in microsoft mode */
2636 specifiers->decl_modifiers |= DM_FORCEINLINE;
2640 specifiers->is_inline = true;
2645 if(type_specifiers & SPECIFIER_LONG_LONG) {
2646 errorf(HERE, "multiple type specifiers given");
2647 } else if(type_specifiers & SPECIFIER_LONG) {
2648 type_specifiers |= SPECIFIER_LONG_LONG;
2650 type_specifiers |= SPECIFIER_LONG;
2655 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2657 type->compound.declaration = parse_compound_type_specifier(true);
2661 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2663 type->compound.declaration = parse_compound_type_specifier(false);
2667 type = parse_enum_specifier();
2670 type = parse_typeof();
2672 case T___builtin_va_list:
2673 type = duplicate_type(type_valist);
2677 case T___attribute__:
2681 case T_IDENTIFIER: {
2682 /* only parse identifier if we haven't found a type yet */
2683 if(type != NULL || type_specifiers != 0)
2684 goto finish_specifiers;
2686 type_t *typedef_type = get_typedef_type(token.v.symbol);
2688 if(typedef_type == NULL)
2689 goto finish_specifiers;
2692 type = typedef_type;
2696 /* function specifier */
2698 goto finish_specifiers;
2705 atomic_type_kind_t atomic_type;
2707 /* match valid basic types */
2708 switch(type_specifiers) {
2709 case SPECIFIER_VOID:
2710 atomic_type = ATOMIC_TYPE_VOID;
2712 case SPECIFIER_CHAR:
2713 atomic_type = ATOMIC_TYPE_CHAR;
2715 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2716 atomic_type = ATOMIC_TYPE_SCHAR;
2718 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2719 atomic_type = ATOMIC_TYPE_UCHAR;
2721 case SPECIFIER_SHORT:
2722 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2723 case SPECIFIER_SHORT | SPECIFIER_INT:
2724 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2725 atomic_type = ATOMIC_TYPE_SHORT;
2727 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2728 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2729 atomic_type = ATOMIC_TYPE_USHORT;
2732 case SPECIFIER_SIGNED:
2733 case SPECIFIER_SIGNED | SPECIFIER_INT:
2734 atomic_type = ATOMIC_TYPE_INT;
2736 case SPECIFIER_UNSIGNED:
2737 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2738 atomic_type = ATOMIC_TYPE_UINT;
2740 case SPECIFIER_LONG:
2741 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2742 case SPECIFIER_LONG | SPECIFIER_INT:
2743 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2744 atomic_type = ATOMIC_TYPE_LONG;
2746 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2747 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2748 atomic_type = ATOMIC_TYPE_ULONG;
2750 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2751 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2752 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2753 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2755 atomic_type = ATOMIC_TYPE_LONGLONG;
2757 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2758 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2760 atomic_type = ATOMIC_TYPE_ULONGLONG;
2763 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2764 atomic_type = unsigned_int8_type_kind;
2767 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2768 atomic_type = unsigned_int16_type_kind;
2771 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2772 atomic_type = unsigned_int32_type_kind;
2775 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2776 atomic_type = unsigned_int64_type_kind;
2779 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2780 atomic_type = unsigned_int128_type_kind;
2783 case SPECIFIER_INT8:
2784 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2785 atomic_type = int8_type_kind;
2788 case SPECIFIER_INT16:
2789 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2790 atomic_type = int16_type_kind;
2793 case SPECIFIER_INT32:
2794 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2795 atomic_type = int32_type_kind;
2798 case SPECIFIER_INT64:
2799 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2800 atomic_type = int64_type_kind;
2803 case SPECIFIER_INT128:
2804 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2805 atomic_type = int128_type_kind;
2808 case SPECIFIER_FLOAT:
2809 atomic_type = ATOMIC_TYPE_FLOAT;
2811 case SPECIFIER_DOUBLE:
2812 atomic_type = ATOMIC_TYPE_DOUBLE;
2814 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2815 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2817 case SPECIFIER_BOOL:
2818 atomic_type = ATOMIC_TYPE_BOOL;
2820 #ifdef PROVIDE_COMPLEX
2821 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2822 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2824 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2825 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2827 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2828 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2830 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2831 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2833 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2834 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2836 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2837 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2841 /* invalid specifier combination, give an error message */
2842 if(type_specifiers == 0) {
2843 if (! strict_mode) {
2844 if (warning.implicit_int) {
2845 warningf(HERE, "no type specifiers in declaration, using 'int'");
2847 atomic_type = ATOMIC_TYPE_INT;
2850 errorf(HERE, "no type specifiers given in declaration");
2852 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2853 (type_specifiers & SPECIFIER_UNSIGNED)) {
2854 errorf(HERE, "signed and unsigned specifiers gives");
2855 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2856 errorf(HERE, "only integer types can be signed or unsigned");
2858 errorf(HERE, "multiple datatypes in declaration");
2860 atomic_type = ATOMIC_TYPE_INVALID;
2863 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2864 type->atomic.akind = atomic_type;
2867 if(type_specifiers != 0) {
2868 errorf(HERE, "multiple datatypes in declaration");
2872 type->base.qualifiers = type_qualifiers;
2873 /* FIXME: check type qualifiers here */
2875 type_t *result = typehash_insert(type);
2876 if(newtype && result != type) {
2880 specifiers->type = result;
2885 static type_qualifiers_t parse_type_qualifiers(void)
2887 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2890 switch(token.type) {
2891 /* type qualifiers */
2892 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2893 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2894 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2895 /* microsoft extended type modifiers */
2896 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2897 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2898 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2899 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2900 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2903 return type_qualifiers;
2908 static declaration_t *parse_identifier_list(void)
2910 declaration_t *declarations = NULL;
2911 declaration_t *last_declaration = NULL;
2913 declaration_t *const declaration = allocate_declaration_zero();
2914 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2915 declaration->source_position = token.source_position;
2916 declaration->symbol = token.v.symbol;
2919 if(last_declaration != NULL) {
2920 last_declaration->next = declaration;
2922 declarations = declaration;
2924 last_declaration = declaration;
2926 if(token.type != ',')
2929 } while(token.type == T_IDENTIFIER);
2931 return declarations;
2934 static void semantic_parameter(declaration_t *declaration)
2936 /* TODO: improve error messages */
2938 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2939 errorf(HERE, "typedef not allowed in parameter list");
2940 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2941 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2942 errorf(HERE, "parameter may only have none or register storage class");
2945 type_t *const orig_type = declaration->type;
2946 type_t * type = skip_typeref(orig_type);
2948 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2949 * into a pointer. § 6.7.5.3 (7) */
2950 if (is_type_array(type)) {
2951 type_t *const element_type = type->array.element_type;
2953 type = make_pointer_type(element_type, type->base.qualifiers);
2955 declaration->type = type;
2958 if(is_type_incomplete(type)) {
2959 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2960 orig_type, declaration->symbol);
2964 static declaration_t *parse_parameter(void)
2966 declaration_specifiers_t specifiers;
2967 memset(&specifiers, 0, sizeof(specifiers));
2969 parse_declaration_specifiers(&specifiers);
2971 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2973 semantic_parameter(declaration);
2978 static declaration_t *parse_parameters(function_type_t *type)
2980 if(token.type == T_IDENTIFIER) {
2981 symbol_t *symbol = token.v.symbol;
2982 if(!is_typedef_symbol(symbol)) {
2983 type->kr_style_parameters = true;
2984 return parse_identifier_list();
2988 if(token.type == ')') {
2989 type->unspecified_parameters = 1;
2992 if(token.type == T_void && look_ahead(1)->type == ')') {
2997 declaration_t *declarations = NULL;
2998 declaration_t *declaration;
2999 declaration_t *last_declaration = NULL;
3000 function_parameter_t *parameter;
3001 function_parameter_t *last_parameter = NULL;
3004 switch(token.type) {
3008 return declarations;
3011 case T___extension__:
3013 declaration = parse_parameter();
3015 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3016 memset(parameter, 0, sizeof(parameter[0]));
3017 parameter->type = declaration->type;
3019 if(last_parameter != NULL) {
3020 last_declaration->next = declaration;
3021 last_parameter->next = parameter;
3023 type->parameters = parameter;
3024 declarations = declaration;
3026 last_parameter = parameter;
3027 last_declaration = declaration;
3031 return declarations;
3033 if(token.type != ',')
3034 return declarations;
3044 } construct_type_kind_t;
3046 typedef struct construct_type_t construct_type_t;
3047 struct construct_type_t {
3048 construct_type_kind_t kind;
3049 construct_type_t *next;
3052 typedef struct parsed_pointer_t parsed_pointer_t;
3053 struct parsed_pointer_t {
3054 construct_type_t construct_type;
3055 type_qualifiers_t type_qualifiers;
3058 typedef struct construct_function_type_t construct_function_type_t;
3059 struct construct_function_type_t {
3060 construct_type_t construct_type;
3061 type_t *function_type;
3064 typedef struct parsed_array_t parsed_array_t;
3065 struct parsed_array_t {
3066 construct_type_t construct_type;
3067 type_qualifiers_t type_qualifiers;
3073 typedef struct construct_base_type_t construct_base_type_t;
3074 struct construct_base_type_t {
3075 construct_type_t construct_type;
3079 static construct_type_t *parse_pointer_declarator(void)
3083 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3084 memset(pointer, 0, sizeof(pointer[0]));
3085 pointer->construct_type.kind = CONSTRUCT_POINTER;
3086 pointer->type_qualifiers = parse_type_qualifiers();
3088 return (construct_type_t*) pointer;
3091 static construct_type_t *parse_array_declarator(void)
3094 add_anchor_token(']');
3096 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3097 memset(array, 0, sizeof(array[0]));
3098 array->construct_type.kind = CONSTRUCT_ARRAY;
3100 if(token.type == T_static) {
3101 array->is_static = true;
3105 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3106 if(type_qualifiers != 0) {
3107 if(token.type == T_static) {
3108 array->is_static = true;
3112 array->type_qualifiers = type_qualifiers;
3114 if(token.type == '*' && look_ahead(1)->type == ']') {
3115 array->is_variable = true;
3117 } else if(token.type != ']') {
3118 array->size = parse_assignment_expression();
3121 rem_anchor_token(']');
3124 return (construct_type_t*) array;
3129 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3132 add_anchor_token(')');
3135 if(declaration != NULL) {
3136 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
3138 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
3141 declaration_t *parameters = parse_parameters(&type->function);
3142 if(declaration != NULL) {
3143 declaration->scope.declarations = parameters;
3146 construct_function_type_t *construct_function_type =
3147 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3148 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3149 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3150 construct_function_type->function_type = type;
3152 rem_anchor_token(')');
3156 return (construct_type_t*) construct_function_type;
3159 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3160 bool may_be_abstract)
3162 /* construct a single linked list of construct_type_t's which describe
3163 * how to construct the final declarator type */
3164 construct_type_t *first = NULL;
3165 construct_type_t *last = NULL;
3168 while(token.type == '*') {
3169 construct_type_t *type = parse_pointer_declarator();
3180 /* TODO: find out if this is correct */
3183 construct_type_t *inner_types = NULL;
3185 switch(token.type) {
3187 if(declaration == NULL) {
3188 errorf(HERE, "no identifier expected in typename");
3190 declaration->symbol = token.v.symbol;
3191 declaration->source_position = token.source_position;
3197 add_anchor_token(')');
3198 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3199 rem_anchor_token(')');
3205 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3206 /* avoid a loop in the outermost scope, because eat_statement doesn't
3208 if(token.type == '}' && current_function == NULL) {
3216 construct_type_t *p = last;
3219 construct_type_t *type;
3220 switch(token.type) {
3222 type = parse_function_declarator(declaration);
3225 type = parse_array_declarator();
3228 goto declarator_finished;
3231 /* insert in the middle of the list (behind p) */
3233 type->next = p->next;
3244 declarator_finished:
3247 /* append inner_types at the end of the list, we don't to set last anymore
3248 * as it's not needed anymore */
3250 assert(first == NULL);
3251 first = inner_types;
3253 last->next = inner_types;
3261 static type_t *construct_declarator_type(construct_type_t *construct_list,
3264 construct_type_t *iter = construct_list;
3265 for( ; iter != NULL; iter = iter->next) {
3266 switch(iter->kind) {
3267 case CONSTRUCT_INVALID:
3268 internal_errorf(HERE, "invalid type construction found");
3269 case CONSTRUCT_FUNCTION: {
3270 construct_function_type_t *construct_function_type
3271 = (construct_function_type_t*) iter;
3273 type_t *function_type = construct_function_type->function_type;
3275 function_type->function.return_type = type;
3277 type_t *skipped_return_type = skip_typeref(type);
3278 if (is_type_function(skipped_return_type)) {
3279 errorf(HERE, "function returning function is not allowed");
3280 type = type_error_type;
3281 } else if (is_type_array(skipped_return_type)) {
3282 errorf(HERE, "function returning array is not allowed");
3283 type = type_error_type;
3285 type = function_type;
3290 case CONSTRUCT_POINTER: {
3291 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3292 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3293 pointer_type->pointer.points_to = type;
3294 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3296 type = pointer_type;
3300 case CONSTRUCT_ARRAY: {
3301 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3302 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3304 expression_t *size_expression = parsed_array->size;
3305 if(size_expression != NULL) {
3307 = create_implicit_cast(size_expression, type_size_t);
3310 array_type->base.qualifiers = parsed_array->type_qualifiers;
3311 array_type->array.element_type = type;
3312 array_type->array.is_static = parsed_array->is_static;
3313 array_type->array.is_variable = parsed_array->is_variable;
3314 array_type->array.size_expression = size_expression;
3316 if(size_expression != NULL) {
3317 if(is_constant_expression(size_expression)) {
3318 array_type->array.size_constant = true;
3319 array_type->array.size
3320 = fold_constant(size_expression);
3322 array_type->array.is_vla = true;
3326 type_t *skipped_type = skip_typeref(type);
3327 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3328 errorf(HERE, "array of void is not allowed");
3329 type = type_error_type;
3337 type_t *hashed_type = typehash_insert(type);
3338 if(hashed_type != type) {
3339 /* the function type was constructed earlier freeing it here will
3340 * destroy other types... */
3341 if(iter->kind != CONSTRUCT_FUNCTION) {
3351 static declaration_t *parse_declarator(
3352 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3354 declaration_t *const declaration = allocate_declaration_zero();
3355 declaration->declared_storage_class = specifiers->declared_storage_class;
3356 declaration->modifiers = specifiers->decl_modifiers;
3357 declaration->deprecated = specifiers->deprecated;
3358 declaration->deprecated_string = specifiers->deprecated_string;
3359 declaration->get_property_sym = specifiers->get_property_sym;
3360 declaration->put_property_sym = specifiers->put_property_sym;
3361 declaration->is_inline = specifiers->is_inline;
3363 declaration->storage_class = specifiers->declared_storage_class;
3364 if(declaration->storage_class == STORAGE_CLASS_NONE
3365 && scope != global_scope) {
3366 declaration->storage_class = STORAGE_CLASS_AUTO;
3369 if(specifiers->alignment != 0) {
3370 /* TODO: add checks here */
3371 declaration->alignment = specifiers->alignment;
3374 construct_type_t *construct_type
3375 = parse_inner_declarator(declaration, may_be_abstract);
3376 type_t *const type = specifiers->type;
3377 declaration->type = construct_declarator_type(construct_type, type);
3379 if(construct_type != NULL) {
3380 obstack_free(&temp_obst, construct_type);
3386 static type_t *parse_abstract_declarator(type_t *base_type)
3388 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3390 type_t *result = construct_declarator_type(construct_type, base_type);
3391 if(construct_type != NULL) {
3392 obstack_free(&temp_obst, construct_type);
3398 static declaration_t *append_declaration(declaration_t* const declaration)
3400 if (last_declaration != NULL) {
3401 last_declaration->next = declaration;
3403 scope->declarations = declaration;
3405 last_declaration = declaration;
3410 * Check if the declaration of main is suspicious. main should be a
3411 * function with external linkage, returning int, taking either zero
3412 * arguments, two, or three arguments of appropriate types, ie.
3414 * int main([ int argc, char **argv [, char **env ] ]).
3416 * @param decl the declaration to check
3417 * @param type the function type of the declaration
3419 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3421 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3422 warningf(decl->source_position, "'main' is normally a non-static function");
3424 if (skip_typeref(func_type->return_type) != type_int) {
3425 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3427 const function_parameter_t *parm = func_type->parameters;
3429 type_t *const first_type = parm->type;
3430 if (!types_compatible(skip_typeref(first_type), type_int)) {
3431 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3435 type_t *const second_type = parm->type;
3436 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3437 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3441 type_t *const third_type = parm->type;
3442 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3443 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3447 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3451 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3457 * Check if a symbol is the equal to "main".
3459 static bool is_sym_main(const symbol_t *const sym)
3461 return strcmp(sym->string, "main") == 0;
3464 static declaration_t *internal_record_declaration(
3465 declaration_t *const declaration,
3466 const bool is_function_definition)
3468 const symbol_t *const symbol = declaration->symbol;
3469 const namespace_t namespc = (namespace_t)declaration->namespc;
3471 type_t *const orig_type = declaration->type;
3472 type_t *const type = skip_typeref(orig_type);
3473 if (is_type_function(type) &&
3474 type->function.unspecified_parameters &&
3475 warning.strict_prototypes) {
3476 warningf(declaration->source_position,
3477 "function declaration '%#T' is not a prototype",
3478 orig_type, declaration->symbol);
3481 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3482 check_type_of_main(declaration, &type->function);
3485 assert(declaration->symbol != NULL);
3486 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3488 assert(declaration != previous_declaration);
3489 if (previous_declaration != NULL) {
3490 if (previous_declaration->parent_scope == scope) {
3491 /* can happen for K&R style declarations */
3492 if(previous_declaration->type == NULL) {
3493 previous_declaration->type = declaration->type;
3496 const type_t *prev_type = skip_typeref(previous_declaration->type);
3497 if (!types_compatible(type, prev_type)) {
3498 errorf(declaration->source_position,
3499 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3500 orig_type, symbol, previous_declaration->type, symbol,
3501 previous_declaration->source_position);
3503 unsigned old_storage_class = previous_declaration->storage_class;
3504 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3505 errorf(declaration->source_position, "redeclaration of enum entry '%Y' (declared %P)",
3506 symbol, previous_declaration->source_position);
3507 return previous_declaration;
3510 unsigned new_storage_class = declaration->storage_class;
3512 if(is_type_incomplete(prev_type)) {
3513 previous_declaration->type = type;
3517 /* pretend no storage class means extern for function
3518 * declarations (except if the previous declaration is neither
3519 * none nor extern) */
3520 if (is_type_function(type)) {
3521 switch (old_storage_class) {
3522 case STORAGE_CLASS_NONE:
3523 old_storage_class = STORAGE_CLASS_EXTERN;
3525 case STORAGE_CLASS_EXTERN:
3526 if (is_function_definition) {
3527 if (warning.missing_prototypes &&
3528 prev_type->function.unspecified_parameters &&
3529 !is_sym_main(symbol)) {
3530 warningf(declaration->source_position,
3531 "no previous prototype for '%#T'",
3534 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3535 new_storage_class = STORAGE_CLASS_EXTERN;
3543 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3544 new_storage_class == STORAGE_CLASS_EXTERN) {
3545 warn_redundant_declaration:
3546 if (warning.redundant_decls) {
3547 warningf(declaration->source_position,
3548 "redundant declaration for '%Y' (declared %P)",
3549 symbol, previous_declaration->source_position);
3551 } else if (current_function == NULL) {
3552 if (old_storage_class != STORAGE_CLASS_STATIC &&
3553 new_storage_class == STORAGE_CLASS_STATIC) {
3554 errorf(declaration->source_position,
3555 "static declaration of '%Y' follows non-static declaration (declared %P)",
3556 symbol, previous_declaration->source_position);
3558 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3559 goto warn_redundant_declaration;
3561 if (new_storage_class == STORAGE_CLASS_NONE) {
3562 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3563 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3567 if (old_storage_class == new_storage_class) {
3568 errorf(declaration->source_position,
3569 "redeclaration of '%Y' (declared %P)",
3570 symbol, previous_declaration->source_position);
3572 errorf(declaration->source_position,
3573 "redeclaration of '%Y' with different linkage (declared %P)",
3574 symbol, previous_declaration->source_position);
3578 return previous_declaration;
3580 } else if (is_function_definition) {
3581 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3582 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3583 warningf(declaration->source_position,
3584 "no previous prototype for '%#T'", orig_type, symbol);
3585 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3586 warningf(declaration->source_position,
3587 "no previous declaration for '%#T'", orig_type,
3591 } else if (warning.missing_declarations &&
3592 scope == global_scope &&
3593 !is_type_function(type) && (
3594 declaration->storage_class == STORAGE_CLASS_NONE ||
3595 declaration->storage_class == STORAGE_CLASS_THREAD
3597 warningf(declaration->source_position,
3598 "no previous declaration for '%#T'", orig_type, symbol);
3601 assert(declaration->parent_scope == NULL);
3602 assert(scope != NULL);
3604 declaration->parent_scope = scope;
3606 environment_push(declaration);
3607 return append_declaration(declaration);
3610 static declaration_t *record_declaration(declaration_t *declaration)
3612 return internal_record_declaration(declaration, false);
3615 static declaration_t *record_function_definition(declaration_t *declaration)
3617 return internal_record_declaration(declaration, true);
3620 static void parser_error_multiple_definition(declaration_t *declaration,
3621 const source_position_t source_position)
3623 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
3624 declaration->symbol, declaration->source_position);
3627 static bool is_declaration_specifier(const token_t *token,
3628 bool only_type_specifiers)
3630 switch(token->type) {
3634 return is_typedef_symbol(token->v.symbol);
3636 case T___extension__:
3639 return !only_type_specifiers;
3646 static void parse_init_declarator_rest(declaration_t *declaration)
3650 type_t *orig_type = declaration->type;
3651 type_t *type = skip_typeref(orig_type);
3653 if(declaration->init.initializer != NULL) {
3654 parser_error_multiple_definition(declaration, token.source_position);
3657 bool must_be_constant = false;
3658 if(declaration->storage_class == STORAGE_CLASS_STATIC
3659 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3660 || declaration->parent_scope == global_scope) {
3661 must_be_constant = true;
3664 parse_initializer_env_t env;
3665 env.type = orig_type;
3666 env.must_be_constant = must_be_constant;
3667 env.declaration = declaration;
3669 initializer_t *initializer = parse_initializer(&env);
3671 if(env.type != orig_type) {
3672 orig_type = env.type;
3673 type = skip_typeref(orig_type);
3674 declaration->type = env.type;
3677 if(is_type_function(type)) {
3678 errorf(declaration->source_position,
3679 "initializers not allowed for function types at declator '%Y' (type '%T')",
3680 declaration->symbol, orig_type);
3682 declaration->init.initializer = initializer;
3686 /* parse rest of a declaration without any declarator */
3687 static void parse_anonymous_declaration_rest(
3688 const declaration_specifiers_t *specifiers,
3689 parsed_declaration_func finished_declaration)
3693 declaration_t *const declaration = allocate_declaration_zero();
3694 declaration->type = specifiers->type;
3695 declaration->declared_storage_class = specifiers->declared_storage_class;
3696 declaration->source_position = specifiers->source_position;
3697 declaration->modifiers = specifiers->decl_modifiers;
3699 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3700 warningf(declaration->source_position, "useless storage class in empty declaration");
3702 declaration->storage_class = STORAGE_CLASS_NONE;
3704 type_t *type = declaration->type;
3705 switch (type->kind) {
3706 case TYPE_COMPOUND_STRUCT:
3707 case TYPE_COMPOUND_UNION: {
3708 if (type->compound.declaration->symbol == NULL) {
3709 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3718 warningf(declaration->source_position, "empty declaration");
3722 finished_declaration(declaration);
3725 static void parse_declaration_rest(declaration_t *ndeclaration,
3726 const declaration_specifiers_t *specifiers,
3727 parsed_declaration_func finished_declaration)
3729 add_anchor_token(';');
3730 add_anchor_token('=');
3731 add_anchor_token(',');
3733 declaration_t *declaration = finished_declaration(ndeclaration);
3735 type_t *orig_type = declaration->type;
3736 type_t *type = skip_typeref(orig_type);
3738 if (type->kind != TYPE_FUNCTION &&
3739 declaration->is_inline &&
3740 is_type_valid(type)) {
3741 warningf(declaration->source_position,
3742 "variable '%Y' declared 'inline'\n", declaration->symbol);
3745 if(token.type == '=') {
3746 parse_init_declarator_rest(declaration);
3749 if(token.type != ',')
3753 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3758 rem_anchor_token(';');
3759 rem_anchor_token('=');
3760 rem_anchor_token(',');
3763 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3765 symbol_t *symbol = declaration->symbol;
3766 if(symbol == NULL) {
3767 errorf(HERE, "anonymous declaration not valid as function parameter");
3770 namespace_t namespc = (namespace_t) declaration->namespc;
3771 if(namespc != NAMESPACE_NORMAL) {
3772 return record_declaration(declaration);
3775 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3776 if(previous_declaration == NULL ||
3777 previous_declaration->parent_scope != scope) {
3778 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3783 if(previous_declaration->type == NULL) {
3784 previous_declaration->type = declaration->type;
3785 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3786 previous_declaration->storage_class = declaration->storage_class;
3787 previous_declaration->parent_scope = scope;
3788 return previous_declaration;
3790 return record_declaration(declaration);
3794 static void parse_declaration(parsed_declaration_func finished_declaration)
3796 declaration_specifiers_t specifiers;
3797 memset(&specifiers, 0, sizeof(specifiers));
3798 parse_declaration_specifiers(&specifiers);
3800 if(token.type == ';') {
3801 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3803 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3804 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3808 static void parse_kr_declaration_list(declaration_t *declaration)
3810 type_t *type = skip_typeref(declaration->type);
3811 if(!is_type_function(type))
3814 if(!type->function.kr_style_parameters)
3817 /* push function parameters */
3818 int top = environment_top();
3819 scope_t *last_scope = scope;
3820 set_scope(&declaration->scope);
3822 declaration_t *parameter = declaration->scope.declarations;
3823 for( ; parameter != NULL; parameter = parameter->next) {
3824 assert(parameter->parent_scope == NULL);
3825 parameter->parent_scope = scope;
3826 environment_push(parameter);
3829 /* parse declaration list */
3830 while(is_declaration_specifier(&token, false)) {
3831 parse_declaration(finished_kr_declaration);
3834 /* pop function parameters */
3835 assert(scope == &declaration->scope);
3836 set_scope(last_scope);
3837 environment_pop_to(top);
3839 /* update function type */
3840 type_t *new_type = duplicate_type(type);
3841 new_type->function.kr_style_parameters = false;
3843 function_parameter_t *parameters = NULL;
3844 function_parameter_t *last_parameter = NULL;
3846 declaration_t *parameter_declaration = declaration->scope.declarations;
3847 for( ; parameter_declaration != NULL;
3848 parameter_declaration = parameter_declaration->next) {
3849 type_t *parameter_type = parameter_declaration->type;
3850 if(parameter_type == NULL) {
3852 errorf(HERE, "no type specified for function parameter '%Y'",
3853 parameter_declaration->symbol);
3855 if (warning.implicit_int) {
3856 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3857 parameter_declaration->symbol);
3859 parameter_type = type_int;
3860 parameter_declaration->type = parameter_type;
3864 semantic_parameter(parameter_declaration);
3865 parameter_type = parameter_declaration->type;
3867 function_parameter_t *function_parameter
3868 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3869 memset(function_parameter, 0, sizeof(function_parameter[0]));
3871 function_parameter->type = parameter_type;
3872 if(last_parameter != NULL) {
3873 last_parameter->next = function_parameter;
3875 parameters = function_parameter;
3877 last_parameter = function_parameter;
3879 new_type->function.parameters = parameters;
3881 type = typehash_insert(new_type);
3882 if(type != new_type) {
3883 obstack_free(type_obst, new_type);
3886 declaration->type = type;
3889 static bool first_err = true;
3892 * When called with first_err set, prints the name of the current function,
3895 static void print_in_function(void) {
3898 diagnosticf("%s: In function '%Y':\n",
3899 current_function->source_position.input_name,
3900 current_function->symbol);
3905 * Check if all labels are defined in the current function.
3906 * Check if all labels are used in the current function.
3908 static void check_labels(void)
3910 for (const goto_statement_t *goto_statement = goto_first;
3911 goto_statement != NULL;
3912 goto_statement = goto_statement->next) {
3913 declaration_t *label = goto_statement->label;
3916 if (label->source_position.input_name == NULL) {
3917 print_in_function();
3918 errorf(goto_statement->base.source_position,
3919 "label '%Y' used but not defined", label->symbol);
3922 goto_first = goto_last = NULL;
3924 if (warning.unused_label) {
3925 for (const label_statement_t *label_statement = label_first;
3926 label_statement != NULL;
3927 label_statement = label_statement->next) {
3928 const declaration_t *label = label_statement->label;
3930 if (! label->used) {
3931 print_in_function();
3932 warningf(label_statement->base.source_position,
3933 "label '%Y' defined but not used", label->symbol);
3937 label_first = label_last = NULL;
3941 * Check declarations of current_function for unused entities.
3943 static void check_declarations(void)
3945 if (warning.unused_parameter) {
3946 const scope_t *scope = ¤t_function->scope;
3948 const declaration_t *parameter = scope->declarations;
3949 for (; parameter != NULL; parameter = parameter->next) {
3950 if (! parameter->used) {
3951 print_in_function();
3952 warningf(parameter->source_position,
3953 "unused parameter '%Y'", parameter->symbol);
3957 if (warning.unused_variable) {
3961 static void parse_external_declaration(void)
3963 /* function-definitions and declarations both start with declaration
3965 declaration_specifiers_t specifiers;
3966 memset(&specifiers, 0, sizeof(specifiers));
3968 add_anchor_token(';');
3969 parse_declaration_specifiers(&specifiers);
3970 rem_anchor_token(';');
3972 /* must be a declaration */
3973 if(token.type == ';') {
3974 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3978 add_anchor_token(',');
3979 add_anchor_token('=');
3980 rem_anchor_token(';');
3982 /* declarator is common to both function-definitions and declarations */
3983 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3985 rem_anchor_token(',');
3986 rem_anchor_token('=');
3987 rem_anchor_token(';');
3989 /* must be a declaration */
3990 if(token.type == ',' || token.type == '=' || token.type == ';') {
3991 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3995 /* must be a function definition */
3996 parse_kr_declaration_list(ndeclaration);
3998 if(token.type != '{') {
3999 parse_error_expected("while parsing function definition", '{', 0);
4000 eat_until_matching_token(';');
4004 type_t *type = ndeclaration->type;
4006 /* note that we don't skip typerefs: the standard doesn't allow them here
4007 * (so we can't use is_type_function here) */
4008 if(type->kind != TYPE_FUNCTION) {
4009 if (is_type_valid(type)) {
4010 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4011 type, ndeclaration->symbol);
4017 /* § 6.7.5.3 (14) a function definition with () means no
4018 * parameters (and not unspecified parameters) */
4019 if(type->function.unspecified_parameters) {
4020 type_t *duplicate = duplicate_type(type);
4021 duplicate->function.unspecified_parameters = false;
4023 type = typehash_insert(duplicate);
4024 if(type != duplicate) {
4025 obstack_free(type_obst, duplicate);
4027 ndeclaration->type = type;
4030 declaration_t *const declaration = record_function_definition(ndeclaration);
4031 if(ndeclaration != declaration) {
4032 declaration->scope = ndeclaration->scope;
4034 type = skip_typeref(declaration->type);
4036 /* push function parameters and switch scope */
4037 int top = environment_top();
4038 scope_t *last_scope = scope;
4039 set_scope(&declaration->scope);
4041 declaration_t *parameter = declaration->scope.declarations;
4042 for( ; parameter != NULL; parameter = parameter->next) {
4043 if(parameter->parent_scope == &ndeclaration->scope) {
4044 parameter->parent_scope = scope;
4046 assert(parameter->parent_scope == NULL
4047 || parameter->parent_scope == scope);
4048 parameter->parent_scope = scope;
4049 environment_push(parameter);
4052 if(declaration->init.statement != NULL) {
4053 parser_error_multiple_definition(declaration, token.source_position);
4055 goto end_of_parse_external_declaration;
4057 /* parse function body */
4058 int label_stack_top = label_top();
4059 declaration_t *old_current_function = current_function;
4060 current_function = declaration;
4062 declaration->init.statement = parse_compound_statement();
4065 check_declarations();
4067 assert(current_function == declaration);
4068 current_function = old_current_function;
4069 label_pop_to(label_stack_top);
4072 end_of_parse_external_declaration:
4073 assert(scope == &declaration->scope);
4074 set_scope(last_scope);
4075 environment_pop_to(top);
4078 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4079 source_position_t source_position)
4081 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4082 type->bitfield.base = base;
4083 type->bitfield.size = size;
4088 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4091 declaration_t *iter = compound_declaration->scope.declarations;
4092 for( ; iter != NULL; iter = iter->next) {
4093 if(iter->namespc != NAMESPACE_NORMAL)
4096 if(iter->symbol == NULL) {
4097 type_t *type = skip_typeref(iter->type);
4098 if(is_type_compound(type)) {
4099 declaration_t *result
4100 = find_compound_entry(type->compound.declaration, symbol);
4107 if(iter->symbol == symbol) {
4115 static void parse_compound_declarators(declaration_t *struct_declaration,
4116 const declaration_specifiers_t *specifiers)
4118 declaration_t *last_declaration = struct_declaration->scope.declarations;
4119 if(last_declaration != NULL) {
4120 while(last_declaration->next != NULL) {
4121 last_declaration = last_declaration->next;
4126 declaration_t *declaration;
4128 if(token.type == ':') {
4129 source_position_t source_position = HERE;
4132 type_t *base_type = specifiers->type;
4133 expression_t *size = parse_constant_expression();
4135 if(!is_type_integer(skip_typeref(base_type))) {
4136 errorf(HERE, "bitfield base type '%T' is not an integer type",
4140 type_t *type = make_bitfield_type(base_type, size, source_position);
4142 declaration = allocate_declaration_zero();
4143 declaration->namespc = NAMESPACE_NORMAL;
4144 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4145 declaration->storage_class = STORAGE_CLASS_NONE;
4146 declaration->source_position = source_position;
4147 declaration->modifiers = specifiers->decl_modifiers;
4148 declaration->type = type;
4150 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4152 type_t *orig_type = declaration->type;
4153 type_t *type = skip_typeref(orig_type);
4155 if(token.type == ':') {
4156 source_position_t source_position = HERE;
4158 expression_t *size = parse_constant_expression();
4160 if(!is_type_integer(type)) {
4161 errorf(HERE, "bitfield base type '%T' is not an "
4162 "integer type", orig_type);
4165 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
4166 declaration->type = bitfield_type;
4168 /* TODO we ignore arrays for now... what is missing is a check
4169 * that they're at the end of the struct */
4170 if(is_type_incomplete(type) && !is_type_array(type)) {
4172 "compound member '%Y' has incomplete type '%T'",
4173 declaration->symbol, orig_type);
4174 } else if(is_type_function(type)) {
4175 errorf(HERE, "compound member '%Y' must not have function "
4176 "type '%T'", declaration->symbol, orig_type);
4181 /* make sure we don't define a symbol multiple times */
4182 symbol_t *symbol = declaration->symbol;
4183 if(symbol != NULL) {
4184 declaration_t *prev_decl
4185 = find_compound_entry(struct_declaration, symbol);
4187 if(prev_decl != NULL) {
4188 assert(prev_decl->symbol == symbol);
4189 errorf(declaration->source_position,
4190 "multiple declarations of symbol '%Y' (declared %P)",
4191 symbol, prev_decl->source_position);
4195 /* append declaration */
4196 if(last_declaration != NULL) {
4197 last_declaration->next = declaration;
4199 struct_declaration->scope.declarations = declaration;
4201 last_declaration = declaration;
4203 if(token.type != ',')
4213 static void parse_compound_type_entries(declaration_t *compound_declaration)
4216 add_anchor_token('}');
4218 while(token.type != '}' && token.type != T_EOF) {
4219 declaration_specifiers_t specifiers;
4220 memset(&specifiers, 0, sizeof(specifiers));
4221 parse_declaration_specifiers(&specifiers);
4223 parse_compound_declarators(compound_declaration, &specifiers);
4225 rem_anchor_token('}');
4227 if(token.type == T_EOF) {
4228 errorf(HERE, "EOF while parsing struct");
4233 static type_t *parse_typename(void)
4235 declaration_specifiers_t specifiers;
4236 memset(&specifiers, 0, sizeof(specifiers));
4237 parse_declaration_specifiers(&specifiers);
4238 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4239 /* TODO: improve error message, user does probably not know what a
4240 * storage class is...
4242 errorf(HERE, "typename may not have a storage class");
4245 type_t *result = parse_abstract_declarator(specifiers.type);
4253 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4254 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4255 expression_t *left);
4257 typedef struct expression_parser_function_t expression_parser_function_t;
4258 struct expression_parser_function_t {
4259 unsigned precedence;
4260 parse_expression_function parser;
4261 unsigned infix_precedence;
4262 parse_expression_infix_function infix_parser;
4265 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4268 * Prints an error message if an expression was expected but not read
4270 static expression_t *expected_expression_error(void)
4272 /* skip the error message if the error token was read */
4273 if (token.type != T_ERROR) {
4274 errorf(HERE, "expected expression, got token '%K'", &token);
4278 return create_invalid_expression();
4282 * Parse a string constant.
4284 static expression_t *parse_string_const(void)
4287 if (token.type == T_STRING_LITERAL) {
4288 string_t res = token.v.string;
4290 while (token.type == T_STRING_LITERAL) {
4291 res = concat_strings(&res, &token.v.string);
4294 if (token.type != T_WIDE_STRING_LITERAL) {
4295 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4296 /* note: that we use type_char_ptr here, which is already the
4297 * automatic converted type. revert_automatic_type_conversion
4298 * will construct the array type */
4299 cnst->base.type = type_char_ptr;
4300 cnst->string.value = res;
4304 wres = concat_string_wide_string(&res, &token.v.wide_string);
4306 wres = token.v.wide_string;
4311 switch (token.type) {
4312 case T_WIDE_STRING_LITERAL:
4313 wres = concat_wide_strings(&wres, &token.v.wide_string);
4316 case T_STRING_LITERAL:
4317 wres = concat_wide_string_string(&wres, &token.v.string);
4321 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4322 cnst->base.type = type_wchar_t_ptr;
4323 cnst->wide_string.value = wres;
4332 * Parse an integer constant.
4334 static expression_t *parse_int_const(void)
4336 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4337 cnst->base.source_position = HERE;
4338 cnst->base.type = token.datatype;
4339 cnst->conste.v.int_value = token.v.intvalue;
4347 * Parse a character constant.
4349 static expression_t *parse_character_constant(void)
4351 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4353 cnst->base.source_position = HERE;
4354 cnst->base.type = token.datatype;
4355 cnst->conste.v.character = token.v.string;
4357 if (cnst->conste.v.character.size != 1) {
4358 if (warning.multichar && (c_mode & _GNUC)) {
4360 warningf(HERE, "multi-character character constant");
4362 errorf(HERE, "more than 1 characters in character constant");
4371 * Parse a wide character constant.
4373 static expression_t *parse_wide_character_constant(void)
4375 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4377 cnst->base.source_position = HERE;
4378 cnst->base.type = token.datatype;
4379 cnst->conste.v.wide_character = token.v.wide_string;
4381 if (cnst->conste.v.wide_character.size != 1) {
4382 if (warning.multichar && (c_mode & _GNUC)) {
4384 warningf(HERE, "multi-character character constant");
4386 errorf(HERE, "more than 1 characters in character constant");
4395 * Parse a float constant.
4397 static expression_t *parse_float_const(void)
4399 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4400 cnst->base.type = token.datatype;
4401 cnst->conste.v.float_value = token.v.floatvalue;
4408 static declaration_t *create_implicit_function(symbol_t *symbol,
4409 const source_position_t source_position)
4411 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4412 ntype->function.return_type = type_int;
4413 ntype->function.unspecified_parameters = true;
4415 type_t *type = typehash_insert(ntype);
4420 declaration_t *const declaration = allocate_declaration_zero();
4421 declaration->storage_class = STORAGE_CLASS_EXTERN;
4422 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4423 declaration->type = type;
4424 declaration->symbol = symbol;
4425 declaration->source_position = source_position;
4426 declaration->parent_scope = global_scope;
4428 scope_t *old_scope = scope;
4429 set_scope(global_scope);
4431 environment_push(declaration);
4432 /* prepends the declaration to the global declarations list */
4433 declaration->next = scope->declarations;
4434 scope->declarations = declaration;
4436 assert(scope == global_scope);
4437 set_scope(old_scope);
4443 * Creates a return_type (func)(argument_type) function type if not
4446 * @param return_type the return type
4447 * @param argument_type the argument type
4449 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4451 function_parameter_t *parameter
4452 = obstack_alloc(type_obst, sizeof(parameter[0]));
4453 memset(parameter, 0, sizeof(parameter[0]));
4454 parameter->type = argument_type;
4456 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4457 type->function.return_type = return_type;
4458 type->function.parameters = parameter;
4460 type_t *result = typehash_insert(type);
4461 if(result != type) {
4469 * Creates a function type for some function like builtins.
4471 * @param symbol the symbol describing the builtin
4473 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4475 switch(symbol->ID) {
4476 case T___builtin_alloca:
4477 return make_function_1_type(type_void_ptr, type_size_t);
4478 case T___builtin_nan:
4479 return make_function_1_type(type_double, type_char_ptr);
4480 case T___builtin_nanf:
4481 return make_function_1_type(type_float, type_char_ptr);
4482 case T___builtin_nand:
4483 return make_function_1_type(type_long_double, type_char_ptr);
4484 case T___builtin_va_end:
4485 return make_function_1_type(type_void, type_valist);
4487 internal_errorf(HERE, "not implemented builtin symbol found");
4492 * Performs automatic type cast as described in § 6.3.2.1.
4494 * @param orig_type the original type
4496 static type_t *automatic_type_conversion(type_t *orig_type)
4498 type_t *type = skip_typeref(orig_type);
4499 if(is_type_array(type)) {
4500 array_type_t *array_type = &type->array;
4501 type_t *element_type = array_type->element_type;
4502 unsigned qualifiers = array_type->type.qualifiers;
4504 return make_pointer_type(element_type, qualifiers);
4507 if(is_type_function(type)) {
4508 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4515 * reverts the automatic casts of array to pointer types and function
4516 * to function-pointer types as defined § 6.3.2.1
4518 type_t *revert_automatic_type_conversion(const expression_t *expression)
4520 switch (expression->kind) {
4521 case EXPR_REFERENCE: return expression->reference.declaration->type;
4522 case EXPR_SELECT: return expression->select.compound_entry->type;
4524 case EXPR_UNARY_DEREFERENCE: {
4525 const expression_t *const value = expression->unary.value;
4526 type_t *const type = skip_typeref(value->base.type);
4527 assert(is_type_pointer(type));
4528 return type->pointer.points_to;
4531 case EXPR_BUILTIN_SYMBOL:
4532 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4534 case EXPR_ARRAY_ACCESS: {
4535 const expression_t *array_ref = expression->array_access.array_ref;
4536 type_t *type_left = skip_typeref(array_ref->base.type);
4537 if (!is_type_valid(type_left))
4539 assert(is_type_pointer(type_left));
4540 return type_left->pointer.points_to;
4543 case EXPR_STRING_LITERAL: {
4544 size_t size = expression->string.value.size;
4545 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4548 case EXPR_WIDE_STRING_LITERAL: {
4549 size_t size = expression->wide_string.value.size;
4550 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4553 case EXPR_COMPOUND_LITERAL:
4554 return expression->compound_literal.type;
4559 return expression->base.type;
4562 static expression_t *parse_reference(void)
4564 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4566 reference_expression_t *ref = &expression->reference;
4567 ref->symbol = token.v.symbol;
4569 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4571 source_position_t source_position = token.source_position;
4574 if(declaration == NULL) {
4575 if (! strict_mode && token.type == '(') {
4576 /* an implicitly defined function */
4577 if (warning.implicit_function_declaration) {
4578 warningf(HERE, "implicit declaration of function '%Y'",
4582 declaration = create_implicit_function(ref->symbol,
4585 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4586 return create_invalid_expression();
4590 type_t *type = declaration->type;
4592 /* we always do the auto-type conversions; the & and sizeof parser contains
4593 * code to revert this! */
4594 type = automatic_type_conversion(type);
4596 ref->declaration = declaration;
4597 ref->base.type = type;
4599 /* this declaration is used */
4600 declaration->used = true;
4602 /* check for deprecated functions */
4603 if(declaration->deprecated != 0) {
4604 const char *prefix = "";
4605 if (is_type_function(declaration->type))
4606 prefix = "function ";
4608 if (declaration->deprecated_string != NULL) {
4609 warningf(source_position,
4610 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4611 declaration->deprecated_string);
4613 warningf(source_position,
4614 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4621 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4625 /* TODO check if explicit cast is allowed and issue warnings/errors */
4628 static expression_t *parse_compound_literal(type_t *type)
4630 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4632 parse_initializer_env_t env;
4634 env.declaration = NULL;
4635 env.must_be_constant = false;
4636 initializer_t *initializer = parse_initializer(&env);
4639 expression->compound_literal.initializer = initializer;
4640 expression->compound_literal.type = type;
4641 expression->base.type = automatic_type_conversion(type);
4647 * Parse a cast expression.
4649 static expression_t *parse_cast(void)
4651 source_position_t source_position = token.source_position;
4653 type_t *type = parse_typename();
4655 /* matching add_anchor_token() is at call site */
4656 rem_anchor_token(')');
4659 if(token.type == '{') {
4660 return parse_compound_literal(type);
4663 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4664 cast->base.source_position = source_position;
4666 expression_t *value = parse_sub_expression(20);
4668 check_cast_allowed(value, type);
4670 cast->base.type = type;
4671 cast->unary.value = value;
4675 return create_invalid_expression();
4679 * Parse a statement expression.
4681 static expression_t *parse_statement_expression(void)
4683 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4685 statement_t *statement = parse_compound_statement();
4686 expression->statement.statement = statement;
4687 expression->base.source_position = statement->base.source_position;
4689 /* find last statement and use its type */
4690 type_t *type = type_void;
4691 const statement_t *stmt = statement->compound.statements;
4693 while (stmt->base.next != NULL)
4694 stmt = stmt->base.next;
4696 if (stmt->kind == STATEMENT_EXPRESSION) {
4697 type = stmt->expression.expression->base.type;
4700 warningf(expression->base.source_position, "empty statement expression ({})");
4702 expression->base.type = type;
4708 return create_invalid_expression();
4712 * Parse a braced expression.
4714 static expression_t *parse_brace_expression(void)
4717 add_anchor_token(')');
4719 switch(token.type) {
4721 /* gcc extension: a statement expression */
4722 return parse_statement_expression();
4726 return parse_cast();
4728 if(is_typedef_symbol(token.v.symbol)) {
4729 return parse_cast();
4733 expression_t *result = parse_expression();
4734 rem_anchor_token(')');
4739 return create_invalid_expression();
4742 static expression_t *parse_function_keyword(void)
4747 if (current_function == NULL) {
4748 errorf(HERE, "'__func__' used outside of a function");
4751 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4752 expression->base.type = type_char_ptr;
4753 expression->funcname.kind = FUNCNAME_FUNCTION;
4758 static expression_t *parse_pretty_function_keyword(void)
4760 eat(T___PRETTY_FUNCTION__);
4762 if (current_function == NULL) {
4763 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4766 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4767 expression->base.type = type_char_ptr;
4768 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
4773 static expression_t *parse_funcsig_keyword(void)
4777 if (current_function == NULL) {
4778 errorf(HERE, "'__FUNCSIG__' used outside of a function");
4781 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4782 expression->base.type = type_char_ptr;
4783 expression->funcname.kind = FUNCNAME_FUNCSIG;
4788 static expression_t *parse_funcdname_keyword(void)
4790 eat(T___FUNCDNAME__);
4792 if (current_function == NULL) {
4793 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
4796 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4797 expression->base.type = type_char_ptr;
4798 expression->funcname.kind = FUNCNAME_FUNCDNAME;
4803 static designator_t *parse_designator(void)
4805 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4806 result->source_position = HERE;
4808 if(token.type != T_IDENTIFIER) {
4809 parse_error_expected("while parsing member designator",
4813 result->symbol = token.v.symbol;
4816 designator_t *last_designator = result;
4818 if(token.type == '.') {
4820 if(token.type != T_IDENTIFIER) {
4821 parse_error_expected("while parsing member designator",
4825 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4826 designator->source_position = HERE;
4827 designator->symbol = token.v.symbol;
4830 last_designator->next = designator;
4831 last_designator = designator;
4834 if(token.type == '[') {
4836 add_anchor_token(']');
4837 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4838 designator->source_position = HERE;
4839 designator->array_index = parse_expression();
4840 rem_anchor_token(']');
4842 if(designator->array_index == NULL) {
4846 last_designator->next = designator;
4847 last_designator = designator;
4859 * Parse the __builtin_offsetof() expression.
4861 static expression_t *parse_offsetof(void)
4863 eat(T___builtin_offsetof);
4865 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4866 expression->base.type = type_size_t;
4869 add_anchor_token(',');
4870 type_t *type = parse_typename();
4871 rem_anchor_token(',');
4873 add_anchor_token(')');
4874 designator_t *designator = parse_designator();
4875 rem_anchor_token(')');
4878 expression->offsetofe.type = type;
4879 expression->offsetofe.designator = designator;
4882 memset(&path, 0, sizeof(path));
4883 path.top_type = type;
4884 path.path = NEW_ARR_F(type_path_entry_t, 0);
4886 descend_into_subtype(&path);
4888 if(!walk_designator(&path, designator, true)) {
4889 return create_invalid_expression();
4892 DEL_ARR_F(path.path);
4896 return create_invalid_expression();
4900 * Parses a _builtin_va_start() expression.
4902 static expression_t *parse_va_start(void)
4904 eat(T___builtin_va_start);
4906 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4909 add_anchor_token(',');
4910 expression->va_starte.ap = parse_assignment_expression();
4911 rem_anchor_token(',');
4913 expression_t *const expr = parse_assignment_expression();
4914 if (expr->kind == EXPR_REFERENCE) {
4915 declaration_t *const decl = expr->reference.declaration;
4917 return create_invalid_expression();
4918 if (decl->parent_scope == ¤t_function->scope &&
4919 decl->next == NULL) {
4920 expression->va_starte.parameter = decl;
4925 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4927 return create_invalid_expression();
4931 * Parses a _builtin_va_arg() expression.
4933 static expression_t *parse_va_arg(void)
4935 eat(T___builtin_va_arg);
4937 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4940 expression->va_arge.ap = parse_assignment_expression();
4942 expression->base.type = parse_typename();
4947 return create_invalid_expression();
4950 static expression_t *parse_builtin_symbol(void)
4952 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4954 symbol_t *symbol = token.v.symbol;
4956 expression->builtin_symbol.symbol = symbol;
4959 type_t *type = get_builtin_symbol_type(symbol);
4960 type = automatic_type_conversion(type);
4962 expression->base.type = type;
4967 * Parses a __builtin_constant() expression.
4969 static expression_t *parse_builtin_constant(void)
4971 eat(T___builtin_constant_p);
4973 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4976 add_anchor_token(')');
4977 expression->builtin_constant.value = parse_assignment_expression();
4978 rem_anchor_token(')');
4980 expression->base.type = type_int;
4984 return create_invalid_expression();
4988 * Parses a __builtin_prefetch() expression.
4990 static expression_t *parse_builtin_prefetch(void)
4992 eat(T___builtin_prefetch);
4994 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4997 add_anchor_token(')');
4998 expression->builtin_prefetch.adr = parse_assignment_expression();
4999 if (token.type == ',') {
5001 expression->builtin_prefetch.rw = parse_assignment_expression();
5003 if (token.type == ',') {
5005 expression->builtin_prefetch.locality = parse_assignment_expression();
5007 rem_anchor_token(')');
5009 expression->base.type = type_void;
5013 return create_invalid_expression();
5017 * Parses a __builtin_is_*() compare expression.
5019 static expression_t *parse_compare_builtin(void)
5021 expression_t *expression;
5023 switch(token.type) {
5024 case T___builtin_isgreater:
5025 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5027 case T___builtin_isgreaterequal:
5028 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5030 case T___builtin_isless:
5031 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5033 case T___builtin_islessequal:
5034 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5036 case T___builtin_islessgreater:
5037 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5039 case T___builtin_isunordered:
5040 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5043 internal_errorf(HERE, "invalid compare builtin found");
5046 expression->base.source_position = HERE;
5050 expression->binary.left = parse_assignment_expression();
5052 expression->binary.right = parse_assignment_expression();
5055 type_t *const orig_type_left = expression->binary.left->base.type;
5056 type_t *const orig_type_right = expression->binary.right->base.type;
5058 type_t *const type_left = skip_typeref(orig_type_left);
5059 type_t *const type_right = skip_typeref(orig_type_right);
5060 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5061 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5062 type_error_incompatible("invalid operands in comparison",
5063 expression->base.source_position, orig_type_left, orig_type_right);
5066 semantic_comparison(&expression->binary);
5071 return create_invalid_expression();
5075 * Parses a __builtin_expect() expression.
5077 static expression_t *parse_builtin_expect(void)
5079 eat(T___builtin_expect);
5081 expression_t *expression
5082 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5085 expression->binary.left = parse_assignment_expression();
5087 expression->binary.right = parse_constant_expression();
5090 expression->base.type = expression->binary.left->base.type;
5094 return create_invalid_expression();
5098 * Parses a MS assume() expression.
5100 static expression_t *parse_assume(void) {
5103 expression_t *expression
5104 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5107 add_anchor_token(')');
5108 expression->unary.value = parse_assignment_expression();
5109 rem_anchor_token(')');
5112 expression->base.type = type_void;
5115 return create_invalid_expression();
5119 * Parse a microsoft __noop expression.
5121 static expression_t *parse_noop_expression(void) {
5122 source_position_t source_position = HERE;
5125 if (token.type == '(') {
5126 /* parse arguments */
5128 add_anchor_token(')');
5129 add_anchor_token(',');
5131 if(token.type != ')') {
5133 (void)parse_assignment_expression();
5134 if(token.type != ',')
5140 rem_anchor_token(',');
5141 rem_anchor_token(')');
5144 /* the result is a (int)0 */
5145 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5146 cnst->base.source_position = source_position;
5147 cnst->base.type = type_int;
5148 cnst->conste.v.int_value = 0;
5149 cnst->conste.is_ms_noop = true;
5154 return create_invalid_expression();
5158 * Parses a primary expression.
5160 static expression_t *parse_primary_expression(void)
5162 switch (token.type) {
5163 case T_INTEGER: return parse_int_const();
5164 case T_CHARACTER_CONSTANT: return parse_character_constant();
5165 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5166 case T_FLOATINGPOINT: return parse_float_const();
5167 case T_STRING_LITERAL:
5168 case T_WIDE_STRING_LITERAL: return parse_string_const();
5169 case T_IDENTIFIER: return parse_reference();
5170 case T___FUNCTION__:
5171 case T___func__: return parse_function_keyword();
5172 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5173 case T___FUNCSIG__: return parse_funcsig_keyword();
5174 case T___FUNCDNAME__: return parse_funcdname_keyword();
5175 case T___builtin_offsetof: return parse_offsetof();
5176 case T___builtin_va_start: return parse_va_start();
5177 case T___builtin_va_arg: return parse_va_arg();
5178 case T___builtin_expect: return parse_builtin_expect();
5179 case T___builtin_alloca:
5180 case T___builtin_nan:
5181 case T___builtin_nand:
5182 case T___builtin_nanf:
5183 case T___builtin_va_end: return parse_builtin_symbol();
5184 case T___builtin_isgreater:
5185 case T___builtin_isgreaterequal:
5186 case T___builtin_isless:
5187 case T___builtin_islessequal:
5188 case T___builtin_islessgreater:
5189 case T___builtin_isunordered: return parse_compare_builtin();
5190 case T___builtin_constant_p: return parse_builtin_constant();
5191 case T___builtin_prefetch: return parse_builtin_prefetch();
5192 case T__assume: return parse_assume();
5194 case '(': return parse_brace_expression();
5195 case T___noop: return parse_noop_expression();
5198 errorf(HERE, "unexpected token %K, expected an expression", &token);
5199 return create_invalid_expression();
5203 * Check if the expression has the character type and issue a warning then.
5205 static void check_for_char_index_type(const expression_t *expression) {
5206 type_t *const type = expression->base.type;
5207 const type_t *const base_type = skip_typeref(type);
5209 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5210 warning.char_subscripts) {
5211 warningf(expression->base.source_position,
5212 "array subscript has type '%T'", type);
5216 static expression_t *parse_array_expression(unsigned precedence,
5222 add_anchor_token(']');
5224 expression_t *inside = parse_expression();
5226 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5228 array_access_expression_t *array_access = &expression->array_access;
5230 type_t *const orig_type_left = left->base.type;
5231 type_t *const orig_type_inside = inside->base.type;
5233 type_t *const type_left = skip_typeref(orig_type_left);
5234 type_t *const type_inside = skip_typeref(orig_type_inside);
5236 type_t *return_type;
5237 if (is_type_pointer(type_left)) {
5238 return_type = type_left->pointer.points_to;
5239 array_access->array_ref = left;
5240 array_access->index = inside;
5241 check_for_char_index_type(inside);
5242 } else if (is_type_pointer(type_inside)) {
5243 return_type = type_inside->pointer.points_to;
5244 array_access->array_ref = inside;
5245 array_access->index = left;
5246 array_access->flipped = true;
5247 check_for_char_index_type(left);
5249 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5251 "array access on object with non-pointer types '%T', '%T'",
5252 orig_type_left, orig_type_inside);
5254 return_type = type_error_type;
5255 array_access->array_ref = create_invalid_expression();
5258 rem_anchor_token(']');
5259 if(token.type != ']') {
5260 parse_error_expected("Problem while parsing array access", ']', 0);
5265 return_type = automatic_type_conversion(return_type);
5266 expression->base.type = return_type;
5271 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5273 expression_t *tp_expression = allocate_expression_zero(kind);
5274 tp_expression->base.type = type_size_t;
5276 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5278 add_anchor_token(')');
5279 tp_expression->typeprop.type = parse_typename();
5280 rem_anchor_token(')');
5283 expression_t *expression = parse_sub_expression(precedence);
5284 expression->base.type = revert_automatic_type_conversion(expression);
5286 tp_expression->typeprop.type = expression->base.type;
5287 tp_expression->typeprop.tp_expression = expression;
5290 return tp_expression;
5292 return create_invalid_expression();
5295 static expression_t *parse_sizeof(unsigned precedence)
5298 return parse_typeprop(EXPR_SIZEOF, precedence);
5301 static expression_t *parse_alignof(unsigned precedence)
5304 return parse_typeprop(EXPR_SIZEOF, precedence);
5307 static expression_t *parse_select_expression(unsigned precedence,
5308 expression_t *compound)
5311 assert(token.type == '.' || token.type == T_MINUSGREATER);
5313 bool is_pointer = (token.type == T_MINUSGREATER);
5316 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5317 select->select.compound = compound;
5319 if(token.type != T_IDENTIFIER) {
5320 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5323 symbol_t *symbol = token.v.symbol;
5324 select->select.symbol = symbol;
5327 type_t *const orig_type = compound->base.type;
5328 type_t *const type = skip_typeref(orig_type);
5330 type_t *type_left = type;
5332 if (!is_type_pointer(type)) {
5333 if (is_type_valid(type)) {
5334 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5336 return create_invalid_expression();
5338 type_left = type->pointer.points_to;
5340 type_left = skip_typeref(type_left);
5342 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5343 type_left->kind != TYPE_COMPOUND_UNION) {
5344 if (is_type_valid(type_left)) {
5345 errorf(HERE, "request for member '%Y' in something not a struct or "
5346 "union, but '%T'", symbol, type_left);
5348 return create_invalid_expression();
5351 declaration_t *const declaration = type_left->compound.declaration;
5353 if(!declaration->init.is_defined) {
5354 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5356 return create_invalid_expression();
5359 declaration_t *iter = find_compound_entry(declaration, symbol);
5361 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5362 return create_invalid_expression();
5365 /* we always do the auto-type conversions; the & and sizeof parser contains
5366 * code to revert this! */
5367 type_t *expression_type = automatic_type_conversion(iter->type);
5369 select->select.compound_entry = iter;
5370 select->base.type = expression_type;
5372 if(expression_type->kind == TYPE_BITFIELD) {
5373 expression_t *extract
5374 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5375 extract->unary.value = select;
5376 extract->base.type = expression_type->bitfield.base;
5385 * Parse a call expression, ie. expression '( ... )'.
5387 * @param expression the function address
5389 static expression_t *parse_call_expression(unsigned precedence,
5390 expression_t *expression)
5393 expression_t *result = allocate_expression_zero(EXPR_CALL);
5394 result->base.source_position = expression->base.source_position;
5396 call_expression_t *call = &result->call;
5397 call->function = expression;
5399 type_t *const orig_type = expression->base.type;
5400 type_t *const type = skip_typeref(orig_type);
5402 function_type_t *function_type = NULL;
5403 if (is_type_pointer(type)) {
5404 type_t *const to_type = skip_typeref(type->pointer.points_to);
5406 if (is_type_function(to_type)) {
5407 function_type = &to_type->function;
5408 call->base.type = function_type->return_type;
5412 if (function_type == NULL && is_type_valid(type)) {
5413 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5416 /* parse arguments */
5418 add_anchor_token(')');
5419 add_anchor_token(',');
5421 if(token.type != ')') {
5422 call_argument_t *last_argument = NULL;
5425 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5427 argument->expression = parse_assignment_expression();
5428 if(last_argument == NULL) {
5429 call->arguments = argument;
5431 last_argument->next = argument;
5433 last_argument = argument;
5435 if(token.type != ',')
5440 rem_anchor_token(',');
5441 rem_anchor_token(')');
5444 if(function_type != NULL) {
5445 function_parameter_t *parameter = function_type->parameters;
5446 call_argument_t *argument = call->arguments;
5447 for( ; parameter != NULL && argument != NULL;
5448 parameter = parameter->next, argument = argument->next) {
5449 type_t *expected_type = parameter->type;
5450 /* TODO report scope in error messages */
5451 expression_t *const arg_expr = argument->expression;
5452 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call", arg_expr->base.source_position);
5453 if (res_type == NULL) {
5454 /* TODO improve error message */
5455 errorf(arg_expr->base.source_position,
5456 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5457 arg_expr, arg_expr->base.type, expected_type);
5459 argument->expression = create_implicit_cast(argument->expression, expected_type);
5462 /* too few parameters */
5463 if(parameter != NULL) {
5464 errorf(HERE, "too few arguments to function '%E'", expression);
5465 } else if(argument != NULL) {
5466 /* too many parameters */
5467 if(!function_type->variadic
5468 && !function_type->unspecified_parameters) {
5469 errorf(HERE, "too many arguments to function '%E'", expression);
5471 /* do default promotion */
5472 for( ; argument != NULL; argument = argument->next) {
5473 type_t *type = argument->expression->base.type;
5475 type = skip_typeref(type);
5476 if(is_type_integer(type)) {
5477 type = promote_integer(type);
5478 } else if(type == type_float) {
5482 argument->expression
5483 = create_implicit_cast(argument->expression, type);
5486 check_format(&result->call);
5489 check_format(&result->call);
5495 return create_invalid_expression();
5498 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5500 static bool same_compound_type(const type_t *type1, const type_t *type2)
5503 is_type_compound(type1) &&
5504 type1->kind == type2->kind &&
5505 type1->compound.declaration == type2->compound.declaration;
5509 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5511 * @param expression the conditional expression
5513 static expression_t *parse_conditional_expression(unsigned precedence,
5514 expression_t *expression)
5517 add_anchor_token(':');
5519 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5521 conditional_expression_t *conditional = &result->conditional;
5522 conditional->condition = expression;
5525 type_t *const condition_type_orig = expression->base.type;
5526 type_t *const condition_type = skip_typeref(condition_type_orig);
5527 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5528 type_error("expected a scalar type in conditional condition",
5529 expression->base.source_position, condition_type_orig);
5532 expression_t *true_expression = parse_expression();
5533 rem_anchor_token(':');
5535 expression_t *false_expression = parse_sub_expression(precedence);
5537 type_t *const orig_true_type = true_expression->base.type;
5538 type_t *const orig_false_type = false_expression->base.type;
5539 type_t *const true_type = skip_typeref(orig_true_type);
5540 type_t *const false_type = skip_typeref(orig_false_type);
5543 type_t *result_type;
5544 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5545 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5546 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5547 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5548 warningf(expression->base.source_position,
5549 "ISO C forbids conditional expression with only one void side");
5551 result_type = type_void;
5552 } else if (is_type_arithmetic(true_type)
5553 && is_type_arithmetic(false_type)) {
5554 result_type = semantic_arithmetic(true_type, false_type);
5556 true_expression = create_implicit_cast(true_expression, result_type);
5557 false_expression = create_implicit_cast(false_expression, result_type);
5559 conditional->true_expression = true_expression;
5560 conditional->false_expression = false_expression;
5561 conditional->base.type = result_type;
5562 } else if (same_compound_type(true_type, false_type)) {
5563 /* just take 1 of the 2 types */
5564 result_type = true_type;
5565 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5566 type_t *pointer_type;
5568 expression_t *other_expression;
5569 if (is_type_pointer(true_type)) {
5570 pointer_type = true_type;
5571 other_type = false_type;
5572 other_expression = false_expression;
5574 pointer_type = false_type;
5575 other_type = true_type;
5576 other_expression = true_expression;
5579 if(is_type_pointer(other_type)) {
5580 if(!pointers_compatible(true_type, false_type)) {
5581 warningf(expression->base.source_position,
5582 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5584 result_type = true_type;
5585 } else if(is_null_pointer_constant(other_expression)) {
5586 result_type = pointer_type;
5587 } else if(is_type_integer(other_type)) {
5588 warningf(expression->base.source_position,
5589 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5590 result_type = pointer_type;
5592 type_error_incompatible("while parsing conditional",
5593 expression->base.source_position, true_type, false_type);
5594 result_type = type_error_type;
5597 /* TODO: one pointer to void*, other some pointer */
5599 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5600 type_error_incompatible("while parsing conditional",
5601 expression->base.source_position, true_type,
5604 result_type = type_error_type;
5607 conditional->true_expression
5608 = create_implicit_cast(true_expression, result_type);
5609 conditional->false_expression
5610 = create_implicit_cast(false_expression, result_type);
5611 conditional->base.type = result_type;
5614 return create_invalid_expression();
5618 * Parse an extension expression.
5620 static expression_t *parse_extension(unsigned precedence)
5622 eat(T___extension__);
5624 /* TODO enable extensions */
5625 expression_t *expression = parse_sub_expression(precedence);
5626 /* TODO disable extensions */
5631 * Parse a __builtin_classify_type() expression.
5633 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5635 eat(T___builtin_classify_type);
5637 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5638 result->base.type = type_int;
5641 add_anchor_token(')');
5642 expression_t *expression = parse_sub_expression(precedence);
5643 rem_anchor_token(')');
5645 result->classify_type.type_expression = expression;
5649 return create_invalid_expression();
5652 static void semantic_incdec(unary_expression_t *expression)
5654 type_t *const orig_type = expression->value->base.type;
5655 type_t *const type = skip_typeref(orig_type);
5656 /* TODO !is_type_real && !is_type_pointer */
5657 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5658 if (is_type_valid(type)) {
5659 /* TODO: improve error message */
5660 errorf(HERE, "operation needs an arithmetic or pointer type");
5665 expression->base.type = orig_type;
5668 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5670 type_t *const orig_type = expression->value->base.type;
5671 type_t *const type = skip_typeref(orig_type);
5672 if(!is_type_arithmetic(type)) {
5673 if (is_type_valid(type)) {
5674 /* TODO: improve error message */
5675 errorf(HERE, "operation needs an arithmetic type");
5680 expression->base.type = orig_type;
5683 static void semantic_unexpr_scalar(unary_expression_t *expression)
5685 type_t *const orig_type = expression->value->base.type;
5686 type_t *const type = skip_typeref(orig_type);
5687 if (!is_type_scalar(type)) {
5688 if (is_type_valid(type)) {
5689 errorf(HERE, "operand of ! must be of scalar type");
5694 expression->base.type = orig_type;
5697 static void semantic_unexpr_integer(unary_expression_t *expression)
5699 type_t *const orig_type = expression->value->base.type;
5700 type_t *const type = skip_typeref(orig_type);
5701 if (!is_type_integer(type)) {
5702 if (is_type_valid(type)) {
5703 errorf(HERE, "operand of ~ must be of integer type");
5708 expression->base.type = orig_type;
5711 static void semantic_dereference(unary_expression_t *expression)
5713 type_t *const orig_type = expression->value->base.type;
5714 type_t *const type = skip_typeref(orig_type);
5715 if(!is_type_pointer(type)) {
5716 if (is_type_valid(type)) {
5717 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5722 type_t *result_type = type->pointer.points_to;
5723 result_type = automatic_type_conversion(result_type);
5724 expression->base.type = result_type;
5728 * Check the semantic of the address taken expression.
5730 static void semantic_take_addr(unary_expression_t *expression)
5732 expression_t *value = expression->value;
5733 value->base.type = revert_automatic_type_conversion(value);
5735 type_t *orig_type = value->base.type;
5736 if(!is_type_valid(orig_type))
5739 if(value->kind == EXPR_REFERENCE) {
5740 declaration_t *const declaration = value->reference.declaration;
5741 if(declaration != NULL) {
5742 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5743 errorf(expression->base.source_position,
5744 "address of register variable '%Y' requested",
5745 declaration->symbol);
5747 declaration->address_taken = 1;
5751 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5754 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5755 static expression_t *parse_##unexpression_type(unsigned precedence) \
5759 expression_t *unary_expression \
5760 = allocate_expression_zero(unexpression_type); \
5761 unary_expression->base.source_position = HERE; \
5762 unary_expression->unary.value = parse_sub_expression(precedence); \
5764 sfunc(&unary_expression->unary); \
5766 return unary_expression; \
5769 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5770 semantic_unexpr_arithmetic)
5771 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5772 semantic_unexpr_arithmetic)
5773 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5774 semantic_unexpr_scalar)
5775 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5776 semantic_dereference)
5777 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5779 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5780 semantic_unexpr_integer)
5781 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5783 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5786 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5788 static expression_t *parse_##unexpression_type(unsigned precedence, \
5789 expression_t *left) \
5791 (void) precedence; \
5794 expression_t *unary_expression \
5795 = allocate_expression_zero(unexpression_type); \
5796 unary_expression->unary.value = left; \
5798 sfunc(&unary_expression->unary); \
5800 return unary_expression; \
5803 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5804 EXPR_UNARY_POSTFIX_INCREMENT,
5806 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5807 EXPR_UNARY_POSTFIX_DECREMENT,
5810 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5812 /* TODO: handle complex + imaginary types */
5814 /* § 6.3.1.8 Usual arithmetic conversions */
5815 if(type_left == type_long_double || type_right == type_long_double) {
5816 return type_long_double;
5817 } else if(type_left == type_double || type_right == type_double) {
5819 } else if(type_left == type_float || type_right == type_float) {
5823 type_right = promote_integer(type_right);
5824 type_left = promote_integer(type_left);
5826 if(type_left == type_right)
5829 bool signed_left = is_type_signed(type_left);
5830 bool signed_right = is_type_signed(type_right);
5831 int rank_left = get_rank(type_left);
5832 int rank_right = get_rank(type_right);
5833 if(rank_left < rank_right) {
5834 if(signed_left == signed_right || !signed_right) {
5840 if(signed_left == signed_right || !signed_left) {
5849 * Check the semantic restrictions for a binary expression.
5851 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5853 expression_t *const left = expression->left;
5854 expression_t *const right = expression->right;
5855 type_t *const orig_type_left = left->base.type;
5856 type_t *const orig_type_right = right->base.type;
5857 type_t *const type_left = skip_typeref(orig_type_left);
5858 type_t *const type_right = skip_typeref(orig_type_right);
5860 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5861 /* TODO: improve error message */
5862 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5863 errorf(HERE, "operation needs arithmetic types");
5868 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5869 expression->left = create_implicit_cast(left, arithmetic_type);
5870 expression->right = create_implicit_cast(right, arithmetic_type);
5871 expression->base.type = arithmetic_type;
5874 static void semantic_shift_op(binary_expression_t *expression)
5876 expression_t *const left = expression->left;
5877 expression_t *const right = expression->right;
5878 type_t *const orig_type_left = left->base.type;
5879 type_t *const orig_type_right = right->base.type;
5880 type_t * type_left = skip_typeref(orig_type_left);
5881 type_t * type_right = skip_typeref(orig_type_right);
5883 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5884 /* TODO: improve error message */
5885 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5886 errorf(HERE, "operation needs integer types");
5891 type_left = promote_integer(type_left);
5892 type_right = promote_integer(type_right);
5894 expression->left = create_implicit_cast(left, type_left);
5895 expression->right = create_implicit_cast(right, type_right);
5896 expression->base.type = type_left;
5899 static void semantic_add(binary_expression_t *expression)
5901 expression_t *const left = expression->left;
5902 expression_t *const right = expression->right;
5903 type_t *const orig_type_left = left->base.type;
5904 type_t *const orig_type_right = right->base.type;
5905 type_t *const type_left = skip_typeref(orig_type_left);
5906 type_t *const type_right = skip_typeref(orig_type_right);
5909 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5910 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5911 expression->left = create_implicit_cast(left, arithmetic_type);
5912 expression->right = create_implicit_cast(right, arithmetic_type);
5913 expression->base.type = arithmetic_type;
5915 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5916 expression->base.type = type_left;
5917 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5918 expression->base.type = type_right;
5919 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5920 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5924 static void semantic_sub(binary_expression_t *expression)
5926 expression_t *const left = expression->left;
5927 expression_t *const right = expression->right;
5928 type_t *const orig_type_left = left->base.type;
5929 type_t *const orig_type_right = right->base.type;
5930 type_t *const type_left = skip_typeref(orig_type_left);
5931 type_t *const type_right = skip_typeref(orig_type_right);
5934 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5935 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5936 expression->left = create_implicit_cast(left, arithmetic_type);
5937 expression->right = create_implicit_cast(right, arithmetic_type);
5938 expression->base.type = arithmetic_type;
5940 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5941 expression->base.type = type_left;
5942 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5943 if(!pointers_compatible(type_left, type_right)) {
5945 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5946 orig_type_left, orig_type_right);
5948 expression->base.type = type_ptrdiff_t;
5950 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5951 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5952 orig_type_left, orig_type_right);
5957 * Check the semantics of comparison expressions.
5959 * @param expression The expression to check.
5961 static void semantic_comparison(binary_expression_t *expression)
5963 expression_t *left = expression->left;
5964 expression_t *right = expression->right;
5965 type_t *orig_type_left = left->base.type;
5966 type_t *orig_type_right = right->base.type;
5968 type_t *type_left = skip_typeref(orig_type_left);
5969 type_t *type_right = skip_typeref(orig_type_right);
5971 /* TODO non-arithmetic types */
5972 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5973 if (warning.sign_compare &&
5974 (expression->base.kind != EXPR_BINARY_EQUAL &&
5975 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5976 (is_type_signed(type_left) != is_type_signed(type_right))) {
5977 warningf(expression->base.source_position,
5978 "comparison between signed and unsigned");
5980 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5981 expression->left = create_implicit_cast(left, arithmetic_type);
5982 expression->right = create_implicit_cast(right, arithmetic_type);
5983 expression->base.type = arithmetic_type;
5984 if (warning.float_equal &&
5985 (expression->base.kind == EXPR_BINARY_EQUAL ||
5986 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5987 is_type_float(arithmetic_type)) {
5988 warningf(expression->base.source_position,
5989 "comparing floating point with == or != is unsafe");
5991 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5992 /* TODO check compatibility */
5993 } else if (is_type_pointer(type_left)) {
5994 expression->right = create_implicit_cast(right, type_left);
5995 } else if (is_type_pointer(type_right)) {
5996 expression->left = create_implicit_cast(left, type_right);
5997 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5998 type_error_incompatible("invalid operands in comparison",
5999 expression->base.source_position,
6000 type_left, type_right);
6002 expression->base.type = type_int;
6005 static void semantic_arithmetic_assign(binary_expression_t *expression)
6007 expression_t *left = expression->left;
6008 expression_t *right = expression->right;
6009 type_t *orig_type_left = left->base.type;
6010 type_t *orig_type_right = right->base.type;
6012 type_t *type_left = skip_typeref(orig_type_left);
6013 type_t *type_right = skip_typeref(orig_type_right);
6015 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6016 /* TODO: improve error message */
6017 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6018 errorf(HERE, "operation needs arithmetic types");
6023 /* combined instructions are tricky. We can't create an implicit cast on
6024 * the left side, because we need the uncasted form for the store.
6025 * The ast2firm pass has to know that left_type must be right_type
6026 * for the arithmetic operation and create a cast by itself */
6027 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6028 expression->right = create_implicit_cast(right, arithmetic_type);
6029 expression->base.type = type_left;
6032 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6034 expression_t *const left = expression->left;
6035 expression_t *const right = expression->right;
6036 type_t *const orig_type_left = left->base.type;
6037 type_t *const orig_type_right = right->base.type;
6038 type_t *const type_left = skip_typeref(orig_type_left);
6039 type_t *const type_right = skip_typeref(orig_type_right);
6041 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6042 /* combined instructions are tricky. We can't create an implicit cast on
6043 * the left side, because we need the uncasted form for the store.
6044 * The ast2firm pass has to know that left_type must be right_type
6045 * for the arithmetic operation and create a cast by itself */
6046 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6047 expression->right = create_implicit_cast(right, arithmetic_type);
6048 expression->base.type = type_left;
6049 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6050 expression->base.type = type_left;
6051 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6052 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6057 * Check the semantic restrictions of a logical expression.
6059 static void semantic_logical_op(binary_expression_t *expression)
6061 expression_t *const left = expression->left;
6062 expression_t *const right = expression->right;
6063 type_t *const orig_type_left = left->base.type;
6064 type_t *const orig_type_right = right->base.type;
6065 type_t *const type_left = skip_typeref(orig_type_left);
6066 type_t *const type_right = skip_typeref(orig_type_right);
6068 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6069 /* TODO: improve error message */
6070 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6071 errorf(HERE, "operation needs scalar types");
6076 expression->base.type = type_int;
6080 * Checks if a compound type has constant fields.
6082 static bool has_const_fields(const compound_type_t *type)
6084 const scope_t *scope = &type->declaration->scope;
6085 const declaration_t *declaration = scope->declarations;
6087 for (; declaration != NULL; declaration = declaration->next) {
6088 if (declaration->namespc != NAMESPACE_NORMAL)
6091 const type_t *decl_type = skip_typeref(declaration->type);
6092 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6100 * Check the semantic restrictions of a binary assign expression.
6102 static void semantic_binexpr_assign(binary_expression_t *expression)
6104 expression_t *left = expression->left;
6105 type_t *orig_type_left = left->base.type;
6107 type_t *type_left = revert_automatic_type_conversion(left);
6108 type_left = skip_typeref(orig_type_left);
6110 /* must be a modifiable lvalue */
6111 if (is_type_array(type_left)) {
6112 errorf(HERE, "cannot assign to arrays ('%E')", left);
6115 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6116 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6120 if(is_type_incomplete(type_left)) {
6122 "left-hand side of assignment '%E' has incomplete type '%T'",
6123 left, orig_type_left);
6126 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6127 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6128 left, orig_type_left);
6132 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6133 "assignment", left->base.source_position);
6134 if (res_type == NULL) {
6135 errorf(expression->base.source_position,
6136 "cannot assign to '%T' from '%T'",
6137 orig_type_left, expression->right->base.type);
6139 expression->right = create_implicit_cast(expression->right, res_type);
6142 expression->base.type = orig_type_left;
6146 * Determine if the outermost operation (or parts thereof) of the given
6147 * expression has no effect in order to generate a warning about this fact.
6148 * Therefore in some cases this only examines some of the operands of the
6149 * expression (see comments in the function and examples below).
6151 * f() + 23; // warning, because + has no effect
6152 * x || f(); // no warning, because x controls execution of f()
6153 * x ? y : f(); // warning, because y has no effect
6154 * (void)x; // no warning to be able to suppress the warning
6155 * This function can NOT be used for an "expression has definitely no effect"-
6157 static bool expression_has_effect(const expression_t *const expr)
6159 switch (expr->kind) {
6160 case EXPR_UNKNOWN: break;
6161 case EXPR_INVALID: return true; /* do NOT warn */
6162 case EXPR_REFERENCE: return false;
6163 /* suppress the warning for microsoft __noop operations */
6164 case EXPR_CONST: return expr->conste.is_ms_noop;
6165 case EXPR_CHARACTER_CONSTANT: return false;
6166 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6167 case EXPR_STRING_LITERAL: return false;
6168 case EXPR_WIDE_STRING_LITERAL: return false;
6171 const call_expression_t *const call = &expr->call;
6172 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6175 switch (call->function->builtin_symbol.symbol->ID) {
6176 case T___builtin_va_end: return true;
6177 default: return false;
6181 /* Generate the warning if either the left or right hand side of a
6182 * conditional expression has no effect */
6183 case EXPR_CONDITIONAL: {
6184 const conditional_expression_t *const cond = &expr->conditional;
6186 expression_has_effect(cond->true_expression) &&
6187 expression_has_effect(cond->false_expression);
6190 case EXPR_SELECT: return false;
6191 case EXPR_ARRAY_ACCESS: return false;
6192 case EXPR_SIZEOF: return false;
6193 case EXPR_CLASSIFY_TYPE: return false;
6194 case EXPR_ALIGNOF: return false;
6196 case EXPR_FUNCNAME: return false;
6197 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6198 case EXPR_BUILTIN_CONSTANT_P: return false;
6199 case EXPR_BUILTIN_PREFETCH: return true;
6200 case EXPR_OFFSETOF: return false;
6201 case EXPR_VA_START: return true;
6202 case EXPR_VA_ARG: return true;
6203 case EXPR_STATEMENT: return true; // TODO
6204 case EXPR_COMPOUND_LITERAL: return false;
6206 case EXPR_UNARY_NEGATE: return false;
6207 case EXPR_UNARY_PLUS: return false;
6208 case EXPR_UNARY_BITWISE_NEGATE: return false;
6209 case EXPR_UNARY_NOT: return false;
6210 case EXPR_UNARY_DEREFERENCE: return false;
6211 case EXPR_UNARY_TAKE_ADDRESS: return false;
6212 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6213 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6214 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6215 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6217 /* Treat void casts as if they have an effect in order to being able to
6218 * suppress the warning */
6219 case EXPR_UNARY_CAST: {
6220 type_t *const type = skip_typeref(expr->base.type);
6221 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6224 case EXPR_UNARY_CAST_IMPLICIT: return true;
6225 case EXPR_UNARY_ASSUME: return true;
6226 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6228 case EXPR_BINARY_ADD: return false;
6229 case EXPR_BINARY_SUB: return false;
6230 case EXPR_BINARY_MUL: return false;
6231 case EXPR_BINARY_DIV: return false;
6232 case EXPR_BINARY_MOD: return false;
6233 case EXPR_BINARY_EQUAL: return false;
6234 case EXPR_BINARY_NOTEQUAL: return false;
6235 case EXPR_BINARY_LESS: return false;
6236 case EXPR_BINARY_LESSEQUAL: return false;
6237 case EXPR_BINARY_GREATER: return false;
6238 case EXPR_BINARY_GREATEREQUAL: return false;
6239 case EXPR_BINARY_BITWISE_AND: return false;
6240 case EXPR_BINARY_BITWISE_OR: return false;
6241 case EXPR_BINARY_BITWISE_XOR: return false;
6242 case EXPR_BINARY_SHIFTLEFT: return false;
6243 case EXPR_BINARY_SHIFTRIGHT: return false;
6244 case EXPR_BINARY_ASSIGN: return true;
6245 case EXPR_BINARY_MUL_ASSIGN: return true;
6246 case EXPR_BINARY_DIV_ASSIGN: return true;
6247 case EXPR_BINARY_MOD_ASSIGN: return true;
6248 case EXPR_BINARY_ADD_ASSIGN: return true;
6249 case EXPR_BINARY_SUB_ASSIGN: return true;
6250 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6251 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6252 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6253 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6254 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6256 /* Only examine the right hand side of && and ||, because the left hand
6257 * side already has the effect of controlling the execution of the right
6259 case EXPR_BINARY_LOGICAL_AND:
6260 case EXPR_BINARY_LOGICAL_OR:
6261 /* Only examine the right hand side of a comma expression, because the left
6262 * hand side has a separate warning */
6263 case EXPR_BINARY_COMMA:
6264 return expression_has_effect(expr->binary.right);
6266 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6267 case EXPR_BINARY_ISGREATER: return false;
6268 case EXPR_BINARY_ISGREATEREQUAL: return false;
6269 case EXPR_BINARY_ISLESS: return false;
6270 case EXPR_BINARY_ISLESSEQUAL: return false;
6271 case EXPR_BINARY_ISLESSGREATER: return false;
6272 case EXPR_BINARY_ISUNORDERED: return false;
6275 internal_errorf(HERE, "unexpected expression");
6278 static void semantic_comma(binary_expression_t *expression)
6280 if (warning.unused_value) {
6281 const expression_t *const left = expression->left;
6282 if (!expression_has_effect(left)) {
6283 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6286 expression->base.type = expression->right->base.type;
6289 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6290 static expression_t *parse_##binexpression_type(unsigned precedence, \
6291 expression_t *left) \
6294 source_position_t pos = HERE; \
6296 expression_t *right = parse_sub_expression(precedence + lr); \
6298 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6299 binexpr->base.source_position = pos; \
6300 binexpr->binary.left = left; \
6301 binexpr->binary.right = right; \
6302 sfunc(&binexpr->binary); \
6307 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6308 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6309 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6310 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6311 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6312 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6313 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6314 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6315 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6317 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6318 semantic_comparison, 1)
6319 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6320 semantic_comparison, 1)
6321 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6322 semantic_comparison, 1)
6323 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6324 semantic_comparison, 1)
6326 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6327 semantic_binexpr_arithmetic, 1)
6328 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6329 semantic_binexpr_arithmetic, 1)
6330 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6331 semantic_binexpr_arithmetic, 1)
6332 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6333 semantic_logical_op, 1)
6334 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6335 semantic_logical_op, 1)
6336 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6337 semantic_shift_op, 1)
6338 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6339 semantic_shift_op, 1)
6340 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6341 semantic_arithmetic_addsubb_assign, 0)
6342 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6343 semantic_arithmetic_addsubb_assign, 0)
6344 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6345 semantic_arithmetic_assign, 0)
6346 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6347 semantic_arithmetic_assign, 0)
6348 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6349 semantic_arithmetic_assign, 0)
6350 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6351 semantic_arithmetic_assign, 0)
6352 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6353 semantic_arithmetic_assign, 0)
6354 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6355 semantic_arithmetic_assign, 0)
6356 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6357 semantic_arithmetic_assign, 0)
6358 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6359 semantic_arithmetic_assign, 0)
6361 static expression_t *parse_sub_expression(unsigned precedence)
6363 if(token.type < 0) {
6364 return expected_expression_error();
6367 expression_parser_function_t *parser
6368 = &expression_parsers[token.type];
6369 source_position_t source_position = token.source_position;
6372 if(parser->parser != NULL) {
6373 left = parser->parser(parser->precedence);
6375 left = parse_primary_expression();
6377 assert(left != NULL);
6378 left->base.source_position = source_position;
6381 if(token.type < 0) {
6382 return expected_expression_error();
6385 parser = &expression_parsers[token.type];
6386 if(parser->infix_parser == NULL)
6388 if(parser->infix_precedence < precedence)
6391 left = parser->infix_parser(parser->infix_precedence, left);
6393 assert(left != NULL);
6394 assert(left->kind != EXPR_UNKNOWN);
6395 left->base.source_position = source_position;
6402 * Parse an expression.
6404 static expression_t *parse_expression(void)
6406 return parse_sub_expression(1);
6410 * Register a parser for a prefix-like operator with given precedence.
6412 * @param parser the parser function
6413 * @param token_type the token type of the prefix token
6414 * @param precedence the precedence of the operator
6416 static void register_expression_parser(parse_expression_function parser,
6417 int token_type, unsigned precedence)
6419 expression_parser_function_t *entry = &expression_parsers[token_type];
6421 if(entry->parser != NULL) {
6422 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6423 panic("trying to register multiple expression parsers for a token");
6425 entry->parser = parser;
6426 entry->precedence = precedence;
6430 * Register a parser for an infix operator with given precedence.
6432 * @param parser the parser function
6433 * @param token_type the token type of the infix operator
6434 * @param precedence the precedence of the operator
6436 static void register_infix_parser(parse_expression_infix_function parser,
6437 int token_type, unsigned precedence)
6439 expression_parser_function_t *entry = &expression_parsers[token_type];
6441 if(entry->infix_parser != NULL) {
6442 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6443 panic("trying to register multiple infix expression parsers for a "
6446 entry->infix_parser = parser;
6447 entry->infix_precedence = precedence;
6451 * Initialize the expression parsers.
6453 static void init_expression_parsers(void)
6455 memset(&expression_parsers, 0, sizeof(expression_parsers));
6457 register_infix_parser(parse_array_expression, '[', 30);
6458 register_infix_parser(parse_call_expression, '(', 30);
6459 register_infix_parser(parse_select_expression, '.', 30);
6460 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6461 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6463 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6466 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6467 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6468 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6469 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6470 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6471 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6472 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6473 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6474 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6475 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6476 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6477 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6478 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6479 T_EXCLAMATIONMARKEQUAL, 13);
6480 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6481 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6482 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6483 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6484 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6485 register_infix_parser(parse_conditional_expression, '?', 7);
6486 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6487 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6488 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6489 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6490 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6491 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6492 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6493 T_LESSLESSEQUAL, 2);
6494 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6495 T_GREATERGREATEREQUAL, 2);
6496 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6498 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6500 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6503 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6505 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6506 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6507 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6508 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6509 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6510 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6511 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6513 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6515 register_expression_parser(parse_sizeof, T_sizeof, 25);
6516 register_expression_parser(parse_alignof, T___alignof__, 25);
6517 register_expression_parser(parse_extension, T___extension__, 25);
6518 register_expression_parser(parse_builtin_classify_type,
6519 T___builtin_classify_type, 25);
6523 * Parse a asm statement constraints specification.
6525 static asm_constraint_t *parse_asm_constraints(void)
6527 asm_constraint_t *result = NULL;
6528 asm_constraint_t *last = NULL;
6530 while(token.type == T_STRING_LITERAL || token.type == '[') {
6531 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6532 memset(constraint, 0, sizeof(constraint[0]));
6534 if(token.type == '[') {
6536 if(token.type != T_IDENTIFIER) {
6537 parse_error_expected("while parsing asm constraint",
6541 constraint->symbol = token.v.symbol;
6546 constraint->constraints = parse_string_literals();
6548 constraint->expression = parse_expression();
6552 last->next = constraint;
6554 result = constraint;
6558 if(token.type != ',')
6569 * Parse a asm statement clobber specification.
6571 static asm_clobber_t *parse_asm_clobbers(void)
6573 asm_clobber_t *result = NULL;
6574 asm_clobber_t *last = NULL;
6576 while(token.type == T_STRING_LITERAL) {
6577 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6578 clobber->clobber = parse_string_literals();
6581 last->next = clobber;
6587 if(token.type != ',')
6596 * Parse an asm statement.
6598 static statement_t *parse_asm_statement(void)
6602 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6603 statement->base.source_position = token.source_position;
6605 asm_statement_t *asm_statement = &statement->asms;
6607 if(token.type == T_volatile) {
6609 asm_statement->is_volatile = true;
6613 add_anchor_token(')');
6614 add_anchor_token(':');
6615 asm_statement->asm_text = parse_string_literals();
6617 if(token.type != ':') {
6618 rem_anchor_token(':');
6623 asm_statement->inputs = parse_asm_constraints();
6624 if(token.type != ':') {
6625 rem_anchor_token(':');
6630 asm_statement->outputs = parse_asm_constraints();
6631 if(token.type != ':') {
6632 rem_anchor_token(':');
6635 rem_anchor_token(':');
6638 asm_statement->clobbers = parse_asm_clobbers();
6641 rem_anchor_token(')');
6646 return create_invalid_statement();
6650 * Parse a case statement.
6652 static statement_t *parse_case_statement(void)
6656 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6658 statement->base.source_position = token.source_position;
6659 statement->case_label.expression = parse_expression();
6661 if (c_mode & _GNUC) {
6662 if (token.type == T_DOTDOTDOT) {
6664 statement->case_label.end_range = parse_expression();
6670 if (! is_constant_expression(statement->case_label.expression)) {
6671 errorf(statement->base.source_position,
6672 "case label does not reduce to an integer constant");
6674 /* TODO: check if the case label is already known */
6675 if (current_switch != NULL) {
6676 /* link all cases into the switch statement */
6677 if (current_switch->last_case == NULL) {
6678 current_switch->first_case =
6679 current_switch->last_case = &statement->case_label;
6681 current_switch->last_case->next = &statement->case_label;
6684 errorf(statement->base.source_position,
6685 "case label not within a switch statement");
6688 statement->case_label.statement = parse_statement();
6692 return create_invalid_statement();
6696 * Finds an existing default label of a switch statement.
6698 static case_label_statement_t *
6699 find_default_label(const switch_statement_t *statement)
6701 case_label_statement_t *label = statement->first_case;
6702 for ( ; label != NULL; label = label->next) {
6703 if (label->expression == NULL)
6710 * Parse a default statement.
6712 static statement_t *parse_default_statement(void)
6716 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6718 statement->base.source_position = token.source_position;
6721 if (current_switch != NULL) {
6722 const case_label_statement_t *def_label = find_default_label(current_switch);
6723 if (def_label != NULL) {
6724 errorf(HERE, "multiple default labels in one switch");
6725 errorf(def_label->base.source_position,
6726 "this is the first default label");
6728 /* link all cases into the switch statement */
6729 if (current_switch->last_case == NULL) {
6730 current_switch->first_case =
6731 current_switch->last_case = &statement->case_label;
6733 current_switch->last_case->next = &statement->case_label;
6737 errorf(statement->base.source_position,
6738 "'default' label not within a switch statement");
6740 statement->case_label.statement = parse_statement();
6744 return create_invalid_statement();
6748 * Return the declaration for a given label symbol or create a new one.
6750 static declaration_t *get_label(symbol_t *symbol)
6752 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6753 assert(current_function != NULL);
6754 /* if we found a label in the same function, then we already created the
6756 if(candidate != NULL
6757 && candidate->parent_scope == ¤t_function->scope) {
6761 /* otherwise we need to create a new one */
6762 declaration_t *const declaration = allocate_declaration_zero();
6763 declaration->namespc = NAMESPACE_LABEL;
6764 declaration->symbol = symbol;
6766 label_push(declaration);
6772 * Parse a label statement.
6774 static statement_t *parse_label_statement(void)
6776 assert(token.type == T_IDENTIFIER);
6777 symbol_t *symbol = token.v.symbol;
6780 declaration_t *label = get_label(symbol);
6782 /* if source position is already set then the label is defined twice,
6783 * otherwise it was just mentioned in a goto so far */
6784 if(label->source_position.input_name != NULL) {
6785 errorf(HERE, "duplicate label '%Y' (declared %P)",
6786 symbol, label->source_position);
6788 label->source_position = token.source_position;
6791 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6793 statement->base.source_position = token.source_position;
6794 statement->label.label = label;
6798 if(token.type == '}') {
6799 /* TODO only warn? */
6801 warningf(HERE, "label at end of compound statement");
6802 statement->label.statement = create_empty_statement();
6804 errorf(HERE, "label at end of compound statement");
6805 statement->label.statement = create_invalid_statement();
6809 if (token.type == ';') {
6810 /* eat an empty statement here, to avoid the warning about an empty
6811 * after a label. label:; is commonly used to have a label before
6813 statement->label.statement = create_empty_statement();
6816 statement->label.statement = parse_statement();
6820 /* remember the labels's in a list for later checking */
6821 if (label_last == NULL) {
6822 label_first = &statement->label;
6824 label_last->next = &statement->label;
6826 label_last = &statement->label;
6832 * Parse an if statement.
6834 static statement_t *parse_if(void)
6838 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6839 statement->base.source_position = token.source_position;
6842 add_anchor_token(')');
6843 statement->ifs.condition = parse_expression();
6844 rem_anchor_token(')');
6847 add_anchor_token(T_else);
6848 statement->ifs.true_statement = parse_statement();
6849 rem_anchor_token(T_else);
6851 if(token.type == T_else) {
6853 statement->ifs.false_statement = parse_statement();
6858 return create_invalid_statement();
6862 * Parse a switch statement.
6864 static statement_t *parse_switch(void)
6868 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6869 statement->base.source_position = token.source_position;
6872 expression_t *const expr = parse_expression();
6873 type_t * type = skip_typeref(expr->base.type);
6874 if (is_type_integer(type)) {
6875 type = promote_integer(type);
6876 } else if (is_type_valid(type)) {
6877 errorf(expr->base.source_position,
6878 "switch quantity is not an integer, but '%T'", type);
6879 type = type_error_type;
6881 statement->switchs.expression = create_implicit_cast(expr, type);
6884 switch_statement_t *rem = current_switch;
6885 current_switch = &statement->switchs;
6886 statement->switchs.body = parse_statement();
6887 current_switch = rem;
6889 if (warning.switch_default
6890 && find_default_label(&statement->switchs) == NULL) {
6891 warningf(statement->base.source_position, "switch has no default case");
6896 return create_invalid_statement();
6899 static statement_t *parse_loop_body(statement_t *const loop)
6901 statement_t *const rem = current_loop;
6902 current_loop = loop;
6904 statement_t *const body = parse_statement();
6911 * Parse a while statement.
6913 static statement_t *parse_while(void)
6917 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6918 statement->base.source_position = token.source_position;
6921 add_anchor_token(')');
6922 statement->whiles.condition = parse_expression();
6923 rem_anchor_token(')');
6926 statement->whiles.body = parse_loop_body(statement);
6930 return create_invalid_statement();
6934 * Parse a do statement.
6936 static statement_t *parse_do(void)
6940 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6942 statement->base.source_position = token.source_position;
6944 add_anchor_token(T_while);
6945 statement->do_while.body = parse_loop_body(statement);
6946 rem_anchor_token(T_while);
6950 add_anchor_token(')');
6951 statement->do_while.condition = parse_expression();
6952 rem_anchor_token(')');
6958 return create_invalid_statement();
6962 * Parse a for statement.
6964 static statement_t *parse_for(void)
6968 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6969 statement->base.source_position = token.source_position;
6971 int top = environment_top();
6972 scope_t *last_scope = scope;
6973 set_scope(&statement->fors.scope);
6976 add_anchor_token(')');
6978 if(token.type != ';') {
6979 if(is_declaration_specifier(&token, false)) {
6980 parse_declaration(record_declaration);
6982 expression_t *const init = parse_expression();
6983 statement->fors.initialisation = init;
6984 if (warning.unused_value && !expression_has_effect(init)) {
6985 warningf(init->base.source_position,
6986 "initialisation of 'for'-statement has no effect");
6994 if(token.type != ';') {
6995 statement->fors.condition = parse_expression();
6998 if(token.type != ')') {
6999 expression_t *const step = parse_expression();
7000 statement->fors.step = step;
7001 if (warning.unused_value && !expression_has_effect(step)) {
7002 warningf(step->base.source_position,
7003 "step of 'for'-statement has no effect");
7006 rem_anchor_token(')');
7008 statement->fors.body = parse_loop_body(statement);
7010 assert(scope == &statement->fors.scope);
7011 set_scope(last_scope);
7012 environment_pop_to(top);
7017 rem_anchor_token(')');
7018 assert(scope == &statement->fors.scope);
7019 set_scope(last_scope);
7020 environment_pop_to(top);
7022 return create_invalid_statement();
7026 * Parse a goto statement.
7028 static statement_t *parse_goto(void)
7032 if(token.type != T_IDENTIFIER) {
7033 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
7037 symbol_t *symbol = token.v.symbol;
7040 declaration_t *label = get_label(symbol);
7042 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7043 statement->base.source_position = token.source_position;
7045 statement->gotos.label = label;
7047 /* remember the goto's in a list for later checking */
7048 if (goto_last == NULL) {
7049 goto_first = &statement->gotos;
7051 goto_last->next = &statement->gotos;
7053 goto_last = &statement->gotos;
7059 return create_invalid_statement();
7063 * Parse a continue statement.
7065 static statement_t *parse_continue(void)
7067 statement_t *statement;
7068 if (current_loop == NULL) {
7069 errorf(HERE, "continue statement not within loop");
7072 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7074 statement->base.source_position = token.source_position;
7082 return create_invalid_statement();
7086 * Parse a break statement.
7088 static statement_t *parse_break(void)
7090 statement_t *statement;
7091 if (current_switch == NULL && current_loop == NULL) {
7092 errorf(HERE, "break statement not within loop or switch");
7095 statement = allocate_statement_zero(STATEMENT_BREAK);
7097 statement->base.source_position = token.source_position;
7105 return create_invalid_statement();
7109 * Check if a given declaration represents a local variable.
7111 static bool is_local_var_declaration(const declaration_t *declaration) {
7112 switch ((storage_class_tag_t) declaration->storage_class) {
7113 case STORAGE_CLASS_AUTO:
7114 case STORAGE_CLASS_REGISTER: {
7115 const type_t *type = skip_typeref(declaration->type);
7116 if(is_type_function(type)) {
7128 * Check if a given declaration represents a variable.
7130 static bool is_var_declaration(const declaration_t *declaration) {
7131 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7134 const type_t *type = skip_typeref(declaration->type);
7135 return !is_type_function(type);
7139 * Check if a given expression represents a local variable.
7141 static bool is_local_variable(const expression_t *expression)
7143 if (expression->base.kind != EXPR_REFERENCE) {
7146 const declaration_t *declaration = expression->reference.declaration;
7147 return is_local_var_declaration(declaration);
7151 * Check if a given expression represents a local variable and
7152 * return its declaration then, else return NULL.
7154 declaration_t *expr_is_variable(const expression_t *expression)
7156 if (expression->base.kind != EXPR_REFERENCE) {
7159 declaration_t *declaration = expression->reference.declaration;
7160 if (is_var_declaration(declaration))
7166 * Parse a return statement.
7168 static statement_t *parse_return(void)
7170 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7171 statement->base.source_position = token.source_position;
7175 expression_t *return_value = NULL;
7176 if(token.type != ';') {
7177 return_value = parse_expression();
7181 const type_t *const func_type = current_function->type;
7182 assert(is_type_function(func_type));
7183 type_t *const return_type = skip_typeref(func_type->function.return_type);
7185 if(return_value != NULL) {
7186 type_t *return_value_type = skip_typeref(return_value->base.type);
7188 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7189 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7190 warningf(statement->base.source_position,
7191 "'return' with a value, in function returning void");
7192 return_value = NULL;
7194 type_t *const res_type = semantic_assign(return_type,
7195 return_value, "'return'", statement->base.source_position);
7196 if (res_type == NULL) {
7197 errorf(statement->base.source_position,
7198 "cannot return something of type '%T' in function returning '%T'",
7199 return_value->base.type, return_type);
7201 return_value = create_implicit_cast(return_value, res_type);
7204 /* check for returning address of a local var */
7205 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7206 const expression_t *expression = return_value->unary.value;
7207 if (is_local_variable(expression)) {
7208 warningf(statement->base.source_position,
7209 "function returns address of local variable");
7213 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7214 warningf(statement->base.source_position,
7215 "'return' without value, in function returning non-void");
7218 statement->returns.value = return_value;
7222 return create_invalid_statement();
7226 * Parse a declaration statement.
7228 static statement_t *parse_declaration_statement(void)
7230 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7232 statement->base.source_position = token.source_position;
7234 declaration_t *before = last_declaration;
7235 parse_declaration(record_declaration);
7237 if(before == NULL) {
7238 statement->declaration.declarations_begin = scope->declarations;
7240 statement->declaration.declarations_begin = before->next;
7242 statement->declaration.declarations_end = last_declaration;
7248 * Parse an expression statement, ie. expr ';'.
7250 static statement_t *parse_expression_statement(void)
7252 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7254 statement->base.source_position = token.source_position;
7255 expression_t *const expr = parse_expression();
7256 statement->expression.expression = expr;
7258 if (warning.unused_value && !expression_has_effect(expr)) {
7259 warningf(expr->base.source_position, "statement has no effect");
7266 return create_invalid_statement();
7270 * Parse a statement.
7272 static statement_t *parse_statement(void)
7274 statement_t *statement = NULL;
7276 /* declaration or statement */
7277 add_anchor_token(';');
7278 switch(token.type) {
7280 statement = parse_asm_statement();
7284 statement = parse_case_statement();
7288 statement = parse_default_statement();
7292 statement = parse_compound_statement();
7296 statement = parse_if();
7300 statement = parse_switch();
7304 statement = parse_while();
7308 statement = parse_do();
7312 statement = parse_for();
7316 statement = parse_goto();
7320 statement = parse_continue();
7324 statement = parse_break();
7328 statement = parse_return();
7332 if(warning.empty_statement) {
7333 warningf(HERE, "statement is empty");
7335 statement = create_empty_statement();
7340 if(look_ahead(1)->type == ':') {
7341 statement = parse_label_statement();
7345 if(is_typedef_symbol(token.v.symbol)) {
7346 statement = parse_declaration_statement();
7350 statement = parse_expression_statement();
7353 case T___extension__:
7354 /* this can be a prefix to a declaration or an expression statement */
7355 /* we simply eat it now and parse the rest with tail recursion */
7358 } while(token.type == T___extension__);
7359 statement = parse_statement();
7363 statement = parse_declaration_statement();
7367 statement = parse_expression_statement();
7370 rem_anchor_token(';');
7372 assert(statement != NULL
7373 && statement->base.source_position.input_name != NULL);
7379 * Parse a compound statement.
7381 static statement_t *parse_compound_statement(void)
7383 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7385 statement->base.source_position = token.source_position;
7388 add_anchor_token('}');
7390 int top = environment_top();
7391 scope_t *last_scope = scope;
7392 set_scope(&statement->compound.scope);
7394 statement_t *last_statement = NULL;
7396 while(token.type != '}' && token.type != T_EOF) {
7397 statement_t *sub_statement = parse_statement();
7398 if(is_invalid_statement(sub_statement)) {
7399 /* an error occurred. if we are at an anchor, return */
7405 if(last_statement != NULL) {
7406 last_statement->base.next = sub_statement;
7408 statement->compound.statements = sub_statement;
7411 while(sub_statement->base.next != NULL)
7412 sub_statement = sub_statement->base.next;
7414 last_statement = sub_statement;
7417 if(token.type == '}') {
7420 errorf(statement->base.source_position,
7421 "end of file while looking for closing '}'");
7425 rem_anchor_token('}');
7426 assert(scope == &statement->compound.scope);
7427 set_scope(last_scope);
7428 environment_pop_to(top);
7434 * Initialize builtin types.
7436 static void initialize_builtin_types(void)
7438 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7439 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7440 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7441 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7442 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7443 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7444 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7445 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7447 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7448 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7449 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7450 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7454 * Check for unused global static functions and variables
7456 static void check_unused_globals(void)
7458 if (!warning.unused_function && !warning.unused_variable)
7461 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7462 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7465 type_t *const type = decl->type;
7467 if (is_type_function(skip_typeref(type))) {
7468 if (!warning.unused_function || decl->is_inline)
7471 s = (decl->init.statement != NULL ? "defined" : "declared");
7473 if (!warning.unused_variable)
7479 warningf(decl->source_position, "'%#T' %s but not used",
7480 type, decl->symbol, s);
7485 * Parse a translation unit.
7487 static translation_unit_t *parse_translation_unit(void)
7489 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7491 assert(global_scope == NULL);
7492 global_scope = &unit->scope;
7494 assert(scope == NULL);
7495 set_scope(&unit->scope);
7497 initialize_builtin_types();
7499 while(token.type != T_EOF) {
7500 if (token.type == ';') {
7501 /* TODO error in strict mode */
7502 warningf(HERE, "stray ';' outside of function");
7505 parse_external_declaration();
7509 assert(scope == &unit->scope);
7511 last_declaration = NULL;
7513 assert(global_scope == &unit->scope);
7514 check_unused_globals();
7515 global_scope = NULL;
7523 * @return the translation unit or NULL if errors occurred.
7525 translation_unit_t *parse(void)
7527 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7528 label_stack = NEW_ARR_F(stack_entry_t, 0);
7529 diagnostic_count = 0;
7533 type_set_output(stderr);
7534 ast_set_output(stderr);
7536 lookahead_bufpos = 0;
7537 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7540 translation_unit_t *unit = parse_translation_unit();
7542 DEL_ARR_F(environment_stack);
7543 DEL_ARR_F(label_stack);
7549 * Initialize the parser.
7551 void init_parser(void)
7554 /* add predefined symbols for extended-decl-modifier */
7555 sym_align = symbol_table_insert("align");
7556 sym_allocate = symbol_table_insert("allocate");
7557 sym_dllimport = symbol_table_insert("dllimport");
7558 sym_dllexport = symbol_table_insert("dllexport");
7559 sym_naked = symbol_table_insert("naked");
7560 sym_noinline = symbol_table_insert("noinline");
7561 sym_noreturn = symbol_table_insert("noreturn");
7562 sym_nothrow = symbol_table_insert("nothrow");
7563 sym_novtable = symbol_table_insert("novtable");
7564 sym_property = symbol_table_insert("property");
7565 sym_get = symbol_table_insert("get");
7566 sym_put = symbol_table_insert("put");
7567 sym_selectany = symbol_table_insert("selectany");
7568 sym_thread = symbol_table_insert("thread");
7569 sym_uuid = symbol_table_insert("uuid");
7570 sym_deprecated = symbol_table_insert("deprecated");
7571 sym_restrict = symbol_table_insert("restrict");
7572 sym_noalias = symbol_table_insert("noalias");
7574 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7576 init_expression_parsers();
7577 obstack_init(&temp_obst);
7579 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7580 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7584 * Terminate the parser.
7586 void exit_parser(void)
7588 obstack_free(&temp_obst, NULL);