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,
985 } gnu_attribute_kind_t;
987 static const char *gnu_attribute_names[GNU_AK_LAST] = {
988 [GNU_AK_CONST] = "const",
989 [GNU_AK_VOLATILE] = "volatile",
990 [GNU_AK_CDECL] = "cdecl",
991 [GNU_AK_STDCALL] = "stdcall",
992 [GNU_AK_FASTCALL] = "fastcall",
993 [GNU_AK_DEPRECATED] = "deprecated",
994 [GNU_AK_NOINLINE] = "noinline",
995 [GNU_AK_NORETURN] = "noreturn",
996 [GNU_AK_NAKED] = "naked",
997 [GNU_AK_PURE] = "pure",
998 [GNU_AK_ALWAYS_INLINE] = "always_inline",
999 [GNU_AK_MALLOC] = "malloc",
1000 [GNU_AK_WEAK] = "weak",
1001 [GNU_AK_ALIGNED] = "aligned",
1002 [GNU_AK_ALIAS] = "alias",
1003 [GNU_AK_SECTION] = "section",
1004 [GNU_AK_FORMAT] = "format",
1005 [GNU_AK_FORMAT_ARG] = "format_arg"
1009 * compare two string, ignoring double underscores on the second.
1011 static int strcmp_underscore(const char *s1, const char *s2) {
1012 if(s2[0] == '_' && s2[1] == '_') {
1014 size_t l1 = strlen(s1);
1015 if(l1 + 2 != strlen(s2)) {
1019 return strncmp(s1, s2, l1);
1021 return strcmp(s1, s2);
1024 static expression_t *parse_gnu_attribute_const_arg(void) {
1025 expression_t *expression;
1027 add_anchor_token('(');
1028 expression = parse_constant_expression();
1029 rem_anchor_token('(');
1033 return create_invalid_expression();
1036 static string_t parse_gnu_attribute_string_arg(void) {
1037 string_t string = { NULL, 0 };
1039 add_anchor_token('(');
1040 if(token.type != T_STRING_LITERAL) {
1041 parse_error_expected("while parsing attribute directive", T_STRING_LITERAL);
1044 string = parse_string_literals();
1045 rem_anchor_token('(');
1051 static const char *format_names[] = {
1059 * parse ( identifier, const expression, const expression )
1061 static void parse_gnu_attribute_format_args(void) {
1064 if(token.type != T_IDENTIFIER) {
1065 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER);
1068 const char *name = token.v.symbol->string;
1069 for(i = 0; i < 4; ++i) {
1070 if(strcmp_underscore(format_names[i], name) == 0)
1074 if(warning.attribute)
1075 warningf(HERE, "'%s' is an unrecognized format function type", name);
1080 add_anchor_token(')');
1081 add_anchor_token(',');
1082 parse_constant_expression();
1083 rem_anchor_token(',');
1084 rem_anchor_token('(');
1087 add_anchor_token(')');
1088 parse_constant_expression();
1089 rem_anchor_token('(');
1097 * Parse one GNU attribute.
1099 * Note that attribute names can be specified WITH or WITHOUT
1100 * double underscores, ie const or __const__.
1102 * The following attributes are parsed without arguments
1117 * The following attributes are parsed with arguments
1118 * aligned( const expression )
1119 * alias( string literal )
1120 * section( string literal )
1121 * format( identifier, const expression, const expression )
1122 * format_arg( const expression )
1124 static void parse_gnu_attribute(void)
1126 eat(T___attribute__);
1129 if(token.type != ')') {
1130 /* non-empty attribute list */
1133 if(token.type == T_const) {
1135 } else if(token.type == T_volatile) {
1137 } else if(token.type == T_cdecl) {
1138 /* __attribute__((cdecl)), WITH ms mode */
1140 } else if(token.type != T_IDENTIFIER) {
1141 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1144 const symbol_t *sym = token.v.symbol;
1148 gnu_attribute_kind_t kind;
1149 for(kind = 0; kind < GNU_AK_LAST; ++kind) {
1150 if(strcmp_underscore(gnu_attribute_names[kind], name) == 0)
1156 case GNU_AK_VOLATILE:
1160 case GNU_AK_STDCALL:
1162 case GNU_AK_FASTCALL:
1164 case GNU_AK_DEPRECATED:
1166 case GNU_AK_NOINLINE:
1168 case GNU_AK_NORETURN:
1174 case GNU_AK_ALWAYS_INLINE:
1180 case GNU_AK_ALIGNED:
1181 parse_gnu_attribute_const_arg();
1184 parse_gnu_attribute_string_arg();
1186 case GNU_AK_SECTION:
1187 parse_gnu_attribute_string_arg();
1190 parse_gnu_attribute_format_args();
1192 case GNU_AK_FORMAT_ARG:
1193 parse_gnu_attribute_const_arg();
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 if(token.type != ',')
1216 * Parse GNU attributes.
1218 static void parse_attributes(void)
1221 switch(token.type) {
1222 case T___attribute__: {
1223 parse_gnu_attribute();
1229 if(token.type != T_STRING_LITERAL) {
1230 parse_error_expected("while parsing assembler attribute",
1232 eat_until_matching_token('(');
1235 parse_string_literals();
1240 goto attributes_finished;
1245 attributes_finished:
1249 static designator_t *parse_designation(void)
1251 designator_t *result = NULL;
1252 designator_t *last = NULL;
1255 designator_t *designator;
1256 switch(token.type) {
1258 designator = allocate_ast_zero(sizeof(designator[0]));
1259 designator->source_position = token.source_position;
1261 add_anchor_token(']');
1262 designator->array_index = parse_constant_expression();
1263 rem_anchor_token(']');
1267 designator = allocate_ast_zero(sizeof(designator[0]));
1268 designator->source_position = token.source_position;
1270 if(token.type != T_IDENTIFIER) {
1271 parse_error_expected("while parsing designator",
1275 designator->symbol = token.v.symbol;
1283 assert(designator != NULL);
1285 last->next = designator;
1287 result = designator;
1295 static initializer_t *initializer_from_string(array_type_t *type,
1296 const string_t *const string)
1298 /* TODO: check len vs. size of array type */
1301 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1302 initializer->string.string = *string;
1307 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1308 wide_string_t *const string)
1310 /* TODO: check len vs. size of array type */
1313 initializer_t *const initializer =
1314 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1315 initializer->wide_string.string = *string;
1321 * Build an initializer from a given expression.
1323 static initializer_t *initializer_from_expression(type_t *orig_type,
1324 expression_t *expression)
1326 /* TODO check that expression is a constant expression */
1328 /* § 6.7.8.14/15 char array may be initialized by string literals */
1329 type_t *type = skip_typeref(orig_type);
1330 type_t *expr_type_orig = expression->base.type;
1331 type_t *expr_type = skip_typeref(expr_type_orig);
1332 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1333 array_type_t *const array_type = &type->array;
1334 type_t *const element_type = skip_typeref(array_type->element_type);
1336 if (element_type->kind == TYPE_ATOMIC) {
1337 atomic_type_kind_t akind = element_type->atomic.akind;
1338 switch (expression->kind) {
1339 case EXPR_STRING_LITERAL:
1340 if (akind == ATOMIC_TYPE_CHAR
1341 || akind == ATOMIC_TYPE_SCHAR
1342 || akind == ATOMIC_TYPE_UCHAR) {
1343 return initializer_from_string(array_type,
1344 &expression->string.value);
1347 case EXPR_WIDE_STRING_LITERAL: {
1348 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1349 if (get_unqualified_type(element_type) == bare_wchar_type) {
1350 return initializer_from_wide_string(array_type,
1351 &expression->wide_string.value);
1361 type_t *const res_type = semantic_assign(type, expression, "initializer",
1362 expression->base.source_position);
1363 if (res_type == NULL)
1366 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1367 result->value.value = create_implicit_cast(expression, res_type);
1373 * Checks if a given expression can be used as an constant initializer.
1375 static bool is_initializer_constant(const expression_t *expression)
1377 return is_constant_expression(expression)
1378 || is_address_constant(expression);
1382 * Parses an scalar initializer.
1384 * § 6.7.8.11; eat {} without warning
1386 static initializer_t *parse_scalar_initializer(type_t *type,
1387 bool must_be_constant)
1389 /* there might be extra {} hierarchies */
1391 while(token.type == '{') {
1394 warningf(HERE, "extra curly braces around scalar initializer");
1399 expression_t *expression = parse_assignment_expression();
1400 if(must_be_constant && !is_initializer_constant(expression)) {
1401 errorf(expression->base.source_position,
1402 "Initialisation expression '%E' is not constant\n",
1406 initializer_t *initializer = initializer_from_expression(type, expression);
1408 if(initializer == NULL) {
1409 errorf(expression->base.source_position,
1410 "expression '%E' (type '%T') doesn't match expected type '%T'",
1411 expression, expression->base.type, type);
1416 bool additional_warning_displayed = false;
1418 if(token.type == ',') {
1421 if(token.type != '}') {
1422 if(!additional_warning_displayed) {
1423 warningf(HERE, "additional elements in scalar initializer");
1424 additional_warning_displayed = true;
1435 * An entry in the type path.
1437 typedef struct type_path_entry_t type_path_entry_t;
1438 struct type_path_entry_t {
1439 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1441 size_t index; /**< For array types: the current index. */
1442 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1447 * A type path expression a position inside compound or array types.
1449 typedef struct type_path_t type_path_t;
1450 struct type_path_t {
1451 type_path_entry_t *path; /**< An flexible array containing the current path. */
1452 type_t *top_type; /**< type of the element the path points */
1453 size_t max_index; /**< largest index in outermost array */
1457 * Prints a type path for debugging.
1459 static __attribute__((unused)) void debug_print_type_path(
1460 const type_path_t *path)
1462 size_t len = ARR_LEN(path->path);
1464 for(size_t i = 0; i < len; ++i) {
1465 const type_path_entry_t *entry = & path->path[i];
1467 type_t *type = skip_typeref(entry->type);
1468 if(is_type_compound(type)) {
1469 /* in gcc mode structs can have no members */
1470 if(entry->v.compound_entry == NULL) {
1474 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1475 } else if(is_type_array(type)) {
1476 fprintf(stderr, "[%zd]", entry->v.index);
1478 fprintf(stderr, "-INVALID-");
1481 if(path->top_type != NULL) {
1482 fprintf(stderr, " (");
1483 print_type(path->top_type);
1484 fprintf(stderr, ")");
1489 * Return the top type path entry, ie. in a path
1490 * (type).a.b returns the b.
1492 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1494 size_t len = ARR_LEN(path->path);
1496 return &path->path[len-1];
1500 * Enlarge the type path by an (empty) element.
1502 static type_path_entry_t *append_to_type_path(type_path_t *path)
1504 size_t len = ARR_LEN(path->path);
1505 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1507 type_path_entry_t *result = & path->path[len];
1508 memset(result, 0, sizeof(result[0]));
1513 * Descending into a sub-type. Enter the scope of the current
1516 static void descend_into_subtype(type_path_t *path)
1518 type_t *orig_top_type = path->top_type;
1519 type_t *top_type = skip_typeref(orig_top_type);
1521 assert(is_type_compound(top_type) || is_type_array(top_type));
1523 type_path_entry_t *top = append_to_type_path(path);
1524 top->type = top_type;
1526 if(is_type_compound(top_type)) {
1527 declaration_t *declaration = top_type->compound.declaration;
1528 declaration_t *entry = declaration->scope.declarations;
1529 top->v.compound_entry = entry;
1532 path->top_type = entry->type;
1534 path->top_type = NULL;
1537 assert(is_type_array(top_type));
1540 path->top_type = top_type->array.element_type;
1545 * Pop an entry from the given type path, ie. returning from
1546 * (type).a.b to (type).a
1548 static void ascend_from_subtype(type_path_t *path)
1550 type_path_entry_t *top = get_type_path_top(path);
1552 path->top_type = top->type;
1554 size_t len = ARR_LEN(path->path);
1555 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1559 * Pop entries from the given type path until the given
1560 * path level is reached.
1562 static void ascend_to(type_path_t *path, size_t top_path_level)
1564 size_t len = ARR_LEN(path->path);
1566 while(len > top_path_level) {
1567 ascend_from_subtype(path);
1568 len = ARR_LEN(path->path);
1572 static bool walk_designator(type_path_t *path, const designator_t *designator,
1573 bool used_in_offsetof)
1575 for( ; designator != NULL; designator = designator->next) {
1576 type_path_entry_t *top = get_type_path_top(path);
1577 type_t *orig_type = top->type;
1579 type_t *type = skip_typeref(orig_type);
1581 if(designator->symbol != NULL) {
1582 symbol_t *symbol = designator->symbol;
1583 if(!is_type_compound(type)) {
1584 if(is_type_valid(type)) {
1585 errorf(designator->source_position,
1586 "'.%Y' designator used for non-compound type '%T'",
1592 declaration_t *declaration = type->compound.declaration;
1593 declaration_t *iter = declaration->scope.declarations;
1594 for( ; iter != NULL; iter = iter->next) {
1595 if(iter->symbol == symbol) {
1600 errorf(designator->source_position,
1601 "'%T' has no member named '%Y'", orig_type, symbol);
1604 if(used_in_offsetof) {
1605 type_t *real_type = skip_typeref(iter->type);
1606 if(real_type->kind == TYPE_BITFIELD) {
1607 errorf(designator->source_position,
1608 "offsetof designator '%Y' may not specify bitfield",
1614 top->type = orig_type;
1615 top->v.compound_entry = iter;
1616 orig_type = iter->type;
1618 expression_t *array_index = designator->array_index;
1619 assert(designator->array_index != NULL);
1621 if(!is_type_array(type)) {
1622 if(is_type_valid(type)) {
1623 errorf(designator->source_position,
1624 "[%E] designator used for non-array type '%T'",
1625 array_index, orig_type);
1629 if(!is_type_valid(array_index->base.type)) {
1633 long index = fold_constant(array_index);
1634 if(!used_in_offsetof) {
1636 errorf(designator->source_position,
1637 "array index [%E] must be positive", array_index);
1640 if(type->array.size_constant == true) {
1641 long array_size = type->array.size;
1642 if(index >= array_size) {
1643 errorf(designator->source_position,
1644 "designator [%E] (%d) exceeds array size %d",
1645 array_index, index, array_size);
1651 top->type = orig_type;
1652 top->v.index = (size_t) index;
1653 orig_type = type->array.element_type;
1655 path->top_type = orig_type;
1657 if(designator->next != NULL) {
1658 descend_into_subtype(path);
1667 static void advance_current_object(type_path_t *path, size_t top_path_level)
1669 type_path_entry_t *top = get_type_path_top(path);
1671 type_t *type = skip_typeref(top->type);
1672 if(is_type_union(type)) {
1673 /* in unions only the first element is initialized */
1674 top->v.compound_entry = NULL;
1675 } else if(is_type_struct(type)) {
1676 declaration_t *entry = top->v.compound_entry;
1678 entry = entry->next;
1679 top->v.compound_entry = entry;
1681 path->top_type = entry->type;
1685 assert(is_type_array(type));
1689 if(!type->array.size_constant || top->v.index < type->array.size) {
1694 /* we're past the last member of the current sub-aggregate, try if we
1695 * can ascend in the type hierarchy and continue with another subobject */
1696 size_t len = ARR_LEN(path->path);
1698 if(len > top_path_level) {
1699 ascend_from_subtype(path);
1700 advance_current_object(path, top_path_level);
1702 path->top_type = NULL;
1707 * skip until token is found.
1709 static void skip_until(int type) {
1710 while(token.type != type) {
1711 if(token.type == T_EOF)
1718 * skip any {...} blocks until a closing braket is reached.
1720 static void skip_initializers(void)
1722 if(token.type == '{')
1725 while(token.type != '}') {
1726 if(token.type == T_EOF)
1728 if(token.type == '{') {
1736 static initializer_t *create_empty_initializer(void)
1738 static initializer_t empty_initializer
1739 = { .list = { { INITIALIZER_LIST }, 0 } };
1740 return &empty_initializer;
1744 * Parse a part of an initialiser for a struct or union,
1746 static initializer_t *parse_sub_initializer(type_path_t *path,
1747 type_t *outer_type, size_t top_path_level,
1748 parse_initializer_env_t *env)
1750 if(token.type == '}') {
1751 /* empty initializer */
1752 return create_empty_initializer();
1755 type_t *orig_type = path->top_type;
1756 type_t *type = NULL;
1758 if (orig_type == NULL) {
1759 /* We are initializing an empty compound. */
1761 type = skip_typeref(orig_type);
1763 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1764 * initializers in this case. */
1765 if(!is_type_valid(type)) {
1766 skip_initializers();
1767 return create_empty_initializer();
1771 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1774 designator_t *designator = NULL;
1775 if(token.type == '.' || token.type == '[') {
1776 designator = parse_designation();
1778 /* reset path to toplevel, evaluate designator from there */
1779 ascend_to(path, top_path_level);
1780 if(!walk_designator(path, designator, false)) {
1781 /* can't continue after designation error */
1785 initializer_t *designator_initializer
1786 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1787 designator_initializer->designator.designator = designator;
1788 ARR_APP1(initializer_t*, initializers, designator_initializer);
1793 if(token.type == '{') {
1794 if(type != NULL && is_type_scalar(type)) {
1795 sub = parse_scalar_initializer(type, env->must_be_constant);
1799 if (env->declaration != NULL)
1800 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1801 env->declaration->symbol);
1803 errorf(HERE, "extra brace group at end of initializer");
1805 descend_into_subtype(path);
1807 add_anchor_token('}');
1808 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1810 rem_anchor_token('}');
1813 ascend_from_subtype(path);
1817 goto error_parse_next;
1821 /* must be an expression */
1822 expression_t *expression = parse_assignment_expression();
1824 if(env->must_be_constant && !is_initializer_constant(expression)) {
1825 errorf(expression->base.source_position,
1826 "Initialisation expression '%E' is not constant\n",
1831 /* we are already outside, ... */
1835 /* handle { "string" } special case */
1836 if((expression->kind == EXPR_STRING_LITERAL
1837 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1838 && outer_type != NULL) {
1839 sub = initializer_from_expression(outer_type, expression);
1841 if(token.type == ',') {
1844 if(token.type != '}') {
1845 warningf(HERE, "excessive elements in initializer for type '%T'",
1848 /* TODO: eat , ... */
1853 /* descend into subtypes until expression matches type */
1855 orig_type = path->top_type;
1856 type = skip_typeref(orig_type);
1858 sub = initializer_from_expression(orig_type, expression);
1862 if(!is_type_valid(type)) {
1865 if(is_type_scalar(type)) {
1866 errorf(expression->base.source_position,
1867 "expression '%E' doesn't match expected type '%T'",
1868 expression, orig_type);
1872 descend_into_subtype(path);
1876 /* update largest index of top array */
1877 const type_path_entry_t *first = &path->path[0];
1878 type_t *first_type = first->type;
1879 first_type = skip_typeref(first_type);
1880 if(is_type_array(first_type)) {
1881 size_t index = first->v.index;
1882 if(index > path->max_index)
1883 path->max_index = index;
1887 /* append to initializers list */
1888 ARR_APP1(initializer_t*, initializers, sub);
1891 if(env->declaration != NULL)
1892 warningf(HERE, "excess elements in struct initializer for '%Y'",
1893 env->declaration->symbol);
1895 warningf(HERE, "excess elements in struct initializer");
1899 if(token.type == '}') {
1903 if(token.type == '}') {
1908 /* advance to the next declaration if we are not at the end */
1909 advance_current_object(path, top_path_level);
1910 orig_type = path->top_type;
1911 if(orig_type != NULL)
1912 type = skip_typeref(orig_type);
1918 size_t len = ARR_LEN(initializers);
1919 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1920 initializer_t *result = allocate_ast_zero(size);
1921 result->kind = INITIALIZER_LIST;
1922 result->list.len = len;
1923 memcpy(&result->list.initializers, initializers,
1924 len * sizeof(initializers[0]));
1926 DEL_ARR_F(initializers);
1927 ascend_to(path, top_path_level);
1932 skip_initializers();
1933 DEL_ARR_F(initializers);
1934 ascend_to(path, top_path_level);
1939 * Parses an initializer. Parsers either a compound literal
1940 * (env->declaration == NULL) or an initializer of a declaration.
1942 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1944 type_t *type = skip_typeref(env->type);
1945 initializer_t *result = NULL;
1948 if(is_type_scalar(type)) {
1949 result = parse_scalar_initializer(type, env->must_be_constant);
1950 } else if(token.type == '{') {
1954 memset(&path, 0, sizeof(path));
1955 path.top_type = env->type;
1956 path.path = NEW_ARR_F(type_path_entry_t, 0);
1958 descend_into_subtype(&path);
1960 add_anchor_token('}');
1961 result = parse_sub_initializer(&path, env->type, 1, env);
1962 rem_anchor_token('}');
1964 max_index = path.max_index;
1965 DEL_ARR_F(path.path);
1969 /* parse_scalar_initializer() also works in this case: we simply
1970 * have an expression without {} around it */
1971 result = parse_scalar_initializer(type, env->must_be_constant);
1974 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1975 * the array type size */
1976 if(is_type_array(type) && type->array.size_expression == NULL
1977 && result != NULL) {
1979 switch (result->kind) {
1980 case INITIALIZER_LIST:
1981 size = max_index + 1;
1984 case INITIALIZER_STRING:
1985 size = result->string.string.size;
1988 case INITIALIZER_WIDE_STRING:
1989 size = result->wide_string.string.size;
1993 internal_errorf(HERE, "invalid initializer type");
1996 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1997 cnst->base.type = type_size_t;
1998 cnst->conste.v.int_value = size;
2000 type_t *new_type = duplicate_type(type);
2002 new_type->array.size_expression = cnst;
2003 new_type->array.size_constant = true;
2004 new_type->array.size = size;
2005 env->type = new_type;
2013 static declaration_t *append_declaration(declaration_t *declaration);
2015 static declaration_t *parse_compound_type_specifier(bool is_struct)
2023 symbol_t *symbol = NULL;
2024 declaration_t *declaration = NULL;
2026 if (token.type == T___attribute__) {
2031 if(token.type == T_IDENTIFIER) {
2032 symbol = token.v.symbol;
2036 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2038 declaration = get_declaration(symbol, NAMESPACE_UNION);
2040 } else if(token.type != '{') {
2042 parse_error_expected("while parsing struct type specifier",
2043 T_IDENTIFIER, '{', 0);
2045 parse_error_expected("while parsing union type specifier",
2046 T_IDENTIFIER, '{', 0);
2052 if(declaration == NULL) {
2053 declaration = allocate_declaration_zero();
2054 declaration->namespc =
2055 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2056 declaration->source_position = token.source_position;
2057 declaration->symbol = symbol;
2058 declaration->parent_scope = scope;
2059 if (symbol != NULL) {
2060 environment_push(declaration);
2062 append_declaration(declaration);
2065 if(token.type == '{') {
2066 if(declaration->init.is_defined) {
2067 assert(symbol != NULL);
2068 errorf(HERE, "multiple definitions of '%s %Y'",
2069 is_struct ? "struct" : "union", symbol);
2070 declaration->scope.declarations = NULL;
2072 declaration->init.is_defined = true;
2074 parse_compound_type_entries(declaration);
2081 static void parse_enum_entries(type_t *const enum_type)
2085 if(token.type == '}') {
2087 errorf(HERE, "empty enum not allowed");
2091 add_anchor_token('}');
2093 if(token.type != T_IDENTIFIER) {
2094 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2096 rem_anchor_token('}');
2100 declaration_t *const entry = allocate_declaration_zero();
2101 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2102 entry->type = enum_type;
2103 entry->symbol = token.v.symbol;
2104 entry->source_position = token.source_position;
2107 if(token.type == '=') {
2109 expression_t *value = parse_constant_expression();
2111 value = create_implicit_cast(value, enum_type);
2112 entry->init.enum_value = value;
2117 record_declaration(entry);
2119 if(token.type != ',')
2122 } while(token.type != '}');
2123 rem_anchor_token('}');
2131 static type_t *parse_enum_specifier(void)
2135 declaration_t *declaration;
2138 if(token.type == T_IDENTIFIER) {
2139 symbol = token.v.symbol;
2142 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2143 } else if(token.type != '{') {
2144 parse_error_expected("while parsing enum type specifier",
2145 T_IDENTIFIER, '{', 0);
2152 if(declaration == NULL) {
2153 declaration = allocate_declaration_zero();
2154 declaration->namespc = NAMESPACE_ENUM;
2155 declaration->source_position = token.source_position;
2156 declaration->symbol = symbol;
2157 declaration->parent_scope = scope;
2160 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2161 type->enumt.declaration = declaration;
2163 if(token.type == '{') {
2164 if(declaration->init.is_defined) {
2165 errorf(HERE, "multiple definitions of enum %Y", symbol);
2167 if (symbol != NULL) {
2168 environment_push(declaration);
2170 append_declaration(declaration);
2171 declaration->init.is_defined = 1;
2173 parse_enum_entries(type);
2181 * if a symbol is a typedef to another type, return true
2183 static bool is_typedef_symbol(symbol_t *symbol)
2185 const declaration_t *const declaration =
2186 get_declaration(symbol, NAMESPACE_NORMAL);
2188 declaration != NULL &&
2189 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2192 static type_t *parse_typeof(void)
2199 add_anchor_token(')');
2201 expression_t *expression = NULL;
2204 switch(token.type) {
2205 case T___extension__:
2206 /* this can be a prefix to a typename or an expression */
2207 /* we simply eat it now. */
2210 } while(token.type == T___extension__);
2214 if(is_typedef_symbol(token.v.symbol)) {
2215 type = parse_typename();
2217 expression = parse_expression();
2218 type = expression->base.type;
2223 type = parse_typename();
2227 expression = parse_expression();
2228 type = expression->base.type;
2232 rem_anchor_token(')');
2235 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2236 typeof_type->typeoft.expression = expression;
2237 typeof_type->typeoft.typeof_type = type;
2245 SPECIFIER_SIGNED = 1 << 0,
2246 SPECIFIER_UNSIGNED = 1 << 1,
2247 SPECIFIER_LONG = 1 << 2,
2248 SPECIFIER_INT = 1 << 3,
2249 SPECIFIER_DOUBLE = 1 << 4,
2250 SPECIFIER_CHAR = 1 << 5,
2251 SPECIFIER_SHORT = 1 << 6,
2252 SPECIFIER_LONG_LONG = 1 << 7,
2253 SPECIFIER_FLOAT = 1 << 8,
2254 SPECIFIER_BOOL = 1 << 9,
2255 SPECIFIER_VOID = 1 << 10,
2256 SPECIFIER_INT8 = 1 << 11,
2257 SPECIFIER_INT16 = 1 << 12,
2258 SPECIFIER_INT32 = 1 << 13,
2259 SPECIFIER_INT64 = 1 << 14,
2260 SPECIFIER_INT128 = 1 << 15,
2261 #ifdef PROVIDE_COMPLEX
2262 SPECIFIER_COMPLEX = 1 << 16,
2263 SPECIFIER_IMAGINARY = 1 << 17,
2267 static type_t *create_builtin_type(symbol_t *const symbol,
2268 type_t *const real_type)
2270 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2271 type->builtin.symbol = symbol;
2272 type->builtin.real_type = real_type;
2274 type_t *result = typehash_insert(type);
2275 if (type != result) {
2282 static type_t *get_typedef_type(symbol_t *symbol)
2284 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2285 if(declaration == NULL
2286 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2289 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2290 type->typedeft.declaration = declaration;
2296 * check for the allowed MS alignment values.
2298 static bool check_elignment_value(long long intvalue) {
2299 if(intvalue < 1 || intvalue > 8192) {
2300 errorf(HERE, "illegal alignment value");
2303 unsigned v = (unsigned)intvalue;
2304 for(unsigned i = 1; i <= 8192; i += i) {
2308 errorf(HERE, "alignment must be power of two");
2312 #define DET_MOD(name, tag) do { \
2313 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2314 *modifiers |= tag; \
2317 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2319 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2322 if(token.type == T_restrict) {
2324 DET_MOD(restrict, DM_RESTRICT);
2326 } else if(token.type != T_IDENTIFIER)
2328 symbol_t *symbol = token.v.symbol;
2329 if(symbol == sym_align) {
2332 if(token.type != T_INTEGER)
2334 if(check_elignment_value(token.v.intvalue)) {
2335 if(specifiers->alignment != 0)
2336 warningf(HERE, "align used more than once");
2337 specifiers->alignment = (unsigned char)token.v.intvalue;
2341 } else if(symbol == sym_allocate) {
2344 if(token.type != T_IDENTIFIER)
2346 (void)token.v.symbol;
2348 } else if(symbol == sym_dllimport) {
2350 DET_MOD(dllimport, DM_DLLIMPORT);
2351 } else if(symbol == sym_dllexport) {
2353 DET_MOD(dllexport, DM_DLLEXPORT);
2354 } else if(symbol == sym_thread) {
2356 DET_MOD(thread, DM_THREAD);
2357 } else if(symbol == sym_naked) {
2359 DET_MOD(naked, DM_NAKED);
2360 } else if(symbol == sym_noinline) {
2362 DET_MOD(noinline, DM_NOINLINE);
2363 } else if(symbol == sym_noreturn) {
2365 DET_MOD(noreturn, DM_NORETURN);
2366 } else if(symbol == sym_nothrow) {
2368 DET_MOD(nothrow, DM_NOTHROW);
2369 } else if(symbol == sym_novtable) {
2371 DET_MOD(novtable, DM_NOVTABLE);
2372 } else if(symbol == sym_property) {
2376 bool is_get = false;
2377 if(token.type != T_IDENTIFIER)
2379 if(token.v.symbol == sym_get) {
2381 } else if(token.v.symbol == sym_put) {
2383 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2388 if(token.type != T_IDENTIFIER)
2391 if(specifiers->get_property_sym != NULL) {
2392 errorf(HERE, "get property name already specified");
2394 specifiers->get_property_sym = token.v.symbol;
2397 if(specifiers->put_property_sym != NULL) {
2398 errorf(HERE, "put property name already specified");
2400 specifiers->put_property_sym = token.v.symbol;
2404 if(token.type == ',') {
2411 } else if(symbol == sym_selectany) {
2413 DET_MOD(selectany, DM_SELECTANY);
2414 } else if(symbol == sym_uuid) {
2417 if(token.type != T_STRING_LITERAL)
2421 } else if(symbol == sym_deprecated) {
2423 if(specifiers->deprecated != 0)
2424 warningf(HERE, "deprecated used more than once");
2425 specifiers->deprecated = 1;
2426 if(token.type == '(') {
2428 if(token.type == T_STRING_LITERAL) {
2429 specifiers->deprecated_string = token.v.string.begin;
2432 errorf(HERE, "string literal expected");
2436 } else if(symbol == sym_noalias) {
2438 DET_MOD(noalias, DM_NOALIAS);
2440 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2442 if(token.type == '(')
2446 if (token.type == ',')
2453 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2455 type_t *type = NULL;
2456 unsigned type_qualifiers = 0;
2457 unsigned type_specifiers = 0;
2460 specifiers->source_position = token.source_position;
2463 switch(token.type) {
2466 #define MATCH_STORAGE_CLASS(token, class) \
2468 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2469 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2471 specifiers->declared_storage_class = class; \
2475 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2476 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2477 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2478 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2479 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2484 add_anchor_token(')');
2485 parse_microsoft_extended_decl_modifier(specifiers);
2486 rem_anchor_token(')');
2491 switch (specifiers->declared_storage_class) {
2492 case STORAGE_CLASS_NONE:
2493 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2496 case STORAGE_CLASS_EXTERN:
2497 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2500 case STORAGE_CLASS_STATIC:
2501 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2505 errorf(HERE, "multiple storage classes in declaration specifiers");
2511 /* type qualifiers */
2512 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2514 type_qualifiers |= qualifier; \
2518 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2519 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2520 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2521 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2522 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2523 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2524 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2525 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2527 case T___extension__:
2532 /* type specifiers */
2533 #define MATCH_SPECIFIER(token, specifier, name) \
2536 if(type_specifiers & specifier) { \
2537 errorf(HERE, "multiple " name " type specifiers given"); \
2539 type_specifiers |= specifier; \
2543 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2544 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2545 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2546 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2547 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2548 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2549 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2550 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2551 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2552 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2553 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2554 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2555 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2556 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2557 #ifdef PROVIDE_COMPLEX
2558 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2559 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2561 case T__forceinline:
2562 /* only in microsoft mode */
2563 specifiers->decl_modifiers |= DM_FORCEINLINE;
2567 specifiers->is_inline = true;
2572 if(type_specifiers & SPECIFIER_LONG_LONG) {
2573 errorf(HERE, "multiple type specifiers given");
2574 } else if(type_specifiers & SPECIFIER_LONG) {
2575 type_specifiers |= SPECIFIER_LONG_LONG;
2577 type_specifiers |= SPECIFIER_LONG;
2582 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2584 type->compound.declaration = parse_compound_type_specifier(true);
2588 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2590 type->compound.declaration = parse_compound_type_specifier(false);
2594 type = parse_enum_specifier();
2597 type = parse_typeof();
2599 case T___builtin_va_list:
2600 type = duplicate_type(type_valist);
2604 case T___attribute__:
2608 case T_IDENTIFIER: {
2609 /* only parse identifier if we haven't found a type yet */
2610 if(type != NULL || type_specifiers != 0)
2611 goto finish_specifiers;
2613 type_t *typedef_type = get_typedef_type(token.v.symbol);
2615 if(typedef_type == NULL)
2616 goto finish_specifiers;
2619 type = typedef_type;
2623 /* function specifier */
2625 goto finish_specifiers;
2632 atomic_type_kind_t atomic_type;
2634 /* match valid basic types */
2635 switch(type_specifiers) {
2636 case SPECIFIER_VOID:
2637 atomic_type = ATOMIC_TYPE_VOID;
2639 case SPECIFIER_CHAR:
2640 atomic_type = ATOMIC_TYPE_CHAR;
2642 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2643 atomic_type = ATOMIC_TYPE_SCHAR;
2645 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2646 atomic_type = ATOMIC_TYPE_UCHAR;
2648 case SPECIFIER_SHORT:
2649 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2650 case SPECIFIER_SHORT | SPECIFIER_INT:
2651 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2652 atomic_type = ATOMIC_TYPE_SHORT;
2654 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2655 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2656 atomic_type = ATOMIC_TYPE_USHORT;
2659 case SPECIFIER_SIGNED:
2660 case SPECIFIER_SIGNED | SPECIFIER_INT:
2661 atomic_type = ATOMIC_TYPE_INT;
2663 case SPECIFIER_UNSIGNED:
2664 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2665 atomic_type = ATOMIC_TYPE_UINT;
2667 case SPECIFIER_LONG:
2668 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2669 case SPECIFIER_LONG | SPECIFIER_INT:
2670 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2671 atomic_type = ATOMIC_TYPE_LONG;
2673 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2674 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2675 atomic_type = ATOMIC_TYPE_ULONG;
2677 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2678 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2679 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2680 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2682 atomic_type = ATOMIC_TYPE_LONGLONG;
2684 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2685 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2687 atomic_type = ATOMIC_TYPE_ULONGLONG;
2690 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2691 atomic_type = unsigned_int8_type_kind;
2694 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2695 atomic_type = unsigned_int16_type_kind;
2698 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2699 atomic_type = unsigned_int32_type_kind;
2702 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2703 atomic_type = unsigned_int64_type_kind;
2706 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2707 atomic_type = unsigned_int128_type_kind;
2710 case SPECIFIER_INT8:
2711 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2712 atomic_type = int8_type_kind;
2715 case SPECIFIER_INT16:
2716 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2717 atomic_type = int16_type_kind;
2720 case SPECIFIER_INT32:
2721 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2722 atomic_type = int32_type_kind;
2725 case SPECIFIER_INT64:
2726 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2727 atomic_type = int64_type_kind;
2730 case SPECIFIER_INT128:
2731 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2732 atomic_type = int128_type_kind;
2735 case SPECIFIER_FLOAT:
2736 atomic_type = ATOMIC_TYPE_FLOAT;
2738 case SPECIFIER_DOUBLE:
2739 atomic_type = ATOMIC_TYPE_DOUBLE;
2741 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2742 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2744 case SPECIFIER_BOOL:
2745 atomic_type = ATOMIC_TYPE_BOOL;
2747 #ifdef PROVIDE_COMPLEX
2748 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2749 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2751 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2752 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2754 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2755 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2757 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2758 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2760 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2761 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2763 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2764 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2768 /* invalid specifier combination, give an error message */
2769 if(type_specifiers == 0) {
2770 if (! strict_mode) {
2771 if (warning.implicit_int) {
2772 warningf(HERE, "no type specifiers in declaration, using 'int'");
2774 atomic_type = ATOMIC_TYPE_INT;
2777 errorf(HERE, "no type specifiers given in declaration");
2779 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2780 (type_specifiers & SPECIFIER_UNSIGNED)) {
2781 errorf(HERE, "signed and unsigned specifiers gives");
2782 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2783 errorf(HERE, "only integer types can be signed or unsigned");
2785 errorf(HERE, "multiple datatypes in declaration");
2787 atomic_type = ATOMIC_TYPE_INVALID;
2790 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2791 type->atomic.akind = atomic_type;
2794 if(type_specifiers != 0) {
2795 errorf(HERE, "multiple datatypes in declaration");
2799 type->base.qualifiers = type_qualifiers;
2800 /* FIXME: check type qualifiers here */
2802 type_t *result = typehash_insert(type);
2803 if(newtype && result != type) {
2807 specifiers->type = result;
2812 static type_qualifiers_t parse_type_qualifiers(void)
2814 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2817 switch(token.type) {
2818 /* type qualifiers */
2819 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2820 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2821 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2822 /* microsoft extended type modifiers */
2823 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2824 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2825 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2826 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2827 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2830 return type_qualifiers;
2835 static declaration_t *parse_identifier_list(void)
2837 declaration_t *declarations = NULL;
2838 declaration_t *last_declaration = NULL;
2840 declaration_t *const declaration = allocate_declaration_zero();
2841 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2842 declaration->source_position = token.source_position;
2843 declaration->symbol = token.v.symbol;
2846 if(last_declaration != NULL) {
2847 last_declaration->next = declaration;
2849 declarations = declaration;
2851 last_declaration = declaration;
2853 if(token.type != ',')
2856 } while(token.type == T_IDENTIFIER);
2858 return declarations;
2861 static void semantic_parameter(declaration_t *declaration)
2863 /* TODO: improve error messages */
2865 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2866 errorf(HERE, "typedef not allowed in parameter list");
2867 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2868 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2869 errorf(HERE, "parameter may only have none or register storage class");
2872 type_t *const orig_type = declaration->type;
2873 type_t * type = skip_typeref(orig_type);
2875 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2876 * into a pointer. § 6.7.5.3 (7) */
2877 if (is_type_array(type)) {
2878 type_t *const element_type = type->array.element_type;
2880 type = make_pointer_type(element_type, type->base.qualifiers);
2882 declaration->type = type;
2885 if(is_type_incomplete(type)) {
2886 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2887 orig_type, declaration->symbol);
2891 static declaration_t *parse_parameter(void)
2893 declaration_specifiers_t specifiers;
2894 memset(&specifiers, 0, sizeof(specifiers));
2896 parse_declaration_specifiers(&specifiers);
2898 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2900 semantic_parameter(declaration);
2905 static declaration_t *parse_parameters(function_type_t *type)
2907 if(token.type == T_IDENTIFIER) {
2908 symbol_t *symbol = token.v.symbol;
2909 if(!is_typedef_symbol(symbol)) {
2910 type->kr_style_parameters = true;
2911 return parse_identifier_list();
2915 if(token.type == ')') {
2916 type->unspecified_parameters = 1;
2919 if(token.type == T_void && look_ahead(1)->type == ')') {
2924 declaration_t *declarations = NULL;
2925 declaration_t *declaration;
2926 declaration_t *last_declaration = NULL;
2927 function_parameter_t *parameter;
2928 function_parameter_t *last_parameter = NULL;
2931 switch(token.type) {
2935 return declarations;
2938 case T___extension__:
2940 declaration = parse_parameter();
2942 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2943 memset(parameter, 0, sizeof(parameter[0]));
2944 parameter->type = declaration->type;
2946 if(last_parameter != NULL) {
2947 last_declaration->next = declaration;
2948 last_parameter->next = parameter;
2950 type->parameters = parameter;
2951 declarations = declaration;
2953 last_parameter = parameter;
2954 last_declaration = declaration;
2958 return declarations;
2960 if(token.type != ',')
2961 return declarations;
2971 } construct_type_kind_t;
2973 typedef struct construct_type_t construct_type_t;
2974 struct construct_type_t {
2975 construct_type_kind_t kind;
2976 construct_type_t *next;
2979 typedef struct parsed_pointer_t parsed_pointer_t;
2980 struct parsed_pointer_t {
2981 construct_type_t construct_type;
2982 type_qualifiers_t type_qualifiers;
2985 typedef struct construct_function_type_t construct_function_type_t;
2986 struct construct_function_type_t {
2987 construct_type_t construct_type;
2988 type_t *function_type;
2991 typedef struct parsed_array_t parsed_array_t;
2992 struct parsed_array_t {
2993 construct_type_t construct_type;
2994 type_qualifiers_t type_qualifiers;
3000 typedef struct construct_base_type_t construct_base_type_t;
3001 struct construct_base_type_t {
3002 construct_type_t construct_type;
3006 static construct_type_t *parse_pointer_declarator(void)
3010 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3011 memset(pointer, 0, sizeof(pointer[0]));
3012 pointer->construct_type.kind = CONSTRUCT_POINTER;
3013 pointer->type_qualifiers = parse_type_qualifiers();
3015 return (construct_type_t*) pointer;
3018 static construct_type_t *parse_array_declarator(void)
3021 add_anchor_token(']');
3023 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3024 memset(array, 0, sizeof(array[0]));
3025 array->construct_type.kind = CONSTRUCT_ARRAY;
3027 if(token.type == T_static) {
3028 array->is_static = true;
3032 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3033 if(type_qualifiers != 0) {
3034 if(token.type == T_static) {
3035 array->is_static = true;
3039 array->type_qualifiers = type_qualifiers;
3041 if(token.type == '*' && look_ahead(1)->type == ']') {
3042 array->is_variable = true;
3044 } else if(token.type != ']') {
3045 array->size = parse_assignment_expression();
3048 rem_anchor_token(']');
3051 return (construct_type_t*) array;
3056 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3059 add_anchor_token(')');
3062 if(declaration != NULL) {
3063 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
3065 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
3068 declaration_t *parameters = parse_parameters(&type->function);
3069 if(declaration != NULL) {
3070 declaration->scope.declarations = parameters;
3073 construct_function_type_t *construct_function_type =
3074 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3075 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3076 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3077 construct_function_type->function_type = type;
3079 rem_anchor_token(')');
3083 return (construct_type_t*) construct_function_type;
3086 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3087 bool may_be_abstract)
3089 /* construct a single linked list of construct_type_t's which describe
3090 * how to construct the final declarator type */
3091 construct_type_t *first = NULL;
3092 construct_type_t *last = NULL;
3095 while(token.type == '*') {
3096 construct_type_t *type = parse_pointer_declarator();
3107 /* TODO: find out if this is correct */
3110 construct_type_t *inner_types = NULL;
3112 switch(token.type) {
3114 if(declaration == NULL) {
3115 errorf(HERE, "no identifier expected in typename");
3117 declaration->symbol = token.v.symbol;
3118 declaration->source_position = token.source_position;
3124 add_anchor_token(')');
3125 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3126 rem_anchor_token(')');
3132 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3133 /* avoid a loop in the outermost scope, because eat_statement doesn't
3135 if(token.type == '}' && current_function == NULL) {
3143 construct_type_t *p = last;
3146 construct_type_t *type;
3147 switch(token.type) {
3149 type = parse_function_declarator(declaration);
3152 type = parse_array_declarator();
3155 goto declarator_finished;
3158 /* insert in the middle of the list (behind p) */
3160 type->next = p->next;
3171 declarator_finished:
3174 /* append inner_types at the end of the list, we don't to set last anymore
3175 * as it's not needed anymore */
3177 assert(first == NULL);
3178 first = inner_types;
3180 last->next = inner_types;
3188 static type_t *construct_declarator_type(construct_type_t *construct_list,
3191 construct_type_t *iter = construct_list;
3192 for( ; iter != NULL; iter = iter->next) {
3193 switch(iter->kind) {
3194 case CONSTRUCT_INVALID:
3195 internal_errorf(HERE, "invalid type construction found");
3196 case CONSTRUCT_FUNCTION: {
3197 construct_function_type_t *construct_function_type
3198 = (construct_function_type_t*) iter;
3200 type_t *function_type = construct_function_type->function_type;
3202 function_type->function.return_type = type;
3204 type_t *skipped_return_type = skip_typeref(type);
3205 if (is_type_function(skipped_return_type)) {
3206 errorf(HERE, "function returning function is not allowed");
3207 type = type_error_type;
3208 } else if (is_type_array(skipped_return_type)) {
3209 errorf(HERE, "function returning array is not allowed");
3210 type = type_error_type;
3212 type = function_type;
3217 case CONSTRUCT_POINTER: {
3218 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3219 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3220 pointer_type->pointer.points_to = type;
3221 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3223 type = pointer_type;
3227 case CONSTRUCT_ARRAY: {
3228 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3229 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3231 expression_t *size_expression = parsed_array->size;
3232 if(size_expression != NULL) {
3234 = create_implicit_cast(size_expression, type_size_t);
3237 array_type->base.qualifiers = parsed_array->type_qualifiers;
3238 array_type->array.element_type = type;
3239 array_type->array.is_static = parsed_array->is_static;
3240 array_type->array.is_variable = parsed_array->is_variable;
3241 array_type->array.size_expression = size_expression;
3243 if(size_expression != NULL) {
3244 if(is_constant_expression(size_expression)) {
3245 array_type->array.size_constant = true;
3246 array_type->array.size
3247 = fold_constant(size_expression);
3249 array_type->array.is_vla = true;
3253 type_t *skipped_type = skip_typeref(type);
3254 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3255 errorf(HERE, "array of void is not allowed");
3256 type = type_error_type;
3264 type_t *hashed_type = typehash_insert(type);
3265 if(hashed_type != type) {
3266 /* the function type was constructed earlier freeing it here will
3267 * destroy other types... */
3268 if(iter->kind != CONSTRUCT_FUNCTION) {
3278 static declaration_t *parse_declarator(
3279 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3281 declaration_t *const declaration = allocate_declaration_zero();
3282 declaration->declared_storage_class = specifiers->declared_storage_class;
3283 declaration->modifiers = specifiers->decl_modifiers;
3284 declaration->deprecated = specifiers->deprecated;
3285 declaration->deprecated_string = specifiers->deprecated_string;
3286 declaration->get_property_sym = specifiers->get_property_sym;
3287 declaration->put_property_sym = specifiers->put_property_sym;
3288 declaration->is_inline = specifiers->is_inline;
3290 declaration->storage_class = specifiers->declared_storage_class;
3291 if(declaration->storage_class == STORAGE_CLASS_NONE
3292 && scope != global_scope) {
3293 declaration->storage_class = STORAGE_CLASS_AUTO;
3296 if(specifiers->alignment != 0) {
3297 /* TODO: add checks here */
3298 declaration->alignment = specifiers->alignment;
3301 construct_type_t *construct_type
3302 = parse_inner_declarator(declaration, may_be_abstract);
3303 type_t *const type = specifiers->type;
3304 declaration->type = construct_declarator_type(construct_type, type);
3306 if(construct_type != NULL) {
3307 obstack_free(&temp_obst, construct_type);
3313 static type_t *parse_abstract_declarator(type_t *base_type)
3315 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3317 type_t *result = construct_declarator_type(construct_type, base_type);
3318 if(construct_type != NULL) {
3319 obstack_free(&temp_obst, construct_type);
3325 static declaration_t *append_declaration(declaration_t* const declaration)
3327 if (last_declaration != NULL) {
3328 last_declaration->next = declaration;
3330 scope->declarations = declaration;
3332 last_declaration = declaration;
3337 * Check if the declaration of main is suspicious. main should be a
3338 * function with external linkage, returning int, taking either zero
3339 * arguments, two, or three arguments of appropriate types, ie.
3341 * int main([ int argc, char **argv [, char **env ] ]).
3343 * @param decl the declaration to check
3344 * @param type the function type of the declaration
3346 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3348 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3349 warningf(decl->source_position, "'main' is normally a non-static function");
3351 if (skip_typeref(func_type->return_type) != type_int) {
3352 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3354 const function_parameter_t *parm = func_type->parameters;
3356 type_t *const first_type = parm->type;
3357 if (!types_compatible(skip_typeref(first_type), type_int)) {
3358 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3362 type_t *const second_type = parm->type;
3363 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3364 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3368 type_t *const third_type = parm->type;
3369 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3370 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3374 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3378 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3384 * Check if a symbol is the equal to "main".
3386 static bool is_sym_main(const symbol_t *const sym)
3388 return strcmp(sym->string, "main") == 0;
3391 static declaration_t *internal_record_declaration(
3392 declaration_t *const declaration,
3393 const bool is_function_definition)
3395 const symbol_t *const symbol = declaration->symbol;
3396 const namespace_t namespc = (namespace_t)declaration->namespc;
3398 type_t *const orig_type = declaration->type;
3399 type_t *const type = skip_typeref(orig_type);
3400 if (is_type_function(type) &&
3401 type->function.unspecified_parameters &&
3402 warning.strict_prototypes) {
3403 warningf(declaration->source_position,
3404 "function declaration '%#T' is not a prototype",
3405 orig_type, declaration->symbol);
3408 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3409 check_type_of_main(declaration, &type->function);
3412 assert(declaration->symbol != NULL);
3413 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3415 assert(declaration != previous_declaration);
3416 if (previous_declaration != NULL) {
3417 if (previous_declaration->parent_scope == scope) {
3418 /* can happen for K&R style declarations */
3419 if(previous_declaration->type == NULL) {
3420 previous_declaration->type = declaration->type;
3423 const type_t *prev_type = skip_typeref(previous_declaration->type);
3424 if (!types_compatible(type, prev_type)) {
3425 errorf(declaration->source_position,
3426 "declaration '%#T' is incompatible with "
3427 "previous declaration '%#T'",
3428 orig_type, symbol, previous_declaration->type, symbol);
3429 errorf(previous_declaration->source_position,
3430 "previous declaration of '%Y' was here", symbol);
3432 unsigned old_storage_class = previous_declaration->storage_class;
3433 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3434 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3435 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3436 return previous_declaration;
3439 unsigned new_storage_class = declaration->storage_class;
3441 if(is_type_incomplete(prev_type)) {
3442 previous_declaration->type = type;
3446 /* pretend no storage class means extern for function
3447 * declarations (except if the previous declaration is neither
3448 * none nor extern) */
3449 if (is_type_function(type)) {
3450 switch (old_storage_class) {
3451 case STORAGE_CLASS_NONE:
3452 old_storage_class = STORAGE_CLASS_EXTERN;
3454 case STORAGE_CLASS_EXTERN:
3455 if (is_function_definition) {
3456 if (warning.missing_prototypes &&
3457 prev_type->function.unspecified_parameters &&
3458 !is_sym_main(symbol)) {
3459 warningf(declaration->source_position,
3460 "no previous prototype for '%#T'",
3463 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3464 new_storage_class = STORAGE_CLASS_EXTERN;
3472 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3473 new_storage_class == STORAGE_CLASS_EXTERN) {
3474 warn_redundant_declaration:
3475 if (warning.redundant_decls) {
3476 warningf(declaration->source_position,
3477 "redundant declaration for '%Y'", symbol);
3478 warningf(previous_declaration->source_position,
3479 "previous declaration of '%Y' was here",
3482 } else if (current_function == NULL) {
3483 if (old_storage_class != STORAGE_CLASS_STATIC &&
3484 new_storage_class == STORAGE_CLASS_STATIC) {
3485 errorf(declaration->source_position,
3486 "static declaration of '%Y' follows non-static declaration",
3488 errorf(previous_declaration->source_position,
3489 "previous declaration of '%Y' was here", symbol);
3491 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3492 goto warn_redundant_declaration;
3494 if (new_storage_class == STORAGE_CLASS_NONE) {
3495 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3496 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3500 if (old_storage_class == new_storage_class) {
3501 errorf(declaration->source_position,
3502 "redeclaration of '%Y'", symbol);
3504 errorf(declaration->source_position,
3505 "redeclaration of '%Y' with different linkage",
3508 errorf(previous_declaration->source_position,
3509 "previous declaration of '%Y' was here", symbol);
3512 return previous_declaration;
3514 } else if (is_function_definition) {
3515 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3516 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3517 warningf(declaration->source_position,
3518 "no previous prototype for '%#T'", orig_type, symbol);
3519 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3520 warningf(declaration->source_position,
3521 "no previous declaration for '%#T'", orig_type,
3525 } else if (warning.missing_declarations &&
3526 scope == global_scope &&
3527 !is_type_function(type) && (
3528 declaration->storage_class == STORAGE_CLASS_NONE ||
3529 declaration->storage_class == STORAGE_CLASS_THREAD
3531 warningf(declaration->source_position,
3532 "no previous declaration for '%#T'", orig_type, symbol);
3535 assert(declaration->parent_scope == NULL);
3536 assert(scope != NULL);
3538 declaration->parent_scope = scope;
3540 environment_push(declaration);
3541 return append_declaration(declaration);
3544 static declaration_t *record_declaration(declaration_t *declaration)
3546 return internal_record_declaration(declaration, false);
3549 static declaration_t *record_function_definition(declaration_t *declaration)
3551 return internal_record_declaration(declaration, true);
3554 static void parser_error_multiple_definition(declaration_t *declaration,
3555 const source_position_t source_position)
3557 errorf(source_position, "multiple definition of symbol '%Y'",
3558 declaration->symbol);
3559 errorf(declaration->source_position,
3560 "this is the location of the previous definition.");
3563 static bool is_declaration_specifier(const token_t *token,
3564 bool only_type_specifiers)
3566 switch(token->type) {
3570 return is_typedef_symbol(token->v.symbol);
3572 case T___extension__:
3575 return !only_type_specifiers;
3582 static void parse_init_declarator_rest(declaration_t *declaration)
3586 type_t *orig_type = declaration->type;
3587 type_t *type = skip_typeref(orig_type);
3589 if(declaration->init.initializer != NULL) {
3590 parser_error_multiple_definition(declaration, token.source_position);
3593 bool must_be_constant = false;
3594 if(declaration->storage_class == STORAGE_CLASS_STATIC
3595 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3596 || declaration->parent_scope == global_scope) {
3597 must_be_constant = true;
3600 parse_initializer_env_t env;
3601 env.type = orig_type;
3602 env.must_be_constant = must_be_constant;
3603 env.declaration = declaration;
3605 initializer_t *initializer = parse_initializer(&env);
3607 if(env.type != orig_type) {
3608 orig_type = env.type;
3609 type = skip_typeref(orig_type);
3610 declaration->type = env.type;
3613 if(is_type_function(type)) {
3614 errorf(declaration->source_position,
3615 "initializers not allowed for function types at declator '%Y' (type '%T')",
3616 declaration->symbol, orig_type);
3618 declaration->init.initializer = initializer;
3622 /* parse rest of a declaration without any declarator */
3623 static void parse_anonymous_declaration_rest(
3624 const declaration_specifiers_t *specifiers,
3625 parsed_declaration_func finished_declaration)
3629 declaration_t *const declaration = allocate_declaration_zero();
3630 declaration->type = specifiers->type;
3631 declaration->declared_storage_class = specifiers->declared_storage_class;
3632 declaration->source_position = specifiers->source_position;
3633 declaration->modifiers = specifiers->decl_modifiers;
3635 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3636 warningf(declaration->source_position, "useless storage class in empty declaration");
3638 declaration->storage_class = STORAGE_CLASS_NONE;
3640 type_t *type = declaration->type;
3641 switch (type->kind) {
3642 case TYPE_COMPOUND_STRUCT:
3643 case TYPE_COMPOUND_UNION: {
3644 if (type->compound.declaration->symbol == NULL) {
3645 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3654 warningf(declaration->source_position, "empty declaration");
3658 finished_declaration(declaration);
3661 static void parse_declaration_rest(declaration_t *ndeclaration,
3662 const declaration_specifiers_t *specifiers,
3663 parsed_declaration_func finished_declaration)
3665 add_anchor_token(';');
3666 add_anchor_token('=');
3667 add_anchor_token(',');
3669 declaration_t *declaration = finished_declaration(ndeclaration);
3671 type_t *orig_type = declaration->type;
3672 type_t *type = skip_typeref(orig_type);
3674 if (type->kind != TYPE_FUNCTION &&
3675 declaration->is_inline &&
3676 is_type_valid(type)) {
3677 warningf(declaration->source_position,
3678 "variable '%Y' declared 'inline'\n", declaration->symbol);
3681 if(token.type == '=') {
3682 parse_init_declarator_rest(declaration);
3685 if(token.type != ',')
3689 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3694 rem_anchor_token(';');
3695 rem_anchor_token('=');
3696 rem_anchor_token(',');
3699 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3701 symbol_t *symbol = declaration->symbol;
3702 if(symbol == NULL) {
3703 errorf(HERE, "anonymous declaration not valid as function parameter");
3706 namespace_t namespc = (namespace_t) declaration->namespc;
3707 if(namespc != NAMESPACE_NORMAL) {
3708 return record_declaration(declaration);
3711 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3712 if(previous_declaration == NULL ||
3713 previous_declaration->parent_scope != scope) {
3714 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3719 if(previous_declaration->type == NULL) {
3720 previous_declaration->type = declaration->type;
3721 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3722 previous_declaration->storage_class = declaration->storage_class;
3723 previous_declaration->parent_scope = scope;
3724 return previous_declaration;
3726 return record_declaration(declaration);
3730 static void parse_declaration(parsed_declaration_func finished_declaration)
3732 declaration_specifiers_t specifiers;
3733 memset(&specifiers, 0, sizeof(specifiers));
3734 parse_declaration_specifiers(&specifiers);
3736 if(token.type == ';') {
3737 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3739 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3740 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3744 static void parse_kr_declaration_list(declaration_t *declaration)
3746 type_t *type = skip_typeref(declaration->type);
3747 if(!is_type_function(type))
3750 if(!type->function.kr_style_parameters)
3753 /* push function parameters */
3754 int top = environment_top();
3755 scope_t *last_scope = scope;
3756 set_scope(&declaration->scope);
3758 declaration_t *parameter = declaration->scope.declarations;
3759 for( ; parameter != NULL; parameter = parameter->next) {
3760 assert(parameter->parent_scope == NULL);
3761 parameter->parent_scope = scope;
3762 environment_push(parameter);
3765 /* parse declaration list */
3766 while(is_declaration_specifier(&token, false)) {
3767 parse_declaration(finished_kr_declaration);
3770 /* pop function parameters */
3771 assert(scope == &declaration->scope);
3772 set_scope(last_scope);
3773 environment_pop_to(top);
3775 /* update function type */
3776 type_t *new_type = duplicate_type(type);
3777 new_type->function.kr_style_parameters = false;
3779 function_parameter_t *parameters = NULL;
3780 function_parameter_t *last_parameter = NULL;
3782 declaration_t *parameter_declaration = declaration->scope.declarations;
3783 for( ; parameter_declaration != NULL;
3784 parameter_declaration = parameter_declaration->next) {
3785 type_t *parameter_type = parameter_declaration->type;
3786 if(parameter_type == NULL) {
3788 errorf(HERE, "no type specified for function parameter '%Y'",
3789 parameter_declaration->symbol);
3791 if (warning.implicit_int) {
3792 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3793 parameter_declaration->symbol);
3795 parameter_type = type_int;
3796 parameter_declaration->type = parameter_type;
3800 semantic_parameter(parameter_declaration);
3801 parameter_type = parameter_declaration->type;
3803 function_parameter_t *function_parameter
3804 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3805 memset(function_parameter, 0, sizeof(function_parameter[0]));
3807 function_parameter->type = parameter_type;
3808 if(last_parameter != NULL) {
3809 last_parameter->next = function_parameter;
3811 parameters = function_parameter;
3813 last_parameter = function_parameter;
3815 new_type->function.parameters = parameters;
3817 type = typehash_insert(new_type);
3818 if(type != new_type) {
3819 obstack_free(type_obst, new_type);
3822 declaration->type = type;
3825 static bool first_err = true;
3828 * When called with first_err set, prints the name of the current function,
3831 static void print_in_function(void) {
3834 diagnosticf("%s: In function '%Y':\n",
3835 current_function->source_position.input_name,
3836 current_function->symbol);
3841 * Check if all labels are defined in the current function.
3842 * Check if all labels are used in the current function.
3844 static void check_labels(void)
3846 for (const goto_statement_t *goto_statement = goto_first;
3847 goto_statement != NULL;
3848 goto_statement = goto_statement->next) {
3849 declaration_t *label = goto_statement->label;
3852 if (label->source_position.input_name == NULL) {
3853 print_in_function();
3854 errorf(goto_statement->base.source_position,
3855 "label '%Y' used but not defined", label->symbol);
3858 goto_first = goto_last = NULL;
3860 if (warning.unused_label) {
3861 for (const label_statement_t *label_statement = label_first;
3862 label_statement != NULL;
3863 label_statement = label_statement->next) {
3864 const declaration_t *label = label_statement->label;
3866 if (! label->used) {
3867 print_in_function();
3868 warningf(label_statement->base.source_position,
3869 "label '%Y' defined but not used", label->symbol);
3873 label_first = label_last = NULL;
3877 * Check declarations of current_function for unused entities.
3879 static void check_declarations(void)
3881 if (warning.unused_parameter) {
3882 const scope_t *scope = ¤t_function->scope;
3884 const declaration_t *parameter = scope->declarations;
3885 for (; parameter != NULL; parameter = parameter->next) {
3886 if (! parameter->used) {
3887 print_in_function();
3888 warningf(parameter->source_position,
3889 "unused parameter '%Y'", parameter->symbol);
3893 if (warning.unused_variable) {
3897 static void parse_external_declaration(void)
3899 /* function-definitions and declarations both start with declaration
3901 declaration_specifiers_t specifiers;
3902 memset(&specifiers, 0, sizeof(specifiers));
3904 add_anchor_token(';');
3905 parse_declaration_specifiers(&specifiers);
3906 rem_anchor_token(';');
3908 /* must be a declaration */
3909 if(token.type == ';') {
3910 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3914 add_anchor_token(',');
3915 add_anchor_token('=');
3916 rem_anchor_token(';');
3918 /* declarator is common to both function-definitions and declarations */
3919 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3921 rem_anchor_token(',');
3922 rem_anchor_token('=');
3923 rem_anchor_token(';');
3925 /* must be a declaration */
3926 if(token.type == ',' || token.type == '=' || token.type == ';') {
3927 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3931 /* must be a function definition */
3932 parse_kr_declaration_list(ndeclaration);
3934 if(token.type != '{') {
3935 parse_error_expected("while parsing function definition", '{', 0);
3936 eat_until_matching_token(';');
3940 type_t *type = ndeclaration->type;
3942 /* note that we don't skip typerefs: the standard doesn't allow them here
3943 * (so we can't use is_type_function here) */
3944 if(type->kind != TYPE_FUNCTION) {
3945 if (is_type_valid(type)) {
3946 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3947 type, ndeclaration->symbol);
3953 /* § 6.7.5.3 (14) a function definition with () means no
3954 * parameters (and not unspecified parameters) */
3955 if(type->function.unspecified_parameters) {
3956 type_t *duplicate = duplicate_type(type);
3957 duplicate->function.unspecified_parameters = false;
3959 type = typehash_insert(duplicate);
3960 if(type != duplicate) {
3961 obstack_free(type_obst, duplicate);
3963 ndeclaration->type = type;
3966 declaration_t *const declaration = record_function_definition(ndeclaration);
3967 if(ndeclaration != declaration) {
3968 declaration->scope = ndeclaration->scope;
3970 type = skip_typeref(declaration->type);
3972 /* push function parameters and switch scope */
3973 int top = environment_top();
3974 scope_t *last_scope = scope;
3975 set_scope(&declaration->scope);
3977 declaration_t *parameter = declaration->scope.declarations;
3978 for( ; parameter != NULL; parameter = parameter->next) {
3979 if(parameter->parent_scope == &ndeclaration->scope) {
3980 parameter->parent_scope = scope;
3982 assert(parameter->parent_scope == NULL
3983 || parameter->parent_scope == scope);
3984 parameter->parent_scope = scope;
3985 environment_push(parameter);
3988 if(declaration->init.statement != NULL) {
3989 parser_error_multiple_definition(declaration, token.source_position);
3991 goto end_of_parse_external_declaration;
3993 /* parse function body */
3994 int label_stack_top = label_top();
3995 declaration_t *old_current_function = current_function;
3996 current_function = declaration;
3998 declaration->init.statement = parse_compound_statement();
4001 check_declarations();
4003 assert(current_function == declaration);
4004 current_function = old_current_function;
4005 label_pop_to(label_stack_top);
4008 end_of_parse_external_declaration:
4009 assert(scope == &declaration->scope);
4010 set_scope(last_scope);
4011 environment_pop_to(top);
4014 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4015 source_position_t source_position)
4017 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4018 type->bitfield.base = base;
4019 type->bitfield.size = size;
4024 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4027 declaration_t *iter = compound_declaration->scope.declarations;
4028 for( ; iter != NULL; iter = iter->next) {
4029 if(iter->namespc != NAMESPACE_NORMAL)
4032 if(iter->symbol == NULL) {
4033 type_t *type = skip_typeref(iter->type);
4034 if(is_type_compound(type)) {
4035 declaration_t *result
4036 = find_compound_entry(type->compound.declaration, symbol);
4043 if(iter->symbol == symbol) {
4051 static void parse_compound_declarators(declaration_t *struct_declaration,
4052 const declaration_specifiers_t *specifiers)
4054 declaration_t *last_declaration = struct_declaration->scope.declarations;
4055 if(last_declaration != NULL) {
4056 while(last_declaration->next != NULL) {
4057 last_declaration = last_declaration->next;
4062 declaration_t *declaration;
4064 if(token.type == ':') {
4065 source_position_t source_position = HERE;
4068 type_t *base_type = specifiers->type;
4069 expression_t *size = parse_constant_expression();
4071 if(!is_type_integer(skip_typeref(base_type))) {
4072 errorf(HERE, "bitfield base type '%T' is not an integer type",
4076 type_t *type = make_bitfield_type(base_type, size, source_position);
4078 declaration = allocate_declaration_zero();
4079 declaration->namespc = NAMESPACE_NORMAL;
4080 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4081 declaration->storage_class = STORAGE_CLASS_NONE;
4082 declaration->source_position = source_position;
4083 declaration->modifiers = specifiers->decl_modifiers;
4084 declaration->type = type;
4086 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4088 type_t *orig_type = declaration->type;
4089 type_t *type = skip_typeref(orig_type);
4091 if(token.type == ':') {
4092 source_position_t source_position = HERE;
4094 expression_t *size = parse_constant_expression();
4096 if(!is_type_integer(type)) {
4097 errorf(HERE, "bitfield base type '%T' is not an "
4098 "integer type", orig_type);
4101 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
4102 declaration->type = bitfield_type;
4104 /* TODO we ignore arrays for now... what is missing is a check
4105 * that they're at the end of the struct */
4106 if(is_type_incomplete(type) && !is_type_array(type)) {
4108 "compound member '%Y' has incomplete type '%T'",
4109 declaration->symbol, orig_type);
4110 } else if(is_type_function(type)) {
4111 errorf(HERE, "compound member '%Y' must not have function "
4112 "type '%T'", declaration->symbol, orig_type);
4117 /* make sure we don't define a symbol multiple times */
4118 symbol_t *symbol = declaration->symbol;
4119 if(symbol != NULL) {
4120 declaration_t *prev_decl
4121 = find_compound_entry(struct_declaration, symbol);
4123 if(prev_decl != NULL) {
4124 assert(prev_decl->symbol == symbol);
4125 errorf(declaration->source_position,
4126 "multiple declarations of symbol '%Y'", symbol);
4127 errorf(prev_decl->source_position,
4128 "previous declaration of '%Y' was here", symbol);
4132 /* append declaration */
4133 if(last_declaration != NULL) {
4134 last_declaration->next = declaration;
4136 struct_declaration->scope.declarations = declaration;
4138 last_declaration = declaration;
4140 if(token.type != ',')
4150 static void parse_compound_type_entries(declaration_t *compound_declaration)
4153 add_anchor_token('}');
4155 while(token.type != '}' && token.type != T_EOF) {
4156 declaration_specifiers_t specifiers;
4157 memset(&specifiers, 0, sizeof(specifiers));
4158 parse_declaration_specifiers(&specifiers);
4160 parse_compound_declarators(compound_declaration, &specifiers);
4162 rem_anchor_token('}');
4164 if(token.type == T_EOF) {
4165 errorf(HERE, "EOF while parsing struct");
4170 static type_t *parse_typename(void)
4172 declaration_specifiers_t specifiers;
4173 memset(&specifiers, 0, sizeof(specifiers));
4174 parse_declaration_specifiers(&specifiers);
4175 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4176 /* TODO: improve error message, user does probably not know what a
4177 * storage class is...
4179 errorf(HERE, "typename may not have a storage class");
4182 type_t *result = parse_abstract_declarator(specifiers.type);
4190 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4191 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4192 expression_t *left);
4194 typedef struct expression_parser_function_t expression_parser_function_t;
4195 struct expression_parser_function_t {
4196 unsigned precedence;
4197 parse_expression_function parser;
4198 unsigned infix_precedence;
4199 parse_expression_infix_function infix_parser;
4202 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4205 * Prints an error message if an expression was expected but not read
4207 static expression_t *expected_expression_error(void)
4209 /* skip the error message if the error token was read */
4210 if (token.type != T_ERROR) {
4211 errorf(HERE, "expected expression, got token '%K'", &token);
4215 return create_invalid_expression();
4219 * Parse a string constant.
4221 static expression_t *parse_string_const(void)
4224 if (token.type == T_STRING_LITERAL) {
4225 string_t res = token.v.string;
4227 while (token.type == T_STRING_LITERAL) {
4228 res = concat_strings(&res, &token.v.string);
4231 if (token.type != T_WIDE_STRING_LITERAL) {
4232 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4233 /* note: that we use type_char_ptr here, which is already the
4234 * automatic converted type. revert_automatic_type_conversion
4235 * will construct the array type */
4236 cnst->base.type = type_char_ptr;
4237 cnst->string.value = res;
4241 wres = concat_string_wide_string(&res, &token.v.wide_string);
4243 wres = token.v.wide_string;
4248 switch (token.type) {
4249 case T_WIDE_STRING_LITERAL:
4250 wres = concat_wide_strings(&wres, &token.v.wide_string);
4253 case T_STRING_LITERAL:
4254 wres = concat_wide_string_string(&wres, &token.v.string);
4258 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4259 cnst->base.type = type_wchar_t_ptr;
4260 cnst->wide_string.value = wres;
4269 * Parse an integer constant.
4271 static expression_t *parse_int_const(void)
4273 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4274 cnst->base.source_position = HERE;
4275 cnst->base.type = token.datatype;
4276 cnst->conste.v.int_value = token.v.intvalue;
4284 * Parse a character constant.
4286 static expression_t *parse_character_constant(void)
4288 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4290 cnst->base.source_position = HERE;
4291 cnst->base.type = token.datatype;
4292 cnst->conste.v.character = token.v.string;
4294 if (cnst->conste.v.character.size != 1) {
4295 if (warning.multichar && (c_mode & _GNUC)) {
4297 warningf(HERE, "multi-character character constant");
4299 errorf(HERE, "more than 1 characters in character constant");
4308 * Parse a wide character constant.
4310 static expression_t *parse_wide_character_constant(void)
4312 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4314 cnst->base.source_position = HERE;
4315 cnst->base.type = token.datatype;
4316 cnst->conste.v.wide_character = token.v.wide_string;
4318 if (cnst->conste.v.wide_character.size != 1) {
4319 if (warning.multichar && (c_mode & _GNUC)) {
4321 warningf(HERE, "multi-character character constant");
4323 errorf(HERE, "more than 1 characters in character constant");
4332 * Parse a float constant.
4334 static expression_t *parse_float_const(void)
4336 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4337 cnst->base.type = token.datatype;
4338 cnst->conste.v.float_value = token.v.floatvalue;
4345 static declaration_t *create_implicit_function(symbol_t *symbol,
4346 const source_position_t source_position)
4348 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4349 ntype->function.return_type = type_int;
4350 ntype->function.unspecified_parameters = true;
4352 type_t *type = typehash_insert(ntype);
4357 declaration_t *const declaration = allocate_declaration_zero();
4358 declaration->storage_class = STORAGE_CLASS_EXTERN;
4359 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4360 declaration->type = type;
4361 declaration->symbol = symbol;
4362 declaration->source_position = source_position;
4363 declaration->parent_scope = global_scope;
4365 scope_t *old_scope = scope;
4366 set_scope(global_scope);
4368 environment_push(declaration);
4369 /* prepends the declaration to the global declarations list */
4370 declaration->next = scope->declarations;
4371 scope->declarations = declaration;
4373 assert(scope == global_scope);
4374 set_scope(old_scope);
4380 * Creates a return_type (func)(argument_type) function type if not
4383 * @param return_type the return type
4384 * @param argument_type the argument type
4386 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4388 function_parameter_t *parameter
4389 = obstack_alloc(type_obst, sizeof(parameter[0]));
4390 memset(parameter, 0, sizeof(parameter[0]));
4391 parameter->type = argument_type;
4393 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4394 type->function.return_type = return_type;
4395 type->function.parameters = parameter;
4397 type_t *result = typehash_insert(type);
4398 if(result != type) {
4406 * Creates a function type for some function like builtins.
4408 * @param symbol the symbol describing the builtin
4410 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4412 switch(symbol->ID) {
4413 case T___builtin_alloca:
4414 return make_function_1_type(type_void_ptr, type_size_t);
4415 case T___builtin_nan:
4416 return make_function_1_type(type_double, type_char_ptr);
4417 case T___builtin_nanf:
4418 return make_function_1_type(type_float, type_char_ptr);
4419 case T___builtin_nand:
4420 return make_function_1_type(type_long_double, type_char_ptr);
4421 case T___builtin_va_end:
4422 return make_function_1_type(type_void, type_valist);
4424 internal_errorf(HERE, "not implemented builtin symbol found");
4429 * Performs automatic type cast as described in § 6.3.2.1.
4431 * @param orig_type the original type
4433 static type_t *automatic_type_conversion(type_t *orig_type)
4435 type_t *type = skip_typeref(orig_type);
4436 if(is_type_array(type)) {
4437 array_type_t *array_type = &type->array;
4438 type_t *element_type = array_type->element_type;
4439 unsigned qualifiers = array_type->type.qualifiers;
4441 return make_pointer_type(element_type, qualifiers);
4444 if(is_type_function(type)) {
4445 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4452 * reverts the automatic casts of array to pointer types and function
4453 * to function-pointer types as defined § 6.3.2.1
4455 type_t *revert_automatic_type_conversion(const expression_t *expression)
4457 switch (expression->kind) {
4458 case EXPR_REFERENCE: return expression->reference.declaration->type;
4459 case EXPR_SELECT: return expression->select.compound_entry->type;
4461 case EXPR_UNARY_DEREFERENCE: {
4462 const expression_t *const value = expression->unary.value;
4463 type_t *const type = skip_typeref(value->base.type);
4464 assert(is_type_pointer(type));
4465 return type->pointer.points_to;
4468 case EXPR_BUILTIN_SYMBOL:
4469 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4471 case EXPR_ARRAY_ACCESS: {
4472 const expression_t *array_ref = expression->array_access.array_ref;
4473 type_t *type_left = skip_typeref(array_ref->base.type);
4474 if (!is_type_valid(type_left))
4476 assert(is_type_pointer(type_left));
4477 return type_left->pointer.points_to;
4480 case EXPR_STRING_LITERAL: {
4481 size_t size = expression->string.value.size;
4482 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4485 case EXPR_WIDE_STRING_LITERAL: {
4486 size_t size = expression->wide_string.value.size;
4487 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4490 case EXPR_COMPOUND_LITERAL:
4491 return expression->compound_literal.type;
4496 return expression->base.type;
4499 static expression_t *parse_reference(void)
4501 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4503 reference_expression_t *ref = &expression->reference;
4504 ref->symbol = token.v.symbol;
4506 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4508 source_position_t source_position = token.source_position;
4511 if(declaration == NULL) {
4512 if (! strict_mode && token.type == '(') {
4513 /* an implicitly defined function */
4514 if (warning.implicit_function_declaration) {
4515 warningf(HERE, "implicit declaration of function '%Y'",
4519 declaration = create_implicit_function(ref->symbol,
4522 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4523 return create_invalid_expression();
4527 type_t *type = declaration->type;
4529 /* we always do the auto-type conversions; the & and sizeof parser contains
4530 * code to revert this! */
4531 type = automatic_type_conversion(type);
4533 ref->declaration = declaration;
4534 ref->base.type = type;
4536 /* this declaration is used */
4537 declaration->used = true;
4539 /* check for deprecated functions */
4540 if(declaration->deprecated != 0) {
4541 const char *prefix = "";
4542 if (is_type_function(declaration->type))
4543 prefix = "function ";
4545 if (declaration->deprecated_string != NULL) {
4546 warningf(source_position,
4547 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4548 declaration->deprecated_string);
4550 warningf(source_position,
4551 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4558 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4562 /* TODO check if explicit cast is allowed and issue warnings/errors */
4565 static expression_t *parse_compound_literal(type_t *type)
4567 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4569 parse_initializer_env_t env;
4571 env.declaration = NULL;
4572 env.must_be_constant = false;
4573 initializer_t *initializer = parse_initializer(&env);
4576 expression->compound_literal.initializer = initializer;
4577 expression->compound_literal.type = type;
4578 expression->base.type = automatic_type_conversion(type);
4584 * Parse a cast expression.
4586 static expression_t *parse_cast(void)
4588 source_position_t source_position = token.source_position;
4590 type_t *type = parse_typename();
4592 /* matching add_anchor_token() is at call site */
4593 rem_anchor_token(')');
4596 if(token.type == '{') {
4597 return parse_compound_literal(type);
4600 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4601 cast->base.source_position = source_position;
4603 expression_t *value = parse_sub_expression(20);
4605 check_cast_allowed(value, type);
4607 cast->base.type = type;
4608 cast->unary.value = value;
4612 return create_invalid_expression();
4616 * Parse a statement expression.
4618 static expression_t *parse_statement_expression(void)
4620 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4622 statement_t *statement = parse_compound_statement();
4623 expression->statement.statement = statement;
4624 expression->base.source_position = statement->base.source_position;
4626 /* find last statement and use its type */
4627 type_t *type = type_void;
4628 const statement_t *stmt = statement->compound.statements;
4630 while (stmt->base.next != NULL)
4631 stmt = stmt->base.next;
4633 if (stmt->kind == STATEMENT_EXPRESSION) {
4634 type = stmt->expression.expression->base.type;
4637 warningf(expression->base.source_position, "empty statement expression ({})");
4639 expression->base.type = type;
4645 return create_invalid_expression();
4649 * Parse a braced expression.
4651 static expression_t *parse_brace_expression(void)
4654 add_anchor_token(')');
4656 switch(token.type) {
4658 /* gcc extension: a statement expression */
4659 return parse_statement_expression();
4663 return parse_cast();
4665 if(is_typedef_symbol(token.v.symbol)) {
4666 return parse_cast();
4670 expression_t *result = parse_expression();
4671 rem_anchor_token(')');
4676 return create_invalid_expression();
4679 static expression_t *parse_function_keyword(void)
4684 if (current_function == NULL) {
4685 errorf(HERE, "'__func__' used outside of a function");
4688 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4689 expression->base.type = type_char_ptr;
4690 expression->funcname.kind = FUNCNAME_FUNCTION;
4695 static expression_t *parse_pretty_function_keyword(void)
4697 eat(T___PRETTY_FUNCTION__);
4699 if (current_function == NULL) {
4700 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4703 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4704 expression->base.type = type_char_ptr;
4705 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
4710 static expression_t *parse_funcsig_keyword(void)
4714 if (current_function == NULL) {
4715 errorf(HERE, "'__FUNCSIG__' used outside of a function");
4718 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4719 expression->base.type = type_char_ptr;
4720 expression->funcname.kind = FUNCNAME_FUNCSIG;
4725 static expression_t *parse_funcdname_keyword(void)
4727 eat(T___FUNCDNAME__);
4729 if (current_function == NULL) {
4730 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
4733 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4734 expression->base.type = type_char_ptr;
4735 expression->funcname.kind = FUNCNAME_FUNCDNAME;
4740 static designator_t *parse_designator(void)
4742 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4743 result->source_position = HERE;
4745 if(token.type != T_IDENTIFIER) {
4746 parse_error_expected("while parsing member designator",
4750 result->symbol = token.v.symbol;
4753 designator_t *last_designator = result;
4755 if(token.type == '.') {
4757 if(token.type != T_IDENTIFIER) {
4758 parse_error_expected("while parsing member designator",
4762 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4763 designator->source_position = HERE;
4764 designator->symbol = token.v.symbol;
4767 last_designator->next = designator;
4768 last_designator = designator;
4771 if(token.type == '[') {
4773 add_anchor_token(']');
4774 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4775 designator->source_position = HERE;
4776 designator->array_index = parse_expression();
4777 rem_anchor_token(']');
4779 if(designator->array_index == NULL) {
4783 last_designator->next = designator;
4784 last_designator = designator;
4796 * Parse the __builtin_offsetof() expression.
4798 static expression_t *parse_offsetof(void)
4800 eat(T___builtin_offsetof);
4802 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4803 expression->base.type = type_size_t;
4806 add_anchor_token(',');
4807 type_t *type = parse_typename();
4808 rem_anchor_token(',');
4810 add_anchor_token(')');
4811 designator_t *designator = parse_designator();
4812 rem_anchor_token(')');
4815 expression->offsetofe.type = type;
4816 expression->offsetofe.designator = designator;
4819 memset(&path, 0, sizeof(path));
4820 path.top_type = type;
4821 path.path = NEW_ARR_F(type_path_entry_t, 0);
4823 descend_into_subtype(&path);
4825 if(!walk_designator(&path, designator, true)) {
4826 return create_invalid_expression();
4829 DEL_ARR_F(path.path);
4833 return create_invalid_expression();
4837 * Parses a _builtin_va_start() expression.
4839 static expression_t *parse_va_start(void)
4841 eat(T___builtin_va_start);
4843 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4846 add_anchor_token(',');
4847 expression->va_starte.ap = parse_assignment_expression();
4848 rem_anchor_token(',');
4850 expression_t *const expr = parse_assignment_expression();
4851 if (expr->kind == EXPR_REFERENCE) {
4852 declaration_t *const decl = expr->reference.declaration;
4854 return create_invalid_expression();
4855 if (decl->parent_scope == ¤t_function->scope &&
4856 decl->next == NULL) {
4857 expression->va_starte.parameter = decl;
4862 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4864 return create_invalid_expression();
4868 * Parses a _builtin_va_arg() expression.
4870 static expression_t *parse_va_arg(void)
4872 eat(T___builtin_va_arg);
4874 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4877 expression->va_arge.ap = parse_assignment_expression();
4879 expression->base.type = parse_typename();
4884 return create_invalid_expression();
4887 static expression_t *parse_builtin_symbol(void)
4889 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4891 symbol_t *symbol = token.v.symbol;
4893 expression->builtin_symbol.symbol = symbol;
4896 type_t *type = get_builtin_symbol_type(symbol);
4897 type = automatic_type_conversion(type);
4899 expression->base.type = type;
4904 * Parses a __builtin_constant() expression.
4906 static expression_t *parse_builtin_constant(void)
4908 eat(T___builtin_constant_p);
4910 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4913 add_anchor_token(')');
4914 expression->builtin_constant.value = parse_assignment_expression();
4915 rem_anchor_token(')');
4917 expression->base.type = type_int;
4921 return create_invalid_expression();
4925 * Parses a __builtin_prefetch() expression.
4927 static expression_t *parse_builtin_prefetch(void)
4929 eat(T___builtin_prefetch);
4931 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4934 add_anchor_token(')');
4935 expression->builtin_prefetch.adr = parse_assignment_expression();
4936 if (token.type == ',') {
4938 expression->builtin_prefetch.rw = parse_assignment_expression();
4940 if (token.type == ',') {
4942 expression->builtin_prefetch.locality = parse_assignment_expression();
4944 rem_anchor_token(')');
4946 expression->base.type = type_void;
4950 return create_invalid_expression();
4954 * Parses a __builtin_is_*() compare expression.
4956 static expression_t *parse_compare_builtin(void)
4958 expression_t *expression;
4960 switch(token.type) {
4961 case T___builtin_isgreater:
4962 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4964 case T___builtin_isgreaterequal:
4965 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4967 case T___builtin_isless:
4968 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4970 case T___builtin_islessequal:
4971 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4973 case T___builtin_islessgreater:
4974 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4976 case T___builtin_isunordered:
4977 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4980 internal_errorf(HERE, "invalid compare builtin found");
4983 expression->base.source_position = HERE;
4987 expression->binary.left = parse_assignment_expression();
4989 expression->binary.right = parse_assignment_expression();
4992 type_t *const orig_type_left = expression->binary.left->base.type;
4993 type_t *const orig_type_right = expression->binary.right->base.type;
4995 type_t *const type_left = skip_typeref(orig_type_left);
4996 type_t *const type_right = skip_typeref(orig_type_right);
4997 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4998 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4999 type_error_incompatible("invalid operands in comparison",
5000 expression->base.source_position, orig_type_left, orig_type_right);
5003 semantic_comparison(&expression->binary);
5008 return create_invalid_expression();
5012 * Parses a __builtin_expect() expression.
5014 static expression_t *parse_builtin_expect(void)
5016 eat(T___builtin_expect);
5018 expression_t *expression
5019 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5022 expression->binary.left = parse_assignment_expression();
5024 expression->binary.right = parse_constant_expression();
5027 expression->base.type = expression->binary.left->base.type;
5031 return create_invalid_expression();
5035 * Parses a MS assume() expression.
5037 static expression_t *parse_assume(void) {
5040 expression_t *expression
5041 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5044 add_anchor_token(')');
5045 expression->unary.value = parse_assignment_expression();
5046 rem_anchor_token(')');
5049 expression->base.type = type_void;
5052 return create_invalid_expression();
5056 * Parse a microsoft __noop expression.
5058 static expression_t *parse_noop_expression(void) {
5059 source_position_t source_position = HERE;
5062 if (token.type == '(') {
5063 /* parse arguments */
5065 add_anchor_token(')');
5066 add_anchor_token(',');
5068 if(token.type != ')') {
5070 (void)parse_assignment_expression();
5071 if(token.type != ',')
5077 rem_anchor_token(',');
5078 rem_anchor_token(')');
5081 /* the result is a (int)0 */
5082 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5083 cnst->base.source_position = source_position;
5084 cnst->base.type = type_int;
5085 cnst->conste.v.int_value = 0;
5086 cnst->conste.is_ms_noop = true;
5091 return create_invalid_expression();
5095 * Parses a primary expression.
5097 static expression_t *parse_primary_expression(void)
5099 switch (token.type) {
5100 case T_INTEGER: return parse_int_const();
5101 case T_CHARACTER_CONSTANT: return parse_character_constant();
5102 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5103 case T_FLOATINGPOINT: return parse_float_const();
5104 case T_STRING_LITERAL:
5105 case T_WIDE_STRING_LITERAL: return parse_string_const();
5106 case T_IDENTIFIER: return parse_reference();
5107 case T___FUNCTION__:
5108 case T___func__: return parse_function_keyword();
5109 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5110 case T___FUNCSIG__: return parse_funcsig_keyword();
5111 case T___FUNCDNAME__: return parse_funcdname_keyword();
5112 case T___builtin_offsetof: return parse_offsetof();
5113 case T___builtin_va_start: return parse_va_start();
5114 case T___builtin_va_arg: return parse_va_arg();
5115 case T___builtin_expect: return parse_builtin_expect();
5116 case T___builtin_alloca:
5117 case T___builtin_nan:
5118 case T___builtin_nand:
5119 case T___builtin_nanf:
5120 case T___builtin_va_end: return parse_builtin_symbol();
5121 case T___builtin_isgreater:
5122 case T___builtin_isgreaterequal:
5123 case T___builtin_isless:
5124 case T___builtin_islessequal:
5125 case T___builtin_islessgreater:
5126 case T___builtin_isunordered: return parse_compare_builtin();
5127 case T___builtin_constant_p: return parse_builtin_constant();
5128 case T___builtin_prefetch: return parse_builtin_prefetch();
5129 case T__assume: return parse_assume();
5131 case '(': return parse_brace_expression();
5132 case T___noop: return parse_noop_expression();
5135 errorf(HERE, "unexpected token %K, expected an expression", &token);
5136 return create_invalid_expression();
5140 * Check if the expression has the character type and issue a warning then.
5142 static void check_for_char_index_type(const expression_t *expression) {
5143 type_t *const type = expression->base.type;
5144 const type_t *const base_type = skip_typeref(type);
5146 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5147 warning.char_subscripts) {
5148 warningf(expression->base.source_position,
5149 "array subscript has type '%T'", type);
5153 static expression_t *parse_array_expression(unsigned precedence,
5159 add_anchor_token(']');
5161 expression_t *inside = parse_expression();
5163 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5165 array_access_expression_t *array_access = &expression->array_access;
5167 type_t *const orig_type_left = left->base.type;
5168 type_t *const orig_type_inside = inside->base.type;
5170 type_t *const type_left = skip_typeref(orig_type_left);
5171 type_t *const type_inside = skip_typeref(orig_type_inside);
5173 type_t *return_type;
5174 if (is_type_pointer(type_left)) {
5175 return_type = type_left->pointer.points_to;
5176 array_access->array_ref = left;
5177 array_access->index = inside;
5178 check_for_char_index_type(inside);
5179 } else if (is_type_pointer(type_inside)) {
5180 return_type = type_inside->pointer.points_to;
5181 array_access->array_ref = inside;
5182 array_access->index = left;
5183 array_access->flipped = true;
5184 check_for_char_index_type(left);
5186 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5188 "array access on object with non-pointer types '%T', '%T'",
5189 orig_type_left, orig_type_inside);
5191 return_type = type_error_type;
5192 array_access->array_ref = create_invalid_expression();
5195 rem_anchor_token(']');
5196 if(token.type != ']') {
5197 parse_error_expected("Problem while parsing array access", ']', 0);
5202 return_type = automatic_type_conversion(return_type);
5203 expression->base.type = return_type;
5208 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5210 expression_t *tp_expression = allocate_expression_zero(kind);
5211 tp_expression->base.type = type_size_t;
5213 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5215 add_anchor_token(')');
5216 tp_expression->typeprop.type = parse_typename();
5217 rem_anchor_token(')');
5220 expression_t *expression = parse_sub_expression(precedence);
5221 expression->base.type = revert_automatic_type_conversion(expression);
5223 tp_expression->typeprop.type = expression->base.type;
5224 tp_expression->typeprop.tp_expression = expression;
5227 return tp_expression;
5229 return create_invalid_expression();
5232 static expression_t *parse_sizeof(unsigned precedence)
5235 return parse_typeprop(EXPR_SIZEOF, precedence);
5238 static expression_t *parse_alignof(unsigned precedence)
5241 return parse_typeprop(EXPR_SIZEOF, precedence);
5244 static expression_t *parse_select_expression(unsigned precedence,
5245 expression_t *compound)
5248 assert(token.type == '.' || token.type == T_MINUSGREATER);
5250 bool is_pointer = (token.type == T_MINUSGREATER);
5253 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5254 select->select.compound = compound;
5256 if(token.type != T_IDENTIFIER) {
5257 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5260 symbol_t *symbol = token.v.symbol;
5261 select->select.symbol = symbol;
5264 type_t *const orig_type = compound->base.type;
5265 type_t *const type = skip_typeref(orig_type);
5267 type_t *type_left = type;
5269 if (!is_type_pointer(type)) {
5270 if (is_type_valid(type)) {
5271 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5273 return create_invalid_expression();
5275 type_left = type->pointer.points_to;
5277 type_left = skip_typeref(type_left);
5279 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5280 type_left->kind != TYPE_COMPOUND_UNION) {
5281 if (is_type_valid(type_left)) {
5282 errorf(HERE, "request for member '%Y' in something not a struct or "
5283 "union, but '%T'", symbol, type_left);
5285 return create_invalid_expression();
5288 declaration_t *const declaration = type_left->compound.declaration;
5290 if(!declaration->init.is_defined) {
5291 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5293 return create_invalid_expression();
5296 declaration_t *iter = find_compound_entry(declaration, symbol);
5298 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5299 return create_invalid_expression();
5302 /* we always do the auto-type conversions; the & and sizeof parser contains
5303 * code to revert this! */
5304 type_t *expression_type = automatic_type_conversion(iter->type);
5306 select->select.compound_entry = iter;
5307 select->base.type = expression_type;
5309 if(expression_type->kind == TYPE_BITFIELD) {
5310 expression_t *extract
5311 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5312 extract->unary.value = select;
5313 extract->base.type = expression_type->bitfield.base;
5322 * Parse a call expression, ie. expression '( ... )'.
5324 * @param expression the function address
5326 static expression_t *parse_call_expression(unsigned precedence,
5327 expression_t *expression)
5330 expression_t *result = allocate_expression_zero(EXPR_CALL);
5331 result->base.source_position = expression->base.source_position;
5333 call_expression_t *call = &result->call;
5334 call->function = expression;
5336 type_t *const orig_type = expression->base.type;
5337 type_t *const type = skip_typeref(orig_type);
5339 function_type_t *function_type = NULL;
5340 if (is_type_pointer(type)) {
5341 type_t *const to_type = skip_typeref(type->pointer.points_to);
5343 if (is_type_function(to_type)) {
5344 function_type = &to_type->function;
5345 call->base.type = function_type->return_type;
5349 if (function_type == NULL && is_type_valid(type)) {
5350 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5353 /* parse arguments */
5355 add_anchor_token(')');
5356 add_anchor_token(',');
5358 if(token.type != ')') {
5359 call_argument_t *last_argument = NULL;
5362 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5364 argument->expression = parse_assignment_expression();
5365 if(last_argument == NULL) {
5366 call->arguments = argument;
5368 last_argument->next = argument;
5370 last_argument = argument;
5372 if(token.type != ',')
5377 rem_anchor_token(',');
5378 rem_anchor_token(')');
5381 if(function_type != NULL) {
5382 function_parameter_t *parameter = function_type->parameters;
5383 call_argument_t *argument = call->arguments;
5384 for( ; parameter != NULL && argument != NULL;
5385 parameter = parameter->next, argument = argument->next) {
5386 type_t *expected_type = parameter->type;
5387 /* TODO report scope in error messages */
5388 expression_t *const arg_expr = argument->expression;
5389 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call", arg_expr->base.source_position);
5390 if (res_type == NULL) {
5391 /* TODO improve error message */
5392 errorf(arg_expr->base.source_position,
5393 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5394 arg_expr, arg_expr->base.type, expected_type);
5396 argument->expression = create_implicit_cast(argument->expression, expected_type);
5399 /* too few parameters */
5400 if(parameter != NULL) {
5401 errorf(HERE, "too few arguments to function '%E'", expression);
5402 } else if(argument != NULL) {
5403 /* too many parameters */
5404 if(!function_type->variadic
5405 && !function_type->unspecified_parameters) {
5406 errorf(HERE, "too many arguments to function '%E'", expression);
5408 /* do default promotion */
5409 for( ; argument != NULL; argument = argument->next) {
5410 type_t *type = argument->expression->base.type;
5412 type = skip_typeref(type);
5413 if(is_type_integer(type)) {
5414 type = promote_integer(type);
5415 } else if(type == type_float) {
5419 argument->expression
5420 = create_implicit_cast(argument->expression, type);
5423 check_format(&result->call);
5426 check_format(&result->call);
5432 return create_invalid_expression();
5435 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5437 static bool same_compound_type(const type_t *type1, const type_t *type2)
5440 is_type_compound(type1) &&
5441 type1->kind == type2->kind &&
5442 type1->compound.declaration == type2->compound.declaration;
5446 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5448 * @param expression the conditional expression
5450 static expression_t *parse_conditional_expression(unsigned precedence,
5451 expression_t *expression)
5454 add_anchor_token(':');
5456 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5458 conditional_expression_t *conditional = &result->conditional;
5459 conditional->condition = expression;
5462 type_t *const condition_type_orig = expression->base.type;
5463 type_t *const condition_type = skip_typeref(condition_type_orig);
5464 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5465 type_error("expected a scalar type in conditional condition",
5466 expression->base.source_position, condition_type_orig);
5469 expression_t *true_expression = parse_expression();
5470 rem_anchor_token(':');
5472 expression_t *false_expression = parse_sub_expression(precedence);
5474 type_t *const orig_true_type = true_expression->base.type;
5475 type_t *const orig_false_type = false_expression->base.type;
5476 type_t *const true_type = skip_typeref(orig_true_type);
5477 type_t *const false_type = skip_typeref(orig_false_type);
5480 type_t *result_type;
5481 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5482 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5483 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5484 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5485 warningf(expression->base.source_position,
5486 "ISO C forbids conditional expression with only one void side");
5488 result_type = type_void;
5489 } else if (is_type_arithmetic(true_type)
5490 && is_type_arithmetic(false_type)) {
5491 result_type = semantic_arithmetic(true_type, false_type);
5493 true_expression = create_implicit_cast(true_expression, result_type);
5494 false_expression = create_implicit_cast(false_expression, result_type);
5496 conditional->true_expression = true_expression;
5497 conditional->false_expression = false_expression;
5498 conditional->base.type = result_type;
5499 } else if (same_compound_type(true_type, false_type)) {
5500 /* just take 1 of the 2 types */
5501 result_type = true_type;
5502 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5503 type_t *pointer_type;
5505 expression_t *other_expression;
5506 if (is_type_pointer(true_type)) {
5507 pointer_type = true_type;
5508 other_type = false_type;
5509 other_expression = false_expression;
5511 pointer_type = false_type;
5512 other_type = true_type;
5513 other_expression = true_expression;
5516 if(is_type_pointer(other_type)) {
5517 if(!pointers_compatible(true_type, false_type)) {
5518 warningf(expression->base.source_position,
5519 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5521 result_type = true_type;
5522 } else if(is_null_pointer_constant(other_expression)) {
5523 result_type = pointer_type;
5524 } else if(is_type_integer(other_type)) {
5525 warningf(expression->base.source_position,
5526 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5527 result_type = pointer_type;
5529 type_error_incompatible("while parsing conditional",
5530 expression->base.source_position, true_type, false_type);
5531 result_type = type_error_type;
5534 /* TODO: one pointer to void*, other some pointer */
5536 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5537 type_error_incompatible("while parsing conditional",
5538 expression->base.source_position, true_type,
5541 result_type = type_error_type;
5544 conditional->true_expression
5545 = create_implicit_cast(true_expression, result_type);
5546 conditional->false_expression
5547 = create_implicit_cast(false_expression, result_type);
5548 conditional->base.type = result_type;
5551 return create_invalid_expression();
5555 * Parse an extension expression.
5557 static expression_t *parse_extension(unsigned precedence)
5559 eat(T___extension__);
5561 /* TODO enable extensions */
5562 expression_t *expression = parse_sub_expression(precedence);
5563 /* TODO disable extensions */
5568 * Parse a __builtin_classify_type() expression.
5570 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5572 eat(T___builtin_classify_type);
5574 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5575 result->base.type = type_int;
5578 add_anchor_token(')');
5579 expression_t *expression = parse_sub_expression(precedence);
5580 rem_anchor_token(')');
5582 result->classify_type.type_expression = expression;
5586 return create_invalid_expression();
5589 static void semantic_incdec(unary_expression_t *expression)
5591 type_t *const orig_type = expression->value->base.type;
5592 type_t *const type = skip_typeref(orig_type);
5593 /* TODO !is_type_real && !is_type_pointer */
5594 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5595 if (is_type_valid(type)) {
5596 /* TODO: improve error message */
5597 errorf(HERE, "operation needs an arithmetic or pointer type");
5602 expression->base.type = orig_type;
5605 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5607 type_t *const orig_type = expression->value->base.type;
5608 type_t *const type = skip_typeref(orig_type);
5609 if(!is_type_arithmetic(type)) {
5610 if (is_type_valid(type)) {
5611 /* TODO: improve error message */
5612 errorf(HERE, "operation needs an arithmetic type");
5617 expression->base.type = orig_type;
5620 static void semantic_unexpr_scalar(unary_expression_t *expression)
5622 type_t *const orig_type = expression->value->base.type;
5623 type_t *const type = skip_typeref(orig_type);
5624 if (!is_type_scalar(type)) {
5625 if (is_type_valid(type)) {
5626 errorf(HERE, "operand of ! must be of scalar type");
5631 expression->base.type = orig_type;
5634 static void semantic_unexpr_integer(unary_expression_t *expression)
5636 type_t *const orig_type = expression->value->base.type;
5637 type_t *const type = skip_typeref(orig_type);
5638 if (!is_type_integer(type)) {
5639 if (is_type_valid(type)) {
5640 errorf(HERE, "operand of ~ must be of integer type");
5645 expression->base.type = orig_type;
5648 static void semantic_dereference(unary_expression_t *expression)
5650 type_t *const orig_type = expression->value->base.type;
5651 type_t *const type = skip_typeref(orig_type);
5652 if(!is_type_pointer(type)) {
5653 if (is_type_valid(type)) {
5654 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5659 type_t *result_type = type->pointer.points_to;
5660 result_type = automatic_type_conversion(result_type);
5661 expression->base.type = result_type;
5665 * Check the semantic of the address taken expression.
5667 static void semantic_take_addr(unary_expression_t *expression)
5669 expression_t *value = expression->value;
5670 value->base.type = revert_automatic_type_conversion(value);
5672 type_t *orig_type = value->base.type;
5673 if(!is_type_valid(orig_type))
5676 if(value->kind == EXPR_REFERENCE) {
5677 declaration_t *const declaration = value->reference.declaration;
5678 if(declaration != NULL) {
5679 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5680 errorf(expression->base.source_position,
5681 "address of register variable '%Y' requested",
5682 declaration->symbol);
5684 declaration->address_taken = 1;
5688 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5691 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5692 static expression_t *parse_##unexpression_type(unsigned precedence) \
5696 expression_t *unary_expression \
5697 = allocate_expression_zero(unexpression_type); \
5698 unary_expression->base.source_position = HERE; \
5699 unary_expression->unary.value = parse_sub_expression(precedence); \
5701 sfunc(&unary_expression->unary); \
5703 return unary_expression; \
5706 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5707 semantic_unexpr_arithmetic)
5708 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5709 semantic_unexpr_arithmetic)
5710 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5711 semantic_unexpr_scalar)
5712 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5713 semantic_dereference)
5714 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5716 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5717 semantic_unexpr_integer)
5718 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5720 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5723 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5725 static expression_t *parse_##unexpression_type(unsigned precedence, \
5726 expression_t *left) \
5728 (void) precedence; \
5731 expression_t *unary_expression \
5732 = allocate_expression_zero(unexpression_type); \
5733 unary_expression->unary.value = left; \
5735 sfunc(&unary_expression->unary); \
5737 return unary_expression; \
5740 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5741 EXPR_UNARY_POSTFIX_INCREMENT,
5743 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5744 EXPR_UNARY_POSTFIX_DECREMENT,
5747 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5749 /* TODO: handle complex + imaginary types */
5751 /* § 6.3.1.8 Usual arithmetic conversions */
5752 if(type_left == type_long_double || type_right == type_long_double) {
5753 return type_long_double;
5754 } else if(type_left == type_double || type_right == type_double) {
5756 } else if(type_left == type_float || type_right == type_float) {
5760 type_right = promote_integer(type_right);
5761 type_left = promote_integer(type_left);
5763 if(type_left == type_right)
5766 bool signed_left = is_type_signed(type_left);
5767 bool signed_right = is_type_signed(type_right);
5768 int rank_left = get_rank(type_left);
5769 int rank_right = get_rank(type_right);
5770 if(rank_left < rank_right) {
5771 if(signed_left == signed_right || !signed_right) {
5777 if(signed_left == signed_right || !signed_left) {
5786 * Check the semantic restrictions for a binary expression.
5788 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5790 expression_t *const left = expression->left;
5791 expression_t *const right = expression->right;
5792 type_t *const orig_type_left = left->base.type;
5793 type_t *const orig_type_right = right->base.type;
5794 type_t *const type_left = skip_typeref(orig_type_left);
5795 type_t *const type_right = skip_typeref(orig_type_right);
5797 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5798 /* TODO: improve error message */
5799 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5800 errorf(HERE, "operation needs arithmetic types");
5805 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5806 expression->left = create_implicit_cast(left, arithmetic_type);
5807 expression->right = create_implicit_cast(right, arithmetic_type);
5808 expression->base.type = arithmetic_type;
5811 static void semantic_shift_op(binary_expression_t *expression)
5813 expression_t *const left = expression->left;
5814 expression_t *const right = expression->right;
5815 type_t *const orig_type_left = left->base.type;
5816 type_t *const orig_type_right = right->base.type;
5817 type_t * type_left = skip_typeref(orig_type_left);
5818 type_t * type_right = skip_typeref(orig_type_right);
5820 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5821 /* TODO: improve error message */
5822 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5823 errorf(HERE, "operation needs integer types");
5828 type_left = promote_integer(type_left);
5829 type_right = promote_integer(type_right);
5831 expression->left = create_implicit_cast(left, type_left);
5832 expression->right = create_implicit_cast(right, type_right);
5833 expression->base.type = type_left;
5836 static void semantic_add(binary_expression_t *expression)
5838 expression_t *const left = expression->left;
5839 expression_t *const right = expression->right;
5840 type_t *const orig_type_left = left->base.type;
5841 type_t *const orig_type_right = right->base.type;
5842 type_t *const type_left = skip_typeref(orig_type_left);
5843 type_t *const type_right = skip_typeref(orig_type_right);
5846 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5847 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5848 expression->left = create_implicit_cast(left, arithmetic_type);
5849 expression->right = create_implicit_cast(right, arithmetic_type);
5850 expression->base.type = arithmetic_type;
5852 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5853 expression->base.type = type_left;
5854 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5855 expression->base.type = type_right;
5856 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5857 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5861 static void semantic_sub(binary_expression_t *expression)
5863 expression_t *const left = expression->left;
5864 expression_t *const right = expression->right;
5865 type_t *const orig_type_left = left->base.type;
5866 type_t *const orig_type_right = right->base.type;
5867 type_t *const type_left = skip_typeref(orig_type_left);
5868 type_t *const type_right = skip_typeref(orig_type_right);
5871 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5872 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5873 expression->left = create_implicit_cast(left, arithmetic_type);
5874 expression->right = create_implicit_cast(right, arithmetic_type);
5875 expression->base.type = arithmetic_type;
5877 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5878 expression->base.type = type_left;
5879 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5880 if(!pointers_compatible(type_left, type_right)) {
5882 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5883 orig_type_left, orig_type_right);
5885 expression->base.type = type_ptrdiff_t;
5887 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5888 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5889 orig_type_left, orig_type_right);
5894 * Check the semantics of comparison expressions.
5896 * @param expression The expression to check.
5898 static void semantic_comparison(binary_expression_t *expression)
5900 expression_t *left = expression->left;
5901 expression_t *right = expression->right;
5902 type_t *orig_type_left = left->base.type;
5903 type_t *orig_type_right = right->base.type;
5905 type_t *type_left = skip_typeref(orig_type_left);
5906 type_t *type_right = skip_typeref(orig_type_right);
5908 /* TODO non-arithmetic types */
5909 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5910 if (warning.sign_compare &&
5911 (expression->base.kind != EXPR_BINARY_EQUAL &&
5912 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5913 (is_type_signed(type_left) != is_type_signed(type_right))) {
5914 warningf(expression->base.source_position,
5915 "comparison between signed and unsigned");
5917 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5918 expression->left = create_implicit_cast(left, arithmetic_type);
5919 expression->right = create_implicit_cast(right, arithmetic_type);
5920 expression->base.type = arithmetic_type;
5921 if (warning.float_equal &&
5922 (expression->base.kind == EXPR_BINARY_EQUAL ||
5923 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5924 is_type_float(arithmetic_type)) {
5925 warningf(expression->base.source_position,
5926 "comparing floating point with == or != is unsafe");
5928 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5929 /* TODO check compatibility */
5930 } else if (is_type_pointer(type_left)) {
5931 expression->right = create_implicit_cast(right, type_left);
5932 } else if (is_type_pointer(type_right)) {
5933 expression->left = create_implicit_cast(left, type_right);
5934 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5935 type_error_incompatible("invalid operands in comparison",
5936 expression->base.source_position,
5937 type_left, type_right);
5939 expression->base.type = type_int;
5942 static void semantic_arithmetic_assign(binary_expression_t *expression)
5944 expression_t *left = expression->left;
5945 expression_t *right = expression->right;
5946 type_t *orig_type_left = left->base.type;
5947 type_t *orig_type_right = right->base.type;
5949 type_t *type_left = skip_typeref(orig_type_left);
5950 type_t *type_right = skip_typeref(orig_type_right);
5952 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5953 /* TODO: improve error message */
5954 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5955 errorf(HERE, "operation needs arithmetic types");
5960 /* combined instructions are tricky. We can't create an implicit cast on
5961 * the left side, because we need the uncasted form for the store.
5962 * The ast2firm pass has to know that left_type must be right_type
5963 * for the arithmetic operation and create a cast by itself */
5964 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5965 expression->right = create_implicit_cast(right, arithmetic_type);
5966 expression->base.type = type_left;
5969 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5971 expression_t *const left = expression->left;
5972 expression_t *const right = expression->right;
5973 type_t *const orig_type_left = left->base.type;
5974 type_t *const orig_type_right = right->base.type;
5975 type_t *const type_left = skip_typeref(orig_type_left);
5976 type_t *const type_right = skip_typeref(orig_type_right);
5978 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5979 /* combined instructions are tricky. We can't create an implicit cast on
5980 * the left side, because we need the uncasted form for the store.
5981 * The ast2firm pass has to know that left_type must be right_type
5982 * for the arithmetic operation and create a cast by itself */
5983 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5984 expression->right = create_implicit_cast(right, arithmetic_type);
5985 expression->base.type = type_left;
5986 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5987 expression->base.type = type_left;
5988 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5989 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5994 * Check the semantic restrictions of a logical expression.
5996 static void semantic_logical_op(binary_expression_t *expression)
5998 expression_t *const left = expression->left;
5999 expression_t *const right = expression->right;
6000 type_t *const orig_type_left = left->base.type;
6001 type_t *const orig_type_right = right->base.type;
6002 type_t *const type_left = skip_typeref(orig_type_left);
6003 type_t *const type_right = skip_typeref(orig_type_right);
6005 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6006 /* TODO: improve error message */
6007 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6008 errorf(HERE, "operation needs scalar types");
6013 expression->base.type = type_int;
6017 * Checks if a compound type has constant fields.
6019 static bool has_const_fields(const compound_type_t *type)
6021 const scope_t *scope = &type->declaration->scope;
6022 const declaration_t *declaration = scope->declarations;
6024 for (; declaration != NULL; declaration = declaration->next) {
6025 if (declaration->namespc != NAMESPACE_NORMAL)
6028 const type_t *decl_type = skip_typeref(declaration->type);
6029 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6037 * Check the semantic restrictions of a binary assign expression.
6039 static void semantic_binexpr_assign(binary_expression_t *expression)
6041 expression_t *left = expression->left;
6042 type_t *orig_type_left = left->base.type;
6044 type_t *type_left = revert_automatic_type_conversion(left);
6045 type_left = skip_typeref(orig_type_left);
6047 /* must be a modifiable lvalue */
6048 if (is_type_array(type_left)) {
6049 errorf(HERE, "cannot assign to arrays ('%E')", left);
6052 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6053 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6057 if(is_type_incomplete(type_left)) {
6059 "left-hand side of assignment '%E' has incomplete type '%T'",
6060 left, orig_type_left);
6063 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6064 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6065 left, orig_type_left);
6069 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6070 "assignment", left->base.source_position);
6071 if (res_type == NULL) {
6072 errorf(expression->base.source_position,
6073 "cannot assign to '%T' from '%T'",
6074 orig_type_left, expression->right->base.type);
6076 expression->right = create_implicit_cast(expression->right, res_type);
6079 expression->base.type = orig_type_left;
6083 * Determine if the outermost operation (or parts thereof) of the given
6084 * expression has no effect in order to generate a warning about this fact.
6085 * Therefore in some cases this only examines some of the operands of the
6086 * expression (see comments in the function and examples below).
6088 * f() + 23; // warning, because + has no effect
6089 * x || f(); // no warning, because x controls execution of f()
6090 * x ? y : f(); // warning, because y has no effect
6091 * (void)x; // no warning to be able to suppress the warning
6092 * This function can NOT be used for an "expression has definitely no effect"-
6094 static bool expression_has_effect(const expression_t *const expr)
6096 switch (expr->kind) {
6097 case EXPR_UNKNOWN: break;
6098 case EXPR_INVALID: return true; /* do NOT warn */
6099 case EXPR_REFERENCE: return false;
6100 /* suppress the warning for microsoft __noop operations */
6101 case EXPR_CONST: return expr->conste.is_ms_noop;
6102 case EXPR_CHARACTER_CONSTANT: return false;
6103 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6104 case EXPR_STRING_LITERAL: return false;
6105 case EXPR_WIDE_STRING_LITERAL: return false;
6108 const call_expression_t *const call = &expr->call;
6109 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6112 switch (call->function->builtin_symbol.symbol->ID) {
6113 case T___builtin_va_end: return true;
6114 default: return false;
6118 /* Generate the warning if either the left or right hand side of a
6119 * conditional expression has no effect */
6120 case EXPR_CONDITIONAL: {
6121 const conditional_expression_t *const cond = &expr->conditional;
6123 expression_has_effect(cond->true_expression) &&
6124 expression_has_effect(cond->false_expression);
6127 case EXPR_SELECT: return false;
6128 case EXPR_ARRAY_ACCESS: return false;
6129 case EXPR_SIZEOF: return false;
6130 case EXPR_CLASSIFY_TYPE: return false;
6131 case EXPR_ALIGNOF: return false;
6133 case EXPR_FUNCNAME: return false;
6134 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6135 case EXPR_BUILTIN_CONSTANT_P: return false;
6136 case EXPR_BUILTIN_PREFETCH: return true;
6137 case EXPR_OFFSETOF: return false;
6138 case EXPR_VA_START: return true;
6139 case EXPR_VA_ARG: return true;
6140 case EXPR_STATEMENT: return true; // TODO
6141 case EXPR_COMPOUND_LITERAL: return false;
6143 case EXPR_UNARY_NEGATE: return false;
6144 case EXPR_UNARY_PLUS: return false;
6145 case EXPR_UNARY_BITWISE_NEGATE: return false;
6146 case EXPR_UNARY_NOT: return false;
6147 case EXPR_UNARY_DEREFERENCE: return false;
6148 case EXPR_UNARY_TAKE_ADDRESS: return false;
6149 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6150 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6151 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6152 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6154 /* Treat void casts as if they have an effect in order to being able to
6155 * suppress the warning */
6156 case EXPR_UNARY_CAST: {
6157 type_t *const type = skip_typeref(expr->base.type);
6158 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6161 case EXPR_UNARY_CAST_IMPLICIT: return true;
6162 case EXPR_UNARY_ASSUME: return true;
6163 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6165 case EXPR_BINARY_ADD: return false;
6166 case EXPR_BINARY_SUB: return false;
6167 case EXPR_BINARY_MUL: return false;
6168 case EXPR_BINARY_DIV: return false;
6169 case EXPR_BINARY_MOD: return false;
6170 case EXPR_BINARY_EQUAL: return false;
6171 case EXPR_BINARY_NOTEQUAL: return false;
6172 case EXPR_BINARY_LESS: return false;
6173 case EXPR_BINARY_LESSEQUAL: return false;
6174 case EXPR_BINARY_GREATER: return false;
6175 case EXPR_BINARY_GREATEREQUAL: return false;
6176 case EXPR_BINARY_BITWISE_AND: return false;
6177 case EXPR_BINARY_BITWISE_OR: return false;
6178 case EXPR_BINARY_BITWISE_XOR: return false;
6179 case EXPR_BINARY_SHIFTLEFT: return false;
6180 case EXPR_BINARY_SHIFTRIGHT: return false;
6181 case EXPR_BINARY_ASSIGN: return true;
6182 case EXPR_BINARY_MUL_ASSIGN: return true;
6183 case EXPR_BINARY_DIV_ASSIGN: return true;
6184 case EXPR_BINARY_MOD_ASSIGN: return true;
6185 case EXPR_BINARY_ADD_ASSIGN: return true;
6186 case EXPR_BINARY_SUB_ASSIGN: return true;
6187 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6188 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6189 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6190 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6191 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6193 /* Only examine the right hand side of && and ||, because the left hand
6194 * side already has the effect of controlling the execution of the right
6196 case EXPR_BINARY_LOGICAL_AND:
6197 case EXPR_BINARY_LOGICAL_OR:
6198 /* Only examine the right hand side of a comma expression, because the left
6199 * hand side has a separate warning */
6200 case EXPR_BINARY_COMMA:
6201 return expression_has_effect(expr->binary.right);
6203 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6204 case EXPR_BINARY_ISGREATER: return false;
6205 case EXPR_BINARY_ISGREATEREQUAL: return false;
6206 case EXPR_BINARY_ISLESS: return false;
6207 case EXPR_BINARY_ISLESSEQUAL: return false;
6208 case EXPR_BINARY_ISLESSGREATER: return false;
6209 case EXPR_BINARY_ISUNORDERED: return false;
6212 internal_errorf(HERE, "unexpected expression");
6215 static void semantic_comma(binary_expression_t *expression)
6217 if (warning.unused_value) {
6218 const expression_t *const left = expression->left;
6219 if (!expression_has_effect(left)) {
6220 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6223 expression->base.type = expression->right->base.type;
6226 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6227 static expression_t *parse_##binexpression_type(unsigned precedence, \
6228 expression_t *left) \
6231 source_position_t pos = HERE; \
6233 expression_t *right = parse_sub_expression(precedence + lr); \
6235 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6236 binexpr->base.source_position = pos; \
6237 binexpr->binary.left = left; \
6238 binexpr->binary.right = right; \
6239 sfunc(&binexpr->binary); \
6244 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6245 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6246 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6247 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6248 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6249 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6250 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6251 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6252 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6254 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6255 semantic_comparison, 1)
6256 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6257 semantic_comparison, 1)
6258 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6259 semantic_comparison, 1)
6260 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6261 semantic_comparison, 1)
6263 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6264 semantic_binexpr_arithmetic, 1)
6265 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6266 semantic_binexpr_arithmetic, 1)
6267 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6268 semantic_binexpr_arithmetic, 1)
6269 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6270 semantic_logical_op, 1)
6271 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6272 semantic_logical_op, 1)
6273 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6274 semantic_shift_op, 1)
6275 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6276 semantic_shift_op, 1)
6277 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6278 semantic_arithmetic_addsubb_assign, 0)
6279 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6280 semantic_arithmetic_addsubb_assign, 0)
6281 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6282 semantic_arithmetic_assign, 0)
6283 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6284 semantic_arithmetic_assign, 0)
6285 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6286 semantic_arithmetic_assign, 0)
6287 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6288 semantic_arithmetic_assign, 0)
6289 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6290 semantic_arithmetic_assign, 0)
6291 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6292 semantic_arithmetic_assign, 0)
6293 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6294 semantic_arithmetic_assign, 0)
6295 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6296 semantic_arithmetic_assign, 0)
6298 static expression_t *parse_sub_expression(unsigned precedence)
6300 if(token.type < 0) {
6301 return expected_expression_error();
6304 expression_parser_function_t *parser
6305 = &expression_parsers[token.type];
6306 source_position_t source_position = token.source_position;
6309 if(parser->parser != NULL) {
6310 left = parser->parser(parser->precedence);
6312 left = parse_primary_expression();
6314 assert(left != NULL);
6315 left->base.source_position = source_position;
6318 if(token.type < 0) {
6319 return expected_expression_error();
6322 parser = &expression_parsers[token.type];
6323 if(parser->infix_parser == NULL)
6325 if(parser->infix_precedence < precedence)
6328 left = parser->infix_parser(parser->infix_precedence, left);
6330 assert(left != NULL);
6331 assert(left->kind != EXPR_UNKNOWN);
6332 left->base.source_position = source_position;
6339 * Parse an expression.
6341 static expression_t *parse_expression(void)
6343 return parse_sub_expression(1);
6347 * Register a parser for a prefix-like operator with given precedence.
6349 * @param parser the parser function
6350 * @param token_type the token type of the prefix token
6351 * @param precedence the precedence of the operator
6353 static void register_expression_parser(parse_expression_function parser,
6354 int token_type, unsigned precedence)
6356 expression_parser_function_t *entry = &expression_parsers[token_type];
6358 if(entry->parser != NULL) {
6359 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6360 panic("trying to register multiple expression parsers for a token");
6362 entry->parser = parser;
6363 entry->precedence = precedence;
6367 * Register a parser for an infix operator with given precedence.
6369 * @param parser the parser function
6370 * @param token_type the token type of the infix operator
6371 * @param precedence the precedence of the operator
6373 static void register_infix_parser(parse_expression_infix_function parser,
6374 int token_type, unsigned precedence)
6376 expression_parser_function_t *entry = &expression_parsers[token_type];
6378 if(entry->infix_parser != NULL) {
6379 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6380 panic("trying to register multiple infix expression parsers for a "
6383 entry->infix_parser = parser;
6384 entry->infix_precedence = precedence;
6388 * Initialize the expression parsers.
6390 static void init_expression_parsers(void)
6392 memset(&expression_parsers, 0, sizeof(expression_parsers));
6394 register_infix_parser(parse_array_expression, '[', 30);
6395 register_infix_parser(parse_call_expression, '(', 30);
6396 register_infix_parser(parse_select_expression, '.', 30);
6397 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6398 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6400 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6403 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6404 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6405 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6406 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6407 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6408 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6409 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6410 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6411 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6412 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6413 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6414 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6415 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6416 T_EXCLAMATIONMARKEQUAL, 13);
6417 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6418 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6419 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6420 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6421 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6422 register_infix_parser(parse_conditional_expression, '?', 7);
6423 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6424 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6425 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6426 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6427 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6428 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6429 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6430 T_LESSLESSEQUAL, 2);
6431 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6432 T_GREATERGREATEREQUAL, 2);
6433 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6435 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6437 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6440 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6442 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6443 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6444 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6445 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6446 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6447 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6448 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6450 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6452 register_expression_parser(parse_sizeof, T_sizeof, 25);
6453 register_expression_parser(parse_alignof, T___alignof__, 25);
6454 register_expression_parser(parse_extension, T___extension__, 25);
6455 register_expression_parser(parse_builtin_classify_type,
6456 T___builtin_classify_type, 25);
6460 * Parse a asm statement constraints specification.
6462 static asm_constraint_t *parse_asm_constraints(void)
6464 asm_constraint_t *result = NULL;
6465 asm_constraint_t *last = NULL;
6467 while(token.type == T_STRING_LITERAL || token.type == '[') {
6468 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6469 memset(constraint, 0, sizeof(constraint[0]));
6471 if(token.type == '[') {
6473 if(token.type != T_IDENTIFIER) {
6474 parse_error_expected("while parsing asm constraint",
6478 constraint->symbol = token.v.symbol;
6483 constraint->constraints = parse_string_literals();
6485 constraint->expression = parse_expression();
6489 last->next = constraint;
6491 result = constraint;
6495 if(token.type != ',')
6506 * Parse a asm statement clobber specification.
6508 static asm_clobber_t *parse_asm_clobbers(void)
6510 asm_clobber_t *result = NULL;
6511 asm_clobber_t *last = NULL;
6513 while(token.type == T_STRING_LITERAL) {
6514 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6515 clobber->clobber = parse_string_literals();
6518 last->next = clobber;
6524 if(token.type != ',')
6533 * Parse an asm statement.
6535 static statement_t *parse_asm_statement(void)
6539 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6540 statement->base.source_position = token.source_position;
6542 asm_statement_t *asm_statement = &statement->asms;
6544 if(token.type == T_volatile) {
6546 asm_statement->is_volatile = true;
6550 add_anchor_token(')');
6551 add_anchor_token(':');
6552 asm_statement->asm_text = parse_string_literals();
6554 if(token.type != ':') {
6555 rem_anchor_token(':');
6560 asm_statement->inputs = parse_asm_constraints();
6561 if(token.type != ':') {
6562 rem_anchor_token(':');
6567 asm_statement->outputs = parse_asm_constraints();
6568 if(token.type != ':') {
6569 rem_anchor_token(':');
6572 rem_anchor_token(':');
6575 asm_statement->clobbers = parse_asm_clobbers();
6578 rem_anchor_token(')');
6583 return create_invalid_statement();
6587 * Parse a case statement.
6589 static statement_t *parse_case_statement(void)
6593 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6595 statement->base.source_position = token.source_position;
6596 statement->case_label.expression = parse_expression();
6598 if (c_mode & _GNUC) {
6599 if (token.type == T_DOTDOTDOT) {
6601 statement->case_label.end_range = parse_expression();
6607 if (! is_constant_expression(statement->case_label.expression)) {
6608 errorf(statement->base.source_position,
6609 "case label does not reduce to an integer constant");
6611 /* TODO: check if the case label is already known */
6612 if (current_switch != NULL) {
6613 /* link all cases into the switch statement */
6614 if (current_switch->last_case == NULL) {
6615 current_switch->first_case =
6616 current_switch->last_case = &statement->case_label;
6618 current_switch->last_case->next = &statement->case_label;
6621 errorf(statement->base.source_position,
6622 "case label not within a switch statement");
6625 statement->case_label.statement = parse_statement();
6629 return create_invalid_statement();
6633 * Finds an existing default label of a switch statement.
6635 static case_label_statement_t *
6636 find_default_label(const switch_statement_t *statement)
6638 case_label_statement_t *label = statement->first_case;
6639 for ( ; label != NULL; label = label->next) {
6640 if (label->expression == NULL)
6647 * Parse a default statement.
6649 static statement_t *parse_default_statement(void)
6653 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6655 statement->base.source_position = token.source_position;
6658 if (current_switch != NULL) {
6659 const case_label_statement_t *def_label = find_default_label(current_switch);
6660 if (def_label != NULL) {
6661 errorf(HERE, "multiple default labels in one switch");
6662 errorf(def_label->base.source_position,
6663 "this is the first default label");
6665 /* link all cases into the switch statement */
6666 if (current_switch->last_case == NULL) {
6667 current_switch->first_case =
6668 current_switch->last_case = &statement->case_label;
6670 current_switch->last_case->next = &statement->case_label;
6674 errorf(statement->base.source_position,
6675 "'default' label not within a switch statement");
6677 statement->case_label.statement = parse_statement();
6681 return create_invalid_statement();
6685 * Return the declaration for a given label symbol or create a new one.
6687 static declaration_t *get_label(symbol_t *symbol)
6689 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6690 assert(current_function != NULL);
6691 /* if we found a label in the same function, then we already created the
6693 if(candidate != NULL
6694 && candidate->parent_scope == ¤t_function->scope) {
6698 /* otherwise we need to create a new one */
6699 declaration_t *const declaration = allocate_declaration_zero();
6700 declaration->namespc = NAMESPACE_LABEL;
6701 declaration->symbol = symbol;
6703 label_push(declaration);
6709 * Parse a label statement.
6711 static statement_t *parse_label_statement(void)
6713 assert(token.type == T_IDENTIFIER);
6714 symbol_t *symbol = token.v.symbol;
6717 declaration_t *label = get_label(symbol);
6719 /* if source position is already set then the label is defined twice,
6720 * otherwise it was just mentioned in a goto so far */
6721 if(label->source_position.input_name != NULL) {
6722 errorf(HERE, "duplicate label '%Y'", symbol);
6723 errorf(label->source_position, "previous definition of '%Y' was here",
6726 label->source_position = token.source_position;
6729 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6731 statement->base.source_position = token.source_position;
6732 statement->label.label = label;
6736 if(token.type == '}') {
6737 /* TODO only warn? */
6739 warningf(HERE, "label at end of compound statement");
6740 statement->label.statement = create_empty_statement();
6742 errorf(HERE, "label at end of compound statement");
6743 statement->label.statement = create_invalid_statement();
6747 if (token.type == ';') {
6748 /* eat an empty statement here, to avoid the warning about an empty
6749 * after a label. label:; is commonly used to have a label before
6751 statement->label.statement = create_empty_statement();
6754 statement->label.statement = parse_statement();
6758 /* remember the labels's in a list for later checking */
6759 if (label_last == NULL) {
6760 label_first = &statement->label;
6762 label_last->next = &statement->label;
6764 label_last = &statement->label;
6770 * Parse an if statement.
6772 static statement_t *parse_if(void)
6776 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6777 statement->base.source_position = token.source_position;
6780 add_anchor_token(')');
6781 statement->ifs.condition = parse_expression();
6782 rem_anchor_token(')');
6785 add_anchor_token(T_else);
6786 statement->ifs.true_statement = parse_statement();
6787 rem_anchor_token(T_else);
6789 if(token.type == T_else) {
6791 statement->ifs.false_statement = parse_statement();
6796 return create_invalid_statement();
6800 * Parse a switch statement.
6802 static statement_t *parse_switch(void)
6806 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6807 statement->base.source_position = token.source_position;
6810 expression_t *const expr = parse_expression();
6811 type_t * type = skip_typeref(expr->base.type);
6812 if (is_type_integer(type)) {
6813 type = promote_integer(type);
6814 } else if (is_type_valid(type)) {
6815 errorf(expr->base.source_position,
6816 "switch quantity is not an integer, but '%T'", type);
6817 type = type_error_type;
6819 statement->switchs.expression = create_implicit_cast(expr, type);
6822 switch_statement_t *rem = current_switch;
6823 current_switch = &statement->switchs;
6824 statement->switchs.body = parse_statement();
6825 current_switch = rem;
6827 if (warning.switch_default
6828 && find_default_label(&statement->switchs) == NULL) {
6829 warningf(statement->base.source_position, "switch has no default case");
6834 return create_invalid_statement();
6837 static statement_t *parse_loop_body(statement_t *const loop)
6839 statement_t *const rem = current_loop;
6840 current_loop = loop;
6842 statement_t *const body = parse_statement();
6849 * Parse a while statement.
6851 static statement_t *parse_while(void)
6855 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6856 statement->base.source_position = token.source_position;
6859 add_anchor_token(')');
6860 statement->whiles.condition = parse_expression();
6861 rem_anchor_token(')');
6864 statement->whiles.body = parse_loop_body(statement);
6868 return create_invalid_statement();
6872 * Parse a do statement.
6874 static statement_t *parse_do(void)
6878 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6880 statement->base.source_position = token.source_position;
6882 add_anchor_token(T_while);
6883 statement->do_while.body = parse_loop_body(statement);
6884 rem_anchor_token(T_while);
6888 add_anchor_token(')');
6889 statement->do_while.condition = parse_expression();
6890 rem_anchor_token(')');
6896 return create_invalid_statement();
6900 * Parse a for statement.
6902 static statement_t *parse_for(void)
6906 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6907 statement->base.source_position = token.source_position;
6909 int top = environment_top();
6910 scope_t *last_scope = scope;
6911 set_scope(&statement->fors.scope);
6914 add_anchor_token(')');
6916 if(token.type != ';') {
6917 if(is_declaration_specifier(&token, false)) {
6918 parse_declaration(record_declaration);
6920 expression_t *const init = parse_expression();
6921 statement->fors.initialisation = init;
6922 if (warning.unused_value && !expression_has_effect(init)) {
6923 warningf(init->base.source_position,
6924 "initialisation of 'for'-statement has no effect");
6932 if(token.type != ';') {
6933 statement->fors.condition = parse_expression();
6936 if(token.type != ')') {
6937 expression_t *const step = parse_expression();
6938 statement->fors.step = step;
6939 if (warning.unused_value && !expression_has_effect(step)) {
6940 warningf(step->base.source_position,
6941 "step of 'for'-statement has no effect");
6944 rem_anchor_token(')');
6946 statement->fors.body = parse_loop_body(statement);
6948 assert(scope == &statement->fors.scope);
6949 set_scope(last_scope);
6950 environment_pop_to(top);
6955 rem_anchor_token(')');
6956 assert(scope == &statement->fors.scope);
6957 set_scope(last_scope);
6958 environment_pop_to(top);
6960 return create_invalid_statement();
6964 * Parse a goto statement.
6966 static statement_t *parse_goto(void)
6970 if(token.type != T_IDENTIFIER) {
6971 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6975 symbol_t *symbol = token.v.symbol;
6978 declaration_t *label = get_label(symbol);
6980 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6981 statement->base.source_position = token.source_position;
6983 statement->gotos.label = label;
6985 /* remember the goto's in a list for later checking */
6986 if (goto_last == NULL) {
6987 goto_first = &statement->gotos;
6989 goto_last->next = &statement->gotos;
6991 goto_last = &statement->gotos;
6997 return create_invalid_statement();
7001 * Parse a continue statement.
7003 static statement_t *parse_continue(void)
7005 statement_t *statement;
7006 if (current_loop == NULL) {
7007 errorf(HERE, "continue statement not within loop");
7010 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7012 statement->base.source_position = token.source_position;
7020 return create_invalid_statement();
7024 * Parse a break statement.
7026 static statement_t *parse_break(void)
7028 statement_t *statement;
7029 if (current_switch == NULL && current_loop == NULL) {
7030 errorf(HERE, "break statement not within loop or switch");
7033 statement = allocate_statement_zero(STATEMENT_BREAK);
7035 statement->base.source_position = token.source_position;
7043 return create_invalid_statement();
7047 * Check if a given declaration represents a local variable.
7049 static bool is_local_var_declaration(const declaration_t *declaration) {
7050 switch ((storage_class_tag_t) declaration->storage_class) {
7051 case STORAGE_CLASS_AUTO:
7052 case STORAGE_CLASS_REGISTER: {
7053 const type_t *type = skip_typeref(declaration->type);
7054 if(is_type_function(type)) {
7066 * Check if a given declaration represents a variable.
7068 static bool is_var_declaration(const declaration_t *declaration) {
7069 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7072 const type_t *type = skip_typeref(declaration->type);
7073 return !is_type_function(type);
7077 * Check if a given expression represents a local variable.
7079 static bool is_local_variable(const expression_t *expression)
7081 if (expression->base.kind != EXPR_REFERENCE) {
7084 const declaration_t *declaration = expression->reference.declaration;
7085 return is_local_var_declaration(declaration);
7089 * Check if a given expression represents a local variable and
7090 * return its declaration then, else return NULL.
7092 declaration_t *expr_is_variable(const expression_t *expression)
7094 if (expression->base.kind != EXPR_REFERENCE) {
7097 declaration_t *declaration = expression->reference.declaration;
7098 if (is_var_declaration(declaration))
7104 * Parse a return statement.
7106 static statement_t *parse_return(void)
7108 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7109 statement->base.source_position = token.source_position;
7113 expression_t *return_value = NULL;
7114 if(token.type != ';') {
7115 return_value = parse_expression();
7119 const type_t *const func_type = current_function->type;
7120 assert(is_type_function(func_type));
7121 type_t *const return_type = skip_typeref(func_type->function.return_type);
7123 if(return_value != NULL) {
7124 type_t *return_value_type = skip_typeref(return_value->base.type);
7126 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7127 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7128 warningf(statement->base.source_position,
7129 "'return' with a value, in function returning void");
7130 return_value = NULL;
7132 type_t *const res_type = semantic_assign(return_type,
7133 return_value, "'return'", statement->base.source_position);
7134 if (res_type == NULL) {
7135 errorf(statement->base.source_position,
7136 "cannot return something of type '%T' in function returning '%T'",
7137 return_value->base.type, return_type);
7139 return_value = create_implicit_cast(return_value, res_type);
7142 /* check for returning address of a local var */
7143 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7144 const expression_t *expression = return_value->unary.value;
7145 if (is_local_variable(expression)) {
7146 warningf(statement->base.source_position,
7147 "function returns address of local variable");
7151 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7152 warningf(statement->base.source_position,
7153 "'return' without value, in function returning non-void");
7156 statement->returns.value = return_value;
7160 return create_invalid_statement();
7164 * Parse a declaration statement.
7166 static statement_t *parse_declaration_statement(void)
7168 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7170 statement->base.source_position = token.source_position;
7172 declaration_t *before = last_declaration;
7173 parse_declaration(record_declaration);
7175 if(before == NULL) {
7176 statement->declaration.declarations_begin = scope->declarations;
7178 statement->declaration.declarations_begin = before->next;
7180 statement->declaration.declarations_end = last_declaration;
7186 * Parse an expression statement, ie. expr ';'.
7188 static statement_t *parse_expression_statement(void)
7190 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7192 statement->base.source_position = token.source_position;
7193 expression_t *const expr = parse_expression();
7194 statement->expression.expression = expr;
7196 if (warning.unused_value && !expression_has_effect(expr)) {
7197 warningf(expr->base.source_position, "statement has no effect");
7204 return create_invalid_statement();
7208 * Parse a statement.
7210 static statement_t *parse_statement(void)
7212 statement_t *statement = NULL;
7214 /* declaration or statement */
7215 add_anchor_token(';');
7216 switch(token.type) {
7218 statement = parse_asm_statement();
7222 statement = parse_case_statement();
7226 statement = parse_default_statement();
7230 statement = parse_compound_statement();
7234 statement = parse_if();
7238 statement = parse_switch();
7242 statement = parse_while();
7246 statement = parse_do();
7250 statement = parse_for();
7254 statement = parse_goto();
7258 statement = parse_continue();
7262 statement = parse_break();
7266 statement = parse_return();
7270 if(warning.empty_statement) {
7271 warningf(HERE, "statement is empty");
7273 statement = create_empty_statement();
7278 if(look_ahead(1)->type == ':') {
7279 statement = parse_label_statement();
7283 if(is_typedef_symbol(token.v.symbol)) {
7284 statement = parse_declaration_statement();
7288 statement = parse_expression_statement();
7291 case T___extension__:
7292 /* this can be a prefix to a declaration or an expression statement */
7293 /* we simply eat it now and parse the rest with tail recursion */
7296 } while(token.type == T___extension__);
7297 statement = parse_statement();
7301 statement = parse_declaration_statement();
7305 statement = parse_expression_statement();
7308 rem_anchor_token(';');
7310 assert(statement != NULL
7311 && statement->base.source_position.input_name != NULL);
7317 * Parse a compound statement.
7319 static statement_t *parse_compound_statement(void)
7321 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7323 statement->base.source_position = token.source_position;
7326 add_anchor_token('}');
7328 int top = environment_top();
7329 scope_t *last_scope = scope;
7330 set_scope(&statement->compound.scope);
7332 statement_t *last_statement = NULL;
7334 while(token.type != '}' && token.type != T_EOF) {
7335 statement_t *sub_statement = parse_statement();
7336 if(is_invalid_statement(sub_statement)) {
7337 /* an error occurred. if we are at an anchor, return */
7343 if(last_statement != NULL) {
7344 last_statement->base.next = sub_statement;
7346 statement->compound.statements = sub_statement;
7349 while(sub_statement->base.next != NULL)
7350 sub_statement = sub_statement->base.next;
7352 last_statement = sub_statement;
7355 if(token.type == '}') {
7358 errorf(statement->base.source_position,
7359 "end of file while looking for closing '}'");
7363 rem_anchor_token('}');
7364 assert(scope == &statement->compound.scope);
7365 set_scope(last_scope);
7366 environment_pop_to(top);
7372 * Initialize builtin types.
7374 static void initialize_builtin_types(void)
7376 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7377 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7378 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7379 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7380 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7381 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7382 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7383 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7385 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7386 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7387 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7388 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7392 * Check for unused global static functions and variables
7394 static void check_unused_globals(void)
7396 if (!warning.unused_function && !warning.unused_variable)
7399 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7400 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7403 type_t *const type = decl->type;
7405 if (is_type_function(skip_typeref(type))) {
7406 if (!warning.unused_function || decl->is_inline)
7409 s = (decl->init.statement != NULL ? "defined" : "declared");
7411 if (!warning.unused_variable)
7417 warningf(decl->source_position, "'%#T' %s but not used",
7418 type, decl->symbol, s);
7423 * Parse a translation unit.
7425 static translation_unit_t *parse_translation_unit(void)
7427 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7429 assert(global_scope == NULL);
7430 global_scope = &unit->scope;
7432 assert(scope == NULL);
7433 set_scope(&unit->scope);
7435 initialize_builtin_types();
7437 while(token.type != T_EOF) {
7438 if (token.type == ';') {
7439 /* TODO error in strict mode */
7440 warningf(HERE, "stray ';' outside of function");
7443 parse_external_declaration();
7447 assert(scope == &unit->scope);
7449 last_declaration = NULL;
7451 assert(global_scope == &unit->scope);
7452 check_unused_globals();
7453 global_scope = NULL;
7461 * @return the translation unit or NULL if errors occurred.
7463 translation_unit_t *parse(void)
7465 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7466 label_stack = NEW_ARR_F(stack_entry_t, 0);
7467 diagnostic_count = 0;
7471 type_set_output(stderr);
7472 ast_set_output(stderr);
7474 lookahead_bufpos = 0;
7475 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7478 translation_unit_t *unit = parse_translation_unit();
7480 DEL_ARR_F(environment_stack);
7481 DEL_ARR_F(label_stack);
7487 * Initialize the parser.
7489 void init_parser(void)
7492 /* add predefined symbols for extended-decl-modifier */
7493 sym_align = symbol_table_insert("align");
7494 sym_allocate = symbol_table_insert("allocate");
7495 sym_dllimport = symbol_table_insert("dllimport");
7496 sym_dllexport = symbol_table_insert("dllexport");
7497 sym_naked = symbol_table_insert("naked");
7498 sym_noinline = symbol_table_insert("noinline");
7499 sym_noreturn = symbol_table_insert("noreturn");
7500 sym_nothrow = symbol_table_insert("nothrow");
7501 sym_novtable = symbol_table_insert("novtable");
7502 sym_property = symbol_table_insert("property");
7503 sym_get = symbol_table_insert("get");
7504 sym_put = symbol_table_insert("put");
7505 sym_selectany = symbol_table_insert("selectany");
7506 sym_thread = symbol_table_insert("thread");
7507 sym_uuid = symbol_table_insert("uuid");
7508 sym_deprecated = symbol_table_insert("deprecated");
7509 sym_restrict = symbol_table_insert("restrict");
7510 sym_noalias = symbol_table_insert("noalias");
7512 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7514 init_expression_parsers();
7515 obstack_init(&temp_obst);
7517 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7518 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7522 * Terminate the parser.
7524 void exit_parser(void)
7526 obstack_free(&temp_obst, NULL);