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,
841 type_t *const orig_type_right = right->base.type;
842 type_t *const type_left = skip_typeref(orig_type_left);
843 type_t *const type_right = skip_typeref(orig_type_right);
845 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
846 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
847 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
848 && is_type_pointer(type_right))) {
849 return orig_type_left;
852 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
853 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
854 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
856 /* the left type has all qualifiers from the right type */
857 unsigned missing_qualifiers
858 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
859 if(missing_qualifiers != 0) {
860 errorf(HERE, "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(right->base.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;
881 if ((is_type_compound(type_left) && is_type_compound(type_right))
882 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
883 type_t *const unqual_type_left = get_unqualified_type(type_left);
884 type_t *const unqual_type_right = get_unqualified_type(type_right);
885 if (types_compatible(unqual_type_left, unqual_type_right)) {
886 return orig_type_left;
890 if (!is_type_valid(type_left))
893 if (!is_type_valid(type_right))
894 return orig_type_right;
899 static expression_t *parse_constant_expression(void)
901 /* start parsing at precedence 7 (conditional expression) */
902 expression_t *result = parse_sub_expression(7);
904 if(!is_constant_expression(result)) {
905 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
911 static expression_t *parse_assignment_expression(void)
913 /* start parsing at precedence 2 (assignment expression) */
914 return parse_sub_expression(2);
917 static type_t *make_global_typedef(const char *name, type_t *type)
919 symbol_t *const symbol = symbol_table_insert(name);
921 declaration_t *const declaration = allocate_declaration_zero();
922 declaration->namespc = NAMESPACE_NORMAL;
923 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
924 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
925 declaration->type = type;
926 declaration->symbol = symbol;
927 declaration->source_position = builtin_source_position;
929 record_declaration(declaration);
931 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
932 typedef_type->typedeft.declaration = declaration;
937 static string_t parse_string_literals(void)
939 assert(token.type == T_STRING_LITERAL);
940 string_t result = token.v.string;
944 while (token.type == T_STRING_LITERAL) {
945 result = concat_strings(&result, &token.v.string);
952 typedef enum gnu_attribute_kind_t {
963 GNU_AK_ALWAYS_INLINE,
972 } gnu_attribute_kind_t;
974 static const char *gnu_attribute_names[GNU_AK_LAST] = {
975 [GNU_AK_CONST] = "const",
976 [GNU_AK_VOLATILE] = "volatile",
977 [GNU_AK_CDECL] = "cdecl",
978 [GNU_AK_STDCALL] = "stdcall",
979 [GNU_AK_FASTCALL] = "fastcall",
980 [GNU_AK_DEPRECATED] = "deprecated",
981 [GNU_AK_NOINLINE] = "noinline",
982 [GNU_AK_NORETURN] = "noreturn",
983 [GNU_AK_NAKED] = "naked",
984 [GNU_AK_PURE] = "pure",
985 [GNU_AK_ALWAYS_INLINE] = "always_inline",
986 [GNU_AK_MALLOC] = "malloc",
987 [GNU_AK_WEAK] = "weak",
988 [GNU_AK_ALIGNED] = "aligned",
989 [GNU_AK_ALIAS] = "alias",
990 [GNU_AK_SECTION] = "section",
991 [GNU_AK_FORMAT] = "format",
992 [GNU_AK_FORMAT_ARG] = "format_arg"
996 * compare two string, ignoring double underscores on the second.
998 static int strcmp_underscore(const char *s1, const char *s2) {
999 if(s2[0] == '_' && s2[1] == '_') {
1001 size_t l1 = strlen(s1);
1002 if(l1 + 2 != strlen(s2)) {
1006 return strncmp(s1, s2, l1);
1008 return strcmp(s1, s2);
1011 static expression_t *parse_gnu_attribute_const_arg(void) {
1012 expression_t *expression;
1014 add_anchor_token('(');
1015 expression = parse_constant_expression();
1016 rem_anchor_token('(');
1020 return create_invalid_expression();
1023 static string_t parse_gnu_attribute_string_arg(void) {
1024 string_t string = { NULL, 0 };
1026 add_anchor_token('(');
1027 if(token.type != T_STRING_LITERAL) {
1028 parse_error_expected("while parsing attribute directive", T_STRING_LITERAL);
1031 string = parse_string_literals();
1032 rem_anchor_token('(');
1038 static const char *format_names[] = {
1046 * parse ( identifier, const expression, const expression )
1048 static void parse_gnu_attribute_format_args(void) {
1051 if(token.type != T_IDENTIFIER) {
1052 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER);
1055 const char *name = token.v.symbol->string;
1056 for(i = 0; i < 4; ++i) {
1057 if(strcmp_underscore(format_names[i], name) == 0)
1061 if(warning.attribute)
1062 warningf(HERE, "'%s' is an unrecognized format function type", name);
1067 add_anchor_token(')');
1068 add_anchor_token(',');
1069 parse_constant_expression();
1070 rem_anchor_token(',');
1071 rem_anchor_token('(');
1074 add_anchor_token(')');
1075 parse_constant_expression();
1076 rem_anchor_token('(');
1084 * Parse one GNU attribute.
1086 * Note that attribute names can be specified WITH or WITHOUT
1087 * double underscores, ie const or __const__.
1089 * The following attributes are parsed without arguments
1104 * The following attributes are parsed with arguments
1105 * aligned( const expression )
1106 * alias( string literal )
1107 * section( string literal )
1108 * format( identifier, const expression, const expression )
1109 * format_arg( const expression )
1111 static void parse_gnu_attribute(void)
1113 eat(T___attribute__);
1116 if(token.type != ')') {
1117 /* non-empty attribute list */
1120 if(token.type == T_const) {
1122 } else if(token.type == T_volatile) {
1124 } else if(token.type == T_cdecl) {
1125 /* __attribute__((cdecl)), WITH ms mode */
1127 } else if(token.type != T_IDENTIFIER) {
1128 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1131 const symbol_t *sym = token.v.symbol;
1135 gnu_attribute_kind_t kind;
1136 for(kind = 0; kind < GNU_AK_LAST; ++kind) {
1137 if(strcmp_underscore(gnu_attribute_names[kind], name) == 0)
1143 case GNU_AK_VOLATILE:
1147 case GNU_AK_STDCALL:
1149 case GNU_AK_FASTCALL:
1151 case GNU_AK_DEPRECATED:
1153 case GNU_AK_NOINLINE:
1155 case GNU_AK_NORETURN:
1161 case GNU_AK_ALWAYS_INLINE:
1167 case GNU_AK_ALIGNED:
1168 parse_gnu_attribute_const_arg();
1171 parse_gnu_attribute_string_arg();
1173 case GNU_AK_SECTION:
1174 parse_gnu_attribute_string_arg();
1177 parse_gnu_attribute_format_args();
1179 case GNU_AK_FORMAT_ARG:
1180 parse_gnu_attribute_const_arg();
1183 if(warning.attribute)
1184 warningf(HERE, "'%s' attribute directive ignored", name);
1186 /* skip possible arguments */
1187 if(token.type == '(')
1188 eat_until_matching_token('(');
1191 if(token.type != ',')
1203 * Parse GNU attributes.
1205 static void parse_attributes(void)
1208 switch(token.type) {
1209 case T___attribute__: {
1210 parse_gnu_attribute();
1216 if(token.type != T_STRING_LITERAL) {
1217 parse_error_expected("while parsing assembler attribute",
1219 eat_until_matching_token('(');
1222 parse_string_literals();
1227 goto attributes_finished;
1232 attributes_finished:
1236 static designator_t *parse_designation(void)
1238 designator_t *result = NULL;
1239 designator_t *last = NULL;
1242 designator_t *designator;
1243 switch(token.type) {
1245 designator = allocate_ast_zero(sizeof(designator[0]));
1246 designator->source_position = token.source_position;
1248 add_anchor_token(']');
1249 designator->array_index = parse_constant_expression();
1250 rem_anchor_token(']');
1254 designator = allocate_ast_zero(sizeof(designator[0]));
1255 designator->source_position = token.source_position;
1257 if(token.type != T_IDENTIFIER) {
1258 parse_error_expected("while parsing designator",
1262 designator->symbol = token.v.symbol;
1270 assert(designator != NULL);
1272 last->next = designator;
1274 result = designator;
1282 static initializer_t *initializer_from_string(array_type_t *type,
1283 const string_t *const string)
1285 /* TODO: check len vs. size of array type */
1288 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1289 initializer->string.string = *string;
1294 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1295 wide_string_t *const string)
1297 /* TODO: check len vs. size of array type */
1300 initializer_t *const initializer =
1301 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1302 initializer->wide_string.string = *string;
1308 * Build an initializer from a given expression.
1310 static initializer_t *initializer_from_expression(type_t *orig_type,
1311 expression_t *expression)
1313 /* TODO check that expression is a constant expression */
1315 /* § 6.7.8.14/15 char array may be initialized by string literals */
1316 type_t *type = skip_typeref(orig_type);
1317 type_t *expr_type_orig = expression->base.type;
1318 type_t *expr_type = skip_typeref(expr_type_orig);
1319 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1320 array_type_t *const array_type = &type->array;
1321 type_t *const element_type = skip_typeref(array_type->element_type);
1323 if (element_type->kind == TYPE_ATOMIC) {
1324 atomic_type_kind_t akind = element_type->atomic.akind;
1325 switch (expression->kind) {
1326 case EXPR_STRING_LITERAL:
1327 if (akind == ATOMIC_TYPE_CHAR
1328 || akind == ATOMIC_TYPE_SCHAR
1329 || akind == ATOMIC_TYPE_UCHAR) {
1330 return initializer_from_string(array_type,
1331 &expression->string.value);
1334 case EXPR_WIDE_STRING_LITERAL: {
1335 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1336 if (get_unqualified_type(element_type) == bare_wchar_type) {
1337 return initializer_from_wide_string(array_type,
1338 &expression->wide_string.value);
1348 type_t *const res_type = semantic_assign(type, expression, "initializer");
1349 if (res_type == NULL)
1352 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1353 result->value.value = create_implicit_cast(expression, res_type);
1359 * Checks if a given expression can be used as an constant initializer.
1361 static bool is_initializer_constant(const expression_t *expression)
1363 return is_constant_expression(expression)
1364 || is_address_constant(expression);
1368 * Parses an scalar initializer.
1370 * § 6.7.8.11; eat {} without warning
1372 static initializer_t *parse_scalar_initializer(type_t *type,
1373 bool must_be_constant)
1375 /* there might be extra {} hierarchies */
1377 while(token.type == '{') {
1380 warningf(HERE, "extra curly braces around scalar initializer");
1385 expression_t *expression = parse_assignment_expression();
1386 if(must_be_constant && !is_initializer_constant(expression)) {
1387 errorf(expression->base.source_position,
1388 "Initialisation expression '%E' is not constant\n",
1392 initializer_t *initializer = initializer_from_expression(type, expression);
1394 if(initializer == NULL) {
1395 errorf(expression->base.source_position,
1396 "expression '%E' (type '%T') doesn't match expected type '%T'",
1397 expression, expression->base.type, type);
1402 bool additional_warning_displayed = false;
1404 if(token.type == ',') {
1407 if(token.type != '}') {
1408 if(!additional_warning_displayed) {
1409 warningf(HERE, "additional elements in scalar initializer");
1410 additional_warning_displayed = true;
1421 * An entry in the type path.
1423 typedef struct type_path_entry_t type_path_entry_t;
1424 struct type_path_entry_t {
1425 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1427 size_t index; /**< For array types: the current index. */
1428 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1433 * A type path expression a position inside compound or array types.
1435 typedef struct type_path_t type_path_t;
1436 struct type_path_t {
1437 type_path_entry_t *path; /**< An flexible array containing the current path. */
1438 type_t *top_type; /**< type of the element the path points */
1439 size_t max_index; /**< largest index in outermost array */
1443 * Prints a type path for debugging.
1445 static __attribute__((unused)) void debug_print_type_path(
1446 const type_path_t *path)
1448 size_t len = ARR_LEN(path->path);
1450 for(size_t i = 0; i < len; ++i) {
1451 const type_path_entry_t *entry = & path->path[i];
1453 type_t *type = skip_typeref(entry->type);
1454 if(is_type_compound(type)) {
1455 /* in gcc mode structs can have no members */
1456 if(entry->v.compound_entry == NULL) {
1460 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1461 } else if(is_type_array(type)) {
1462 fprintf(stderr, "[%zd]", entry->v.index);
1464 fprintf(stderr, "-INVALID-");
1467 if(path->top_type != NULL) {
1468 fprintf(stderr, " (");
1469 print_type(path->top_type);
1470 fprintf(stderr, ")");
1475 * Return the top type path entry, ie. in a path
1476 * (type).a.b returns the b.
1478 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1480 size_t len = ARR_LEN(path->path);
1482 return &path->path[len-1];
1486 * Enlarge the type path by an (empty) element.
1488 static type_path_entry_t *append_to_type_path(type_path_t *path)
1490 size_t len = ARR_LEN(path->path);
1491 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1493 type_path_entry_t *result = & path->path[len];
1494 memset(result, 0, sizeof(result[0]));
1499 * Descending into a sub-type. Enter the scope of the current
1502 static void descend_into_subtype(type_path_t *path)
1504 type_t *orig_top_type = path->top_type;
1505 type_t *top_type = skip_typeref(orig_top_type);
1507 assert(is_type_compound(top_type) || is_type_array(top_type));
1509 type_path_entry_t *top = append_to_type_path(path);
1510 top->type = top_type;
1512 if(is_type_compound(top_type)) {
1513 declaration_t *declaration = top_type->compound.declaration;
1514 declaration_t *entry = declaration->scope.declarations;
1515 top->v.compound_entry = entry;
1518 path->top_type = entry->type;
1520 path->top_type = NULL;
1523 assert(is_type_array(top_type));
1526 path->top_type = top_type->array.element_type;
1531 * Pop an entry from the given type path, ie. returning from
1532 * (type).a.b to (type).a
1534 static void ascend_from_subtype(type_path_t *path)
1536 type_path_entry_t *top = get_type_path_top(path);
1538 path->top_type = top->type;
1540 size_t len = ARR_LEN(path->path);
1541 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1545 * Pop entries from the given type path until the given
1546 * path level is reached.
1548 static void ascend_to(type_path_t *path, size_t top_path_level)
1550 size_t len = ARR_LEN(path->path);
1552 while(len > top_path_level) {
1553 ascend_from_subtype(path);
1554 len = ARR_LEN(path->path);
1558 static bool walk_designator(type_path_t *path, const designator_t *designator,
1559 bool used_in_offsetof)
1561 for( ; designator != NULL; designator = designator->next) {
1562 type_path_entry_t *top = get_type_path_top(path);
1563 type_t *orig_type = top->type;
1565 type_t *type = skip_typeref(orig_type);
1567 if(designator->symbol != NULL) {
1568 symbol_t *symbol = designator->symbol;
1569 if(!is_type_compound(type)) {
1570 if(is_type_valid(type)) {
1571 errorf(designator->source_position,
1572 "'.%Y' designator used for non-compound type '%T'",
1578 declaration_t *declaration = type->compound.declaration;
1579 declaration_t *iter = declaration->scope.declarations;
1580 for( ; iter != NULL; iter = iter->next) {
1581 if(iter->symbol == symbol) {
1586 errorf(designator->source_position,
1587 "'%T' has no member named '%Y'", orig_type, symbol);
1590 if(used_in_offsetof) {
1591 type_t *real_type = skip_typeref(iter->type);
1592 if(real_type->kind == TYPE_BITFIELD) {
1593 errorf(designator->source_position,
1594 "offsetof designator '%Y' may not specify bitfield",
1600 top->type = orig_type;
1601 top->v.compound_entry = iter;
1602 orig_type = iter->type;
1604 expression_t *array_index = designator->array_index;
1605 assert(designator->array_index != NULL);
1607 if(!is_type_array(type)) {
1608 if(is_type_valid(type)) {
1609 errorf(designator->source_position,
1610 "[%E] designator used for non-array type '%T'",
1611 array_index, orig_type);
1615 if(!is_type_valid(array_index->base.type)) {
1619 long index = fold_constant(array_index);
1620 if(!used_in_offsetof) {
1622 errorf(designator->source_position,
1623 "array index [%E] must be positive", array_index);
1626 if(type->array.size_constant == true) {
1627 long array_size = type->array.size;
1628 if(index >= array_size) {
1629 errorf(designator->source_position,
1630 "designator [%E] (%d) exceeds array size %d",
1631 array_index, index, array_size);
1637 top->type = orig_type;
1638 top->v.index = (size_t) index;
1639 orig_type = type->array.element_type;
1641 path->top_type = orig_type;
1643 if(designator->next != NULL) {
1644 descend_into_subtype(path);
1653 static void advance_current_object(type_path_t *path, size_t top_path_level)
1655 type_path_entry_t *top = get_type_path_top(path);
1657 type_t *type = skip_typeref(top->type);
1658 if(is_type_union(type)) {
1659 /* in unions only the first element is initialized */
1660 top->v.compound_entry = NULL;
1661 } else if(is_type_struct(type)) {
1662 declaration_t *entry = top->v.compound_entry;
1664 entry = entry->next;
1665 top->v.compound_entry = entry;
1667 path->top_type = entry->type;
1671 assert(is_type_array(type));
1675 if(!type->array.size_constant || top->v.index < type->array.size) {
1680 /* we're past the last member of the current sub-aggregate, try if we
1681 * can ascend in the type hierarchy and continue with another subobject */
1682 size_t len = ARR_LEN(path->path);
1684 if(len > top_path_level) {
1685 ascend_from_subtype(path);
1686 advance_current_object(path, top_path_level);
1688 path->top_type = NULL;
1693 * skip until token is found.
1695 static void skip_until(int type) {
1696 while(token.type != type) {
1697 if(token.type == T_EOF)
1704 * skip any {...} blocks until a closing braket is reached.
1706 static void skip_initializers(void)
1708 if(token.type == '{')
1711 while(token.type != '}') {
1712 if(token.type == T_EOF)
1714 if(token.type == '{') {
1722 static initializer_t *create_empty_initializer(void)
1724 static initializer_t empty_initializer
1725 = { .list = { { INITIALIZER_LIST }, 0 } };
1726 return &empty_initializer;
1730 * Parse a part of an initialiser for a struct or union,
1732 static initializer_t *parse_sub_initializer(type_path_t *path,
1733 type_t *outer_type, size_t top_path_level,
1734 parse_initializer_env_t *env)
1736 if(token.type == '}') {
1737 /* empty initializer */
1738 return create_empty_initializer();
1741 type_t *orig_type = path->top_type;
1742 type_t *type = NULL;
1744 if (orig_type == NULL) {
1745 /* We are initializing an empty compound. */
1747 type = skip_typeref(orig_type);
1749 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1750 * initializers in this case. */
1751 if(!is_type_valid(type)) {
1752 skip_initializers();
1753 return create_empty_initializer();
1757 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1760 designator_t *designator = NULL;
1761 if(token.type == '.' || token.type == '[') {
1762 designator = parse_designation();
1764 /* reset path to toplevel, evaluate designator from there */
1765 ascend_to(path, top_path_level);
1766 if(!walk_designator(path, designator, false)) {
1767 /* can't continue after designation error */
1771 initializer_t *designator_initializer
1772 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1773 designator_initializer->designator.designator = designator;
1774 ARR_APP1(initializer_t*, initializers, designator_initializer);
1779 if(token.type == '{') {
1780 if(type != NULL && is_type_scalar(type)) {
1781 sub = parse_scalar_initializer(type, env->must_be_constant);
1785 if (env->declaration != NULL)
1786 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1787 env->declaration->symbol);
1789 errorf(HERE, "extra brace group at end of initializer");
1791 descend_into_subtype(path);
1793 add_anchor_token('}');
1794 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1796 rem_anchor_token('}');
1799 ascend_from_subtype(path);
1803 goto error_parse_next;
1807 /* must be an expression */
1808 expression_t *expression = parse_assignment_expression();
1810 if(env->must_be_constant && !is_initializer_constant(expression)) {
1811 errorf(expression->base.source_position,
1812 "Initialisation expression '%E' is not constant\n",
1817 /* we are already outside, ... */
1821 /* handle { "string" } special case */
1822 if((expression->kind == EXPR_STRING_LITERAL
1823 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1824 && outer_type != NULL) {
1825 sub = initializer_from_expression(outer_type, expression);
1827 if(token.type == ',') {
1830 if(token.type != '}') {
1831 warningf(HERE, "excessive elements in initializer for type '%T'",
1834 /* TODO: eat , ... */
1839 /* descend into subtypes until expression matches type */
1841 orig_type = path->top_type;
1842 type = skip_typeref(orig_type);
1844 sub = initializer_from_expression(orig_type, expression);
1848 if(!is_type_valid(type)) {
1851 if(is_type_scalar(type)) {
1852 errorf(expression->base.source_position,
1853 "expression '%E' doesn't match expected type '%T'",
1854 expression, orig_type);
1858 descend_into_subtype(path);
1862 /* update largest index of top array */
1863 const type_path_entry_t *first = &path->path[0];
1864 type_t *first_type = first->type;
1865 first_type = skip_typeref(first_type);
1866 if(is_type_array(first_type)) {
1867 size_t index = first->v.index;
1868 if(index > path->max_index)
1869 path->max_index = index;
1873 /* append to initializers list */
1874 ARR_APP1(initializer_t*, initializers, sub);
1877 if(env->declaration != NULL)
1878 warningf(HERE, "excess elements in struct initializer for '%Y'",
1879 env->declaration->symbol);
1881 warningf(HERE, "excess elements in struct initializer");
1885 if(token.type == '}') {
1889 if(token.type == '}') {
1894 /* advance to the next declaration if we are not at the end */
1895 advance_current_object(path, top_path_level);
1896 orig_type = path->top_type;
1897 if(orig_type != NULL)
1898 type = skip_typeref(orig_type);
1904 size_t len = ARR_LEN(initializers);
1905 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1906 initializer_t *result = allocate_ast_zero(size);
1907 result->kind = INITIALIZER_LIST;
1908 result->list.len = len;
1909 memcpy(&result->list.initializers, initializers,
1910 len * sizeof(initializers[0]));
1912 DEL_ARR_F(initializers);
1913 ascend_to(path, top_path_level);
1918 skip_initializers();
1919 DEL_ARR_F(initializers);
1920 ascend_to(path, top_path_level);
1925 * Parses an initializer. Parsers either a compound literal
1926 * (env->declaration == NULL) or an initializer of a declaration.
1928 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1930 type_t *type = skip_typeref(env->type);
1931 initializer_t *result = NULL;
1934 if(is_type_scalar(type)) {
1935 result = parse_scalar_initializer(type, env->must_be_constant);
1936 } else if(token.type == '{') {
1940 memset(&path, 0, sizeof(path));
1941 path.top_type = env->type;
1942 path.path = NEW_ARR_F(type_path_entry_t, 0);
1944 descend_into_subtype(&path);
1946 add_anchor_token('}');
1947 result = parse_sub_initializer(&path, env->type, 1, env);
1948 rem_anchor_token('}');
1950 max_index = path.max_index;
1951 DEL_ARR_F(path.path);
1955 /* parse_scalar_initializer() also works in this case: we simply
1956 * have an expression without {} around it */
1957 result = parse_scalar_initializer(type, env->must_be_constant);
1960 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1961 * the array type size */
1962 if(is_type_array(type) && type->array.size_expression == NULL
1963 && result != NULL) {
1965 switch (result->kind) {
1966 case INITIALIZER_LIST:
1967 size = max_index + 1;
1970 case INITIALIZER_STRING:
1971 size = result->string.string.size;
1974 case INITIALIZER_WIDE_STRING:
1975 size = result->wide_string.string.size;
1979 internal_errorf(HERE, "invalid initializer type");
1982 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1983 cnst->base.type = type_size_t;
1984 cnst->conste.v.int_value = size;
1986 type_t *new_type = duplicate_type(type);
1988 new_type->array.size_expression = cnst;
1989 new_type->array.size_constant = true;
1990 new_type->array.size = size;
1991 env->type = new_type;
1999 static declaration_t *append_declaration(declaration_t *declaration);
2001 static declaration_t *parse_compound_type_specifier(bool is_struct)
2009 symbol_t *symbol = NULL;
2010 declaration_t *declaration = NULL;
2012 if (token.type == T___attribute__) {
2017 if(token.type == T_IDENTIFIER) {
2018 symbol = token.v.symbol;
2022 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2024 declaration = get_declaration(symbol, NAMESPACE_UNION);
2026 } else if(token.type != '{') {
2028 parse_error_expected("while parsing struct type specifier",
2029 T_IDENTIFIER, '{', 0);
2031 parse_error_expected("while parsing union type specifier",
2032 T_IDENTIFIER, '{', 0);
2038 if(declaration == NULL) {
2039 declaration = allocate_declaration_zero();
2040 declaration->namespc =
2041 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2042 declaration->source_position = token.source_position;
2043 declaration->symbol = symbol;
2044 declaration->parent_scope = scope;
2045 if (symbol != NULL) {
2046 environment_push(declaration);
2048 append_declaration(declaration);
2051 if(token.type == '{') {
2052 if(declaration->init.is_defined) {
2053 assert(symbol != NULL);
2054 errorf(HERE, "multiple definitions of '%s %Y'",
2055 is_struct ? "struct" : "union", symbol);
2056 declaration->scope.declarations = NULL;
2058 declaration->init.is_defined = true;
2060 parse_compound_type_entries(declaration);
2067 static void parse_enum_entries(type_t *const enum_type)
2071 if(token.type == '}') {
2073 errorf(HERE, "empty enum not allowed");
2077 add_anchor_token('}');
2079 if(token.type != T_IDENTIFIER) {
2080 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2082 rem_anchor_token('}');
2086 declaration_t *const entry = allocate_declaration_zero();
2087 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2088 entry->type = enum_type;
2089 entry->symbol = token.v.symbol;
2090 entry->source_position = token.source_position;
2093 if(token.type == '=') {
2095 expression_t *value = parse_constant_expression();
2097 value = create_implicit_cast(value, enum_type);
2098 entry->init.enum_value = value;
2103 record_declaration(entry);
2105 if(token.type != ',')
2108 } while(token.type != '}');
2109 rem_anchor_token('}');
2117 static type_t *parse_enum_specifier(void)
2121 declaration_t *declaration;
2124 if(token.type == T_IDENTIFIER) {
2125 symbol = token.v.symbol;
2128 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2129 } else if(token.type != '{') {
2130 parse_error_expected("while parsing enum type specifier",
2131 T_IDENTIFIER, '{', 0);
2138 if(declaration == NULL) {
2139 declaration = allocate_declaration_zero();
2140 declaration->namespc = NAMESPACE_ENUM;
2141 declaration->source_position = token.source_position;
2142 declaration->symbol = symbol;
2143 declaration->parent_scope = scope;
2146 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2147 type->enumt.declaration = declaration;
2149 if(token.type == '{') {
2150 if(declaration->init.is_defined) {
2151 errorf(HERE, "multiple definitions of enum %Y", symbol);
2153 if (symbol != NULL) {
2154 environment_push(declaration);
2156 append_declaration(declaration);
2157 declaration->init.is_defined = 1;
2159 parse_enum_entries(type);
2167 * if a symbol is a typedef to another type, return true
2169 static bool is_typedef_symbol(symbol_t *symbol)
2171 const declaration_t *const declaration =
2172 get_declaration(symbol, NAMESPACE_NORMAL);
2174 declaration != NULL &&
2175 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2178 static type_t *parse_typeof(void)
2185 add_anchor_token(')');
2187 expression_t *expression = NULL;
2190 switch(token.type) {
2191 case T___extension__:
2192 /* this can be a prefix to a typename or an expression */
2193 /* we simply eat it now. */
2196 } while(token.type == T___extension__);
2200 if(is_typedef_symbol(token.v.symbol)) {
2201 type = parse_typename();
2203 expression = parse_expression();
2204 type = expression->base.type;
2209 type = parse_typename();
2213 expression = parse_expression();
2214 type = expression->base.type;
2218 rem_anchor_token(')');
2221 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2222 typeof_type->typeoft.expression = expression;
2223 typeof_type->typeoft.typeof_type = type;
2231 SPECIFIER_SIGNED = 1 << 0,
2232 SPECIFIER_UNSIGNED = 1 << 1,
2233 SPECIFIER_LONG = 1 << 2,
2234 SPECIFIER_INT = 1 << 3,
2235 SPECIFIER_DOUBLE = 1 << 4,
2236 SPECIFIER_CHAR = 1 << 5,
2237 SPECIFIER_SHORT = 1 << 6,
2238 SPECIFIER_LONG_LONG = 1 << 7,
2239 SPECIFIER_FLOAT = 1 << 8,
2240 SPECIFIER_BOOL = 1 << 9,
2241 SPECIFIER_VOID = 1 << 10,
2242 SPECIFIER_INT8 = 1 << 11,
2243 SPECIFIER_INT16 = 1 << 12,
2244 SPECIFIER_INT32 = 1 << 13,
2245 SPECIFIER_INT64 = 1 << 14,
2246 SPECIFIER_INT128 = 1 << 15,
2247 #ifdef PROVIDE_COMPLEX
2248 SPECIFIER_COMPLEX = 1 << 16,
2249 SPECIFIER_IMAGINARY = 1 << 17,
2253 static type_t *create_builtin_type(symbol_t *const symbol,
2254 type_t *const real_type)
2256 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2257 type->builtin.symbol = symbol;
2258 type->builtin.real_type = real_type;
2260 type_t *result = typehash_insert(type);
2261 if (type != result) {
2268 static type_t *get_typedef_type(symbol_t *symbol)
2270 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2271 if(declaration == NULL
2272 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2275 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2276 type->typedeft.declaration = declaration;
2282 * check for the allowed MS alignment values.
2284 static bool check_elignment_value(long long intvalue) {
2285 if(intvalue < 1 || intvalue > 8192) {
2286 errorf(HERE, "illegal alignment value");
2289 unsigned v = (unsigned)intvalue;
2290 for(unsigned i = 1; i <= 8192; i += i) {
2294 errorf(HERE, "alignment must be power of two");
2298 #define DET_MOD(name, tag) do { \
2299 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2300 *modifiers |= tag; \
2303 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2305 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2308 if(token.type == T_restrict) {
2310 DET_MOD(restrict, DM_RESTRICT);
2312 } else if(token.type != T_IDENTIFIER)
2314 symbol_t *symbol = token.v.symbol;
2315 if(symbol == sym_align) {
2318 if(token.type != T_INTEGER)
2320 if(check_elignment_value(token.v.intvalue)) {
2321 if(specifiers->alignment != 0)
2322 warningf(HERE, "align used more than once");
2323 specifiers->alignment = (unsigned char)token.v.intvalue;
2327 } else if(symbol == sym_allocate) {
2330 if(token.type != T_IDENTIFIER)
2332 (void)token.v.symbol;
2334 } else if(symbol == sym_dllimport) {
2336 DET_MOD(dllimport, DM_DLLIMPORT);
2337 } else if(symbol == sym_dllexport) {
2339 DET_MOD(dllexport, DM_DLLEXPORT);
2340 } else if(symbol == sym_thread) {
2342 DET_MOD(thread, DM_THREAD);
2343 } else if(symbol == sym_naked) {
2345 DET_MOD(naked, DM_NAKED);
2346 } else if(symbol == sym_noinline) {
2348 DET_MOD(noinline, DM_NOINLINE);
2349 } else if(symbol == sym_noreturn) {
2351 DET_MOD(noreturn, DM_NORETURN);
2352 } else if(symbol == sym_nothrow) {
2354 DET_MOD(nothrow, DM_NOTHROW);
2355 } else if(symbol == sym_novtable) {
2357 DET_MOD(novtable, DM_NOVTABLE);
2358 } else if(symbol == sym_property) {
2362 bool is_get = false;
2363 if(token.type != T_IDENTIFIER)
2365 if(token.v.symbol == sym_get) {
2367 } else if(token.v.symbol == sym_put) {
2369 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2374 if(token.type != T_IDENTIFIER)
2377 if(specifiers->get_property_sym != NULL) {
2378 errorf(HERE, "get property name already specified");
2380 specifiers->get_property_sym = token.v.symbol;
2383 if(specifiers->put_property_sym != NULL) {
2384 errorf(HERE, "put property name already specified");
2386 specifiers->put_property_sym = token.v.symbol;
2390 if(token.type == ',') {
2397 } else if(symbol == sym_selectany) {
2399 DET_MOD(selectany, DM_SELECTANY);
2400 } else if(symbol == sym_uuid) {
2403 if(token.type != T_STRING_LITERAL)
2407 } else if(symbol == sym_deprecated) {
2409 if(specifiers->deprecated != 0)
2410 warningf(HERE, "deprecated used more than once");
2411 specifiers->deprecated = 1;
2412 if(token.type == '(') {
2414 if(token.type == T_STRING_LITERAL) {
2415 specifiers->deprecated_string = token.v.string.begin;
2418 errorf(HERE, "string literal expected");
2422 } else if(symbol == sym_noalias) {
2424 DET_MOD(noalias, DM_NOALIAS);
2426 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2428 if(token.type == '(')
2432 if (token.type == ',')
2439 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2441 type_t *type = NULL;
2442 unsigned type_qualifiers = 0;
2443 unsigned type_specifiers = 0;
2446 specifiers->source_position = token.source_position;
2449 switch(token.type) {
2452 #define MATCH_STORAGE_CLASS(token, class) \
2454 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2455 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2457 specifiers->declared_storage_class = class; \
2461 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2462 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2463 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2464 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2465 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2470 add_anchor_token(')');
2471 parse_microsoft_extended_decl_modifier(specifiers);
2472 rem_anchor_token(')');
2477 switch (specifiers->declared_storage_class) {
2478 case STORAGE_CLASS_NONE:
2479 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2482 case STORAGE_CLASS_EXTERN:
2483 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2486 case STORAGE_CLASS_STATIC:
2487 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2491 errorf(HERE, "multiple storage classes in declaration specifiers");
2497 /* type qualifiers */
2498 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2500 type_qualifiers |= qualifier; \
2504 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2505 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2506 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2507 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2508 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2509 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2510 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2511 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2513 case T___extension__:
2518 /* type specifiers */
2519 #define MATCH_SPECIFIER(token, specifier, name) \
2522 if(type_specifiers & specifier) { \
2523 errorf(HERE, "multiple " name " type specifiers given"); \
2525 type_specifiers |= specifier; \
2529 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2530 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2531 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2532 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2533 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2534 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2535 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2536 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2537 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2538 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2539 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2540 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2541 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2542 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2543 #ifdef PROVIDE_COMPLEX
2544 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2545 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2547 case T__forceinline:
2548 /* only in microsoft mode */
2549 specifiers->decl_modifiers |= DM_FORCEINLINE;
2553 specifiers->is_inline = true;
2558 if(type_specifiers & SPECIFIER_LONG_LONG) {
2559 errorf(HERE, "multiple type specifiers given");
2560 } else if(type_specifiers & SPECIFIER_LONG) {
2561 type_specifiers |= SPECIFIER_LONG_LONG;
2563 type_specifiers |= SPECIFIER_LONG;
2568 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2570 type->compound.declaration = parse_compound_type_specifier(true);
2574 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2576 type->compound.declaration = parse_compound_type_specifier(false);
2580 type = parse_enum_specifier();
2583 type = parse_typeof();
2585 case T___builtin_va_list:
2586 type = duplicate_type(type_valist);
2590 case T___attribute__:
2594 case T_IDENTIFIER: {
2595 /* only parse identifier if we haven't found a type yet */
2596 if(type != NULL || type_specifiers != 0)
2597 goto finish_specifiers;
2599 type_t *typedef_type = get_typedef_type(token.v.symbol);
2601 if(typedef_type == NULL)
2602 goto finish_specifiers;
2605 type = typedef_type;
2609 /* function specifier */
2611 goto finish_specifiers;
2618 atomic_type_kind_t atomic_type;
2620 /* match valid basic types */
2621 switch(type_specifiers) {
2622 case SPECIFIER_VOID:
2623 atomic_type = ATOMIC_TYPE_VOID;
2625 case SPECIFIER_CHAR:
2626 atomic_type = ATOMIC_TYPE_CHAR;
2628 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2629 atomic_type = ATOMIC_TYPE_SCHAR;
2631 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2632 atomic_type = ATOMIC_TYPE_UCHAR;
2634 case SPECIFIER_SHORT:
2635 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2636 case SPECIFIER_SHORT | SPECIFIER_INT:
2637 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2638 atomic_type = ATOMIC_TYPE_SHORT;
2640 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2641 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2642 atomic_type = ATOMIC_TYPE_USHORT;
2645 case SPECIFIER_SIGNED:
2646 case SPECIFIER_SIGNED | SPECIFIER_INT:
2647 atomic_type = ATOMIC_TYPE_INT;
2649 case SPECIFIER_UNSIGNED:
2650 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2651 atomic_type = ATOMIC_TYPE_UINT;
2653 case SPECIFIER_LONG:
2654 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2655 case SPECIFIER_LONG | SPECIFIER_INT:
2656 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2657 atomic_type = ATOMIC_TYPE_LONG;
2659 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2660 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2661 atomic_type = ATOMIC_TYPE_ULONG;
2663 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2664 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2665 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2666 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2668 atomic_type = ATOMIC_TYPE_LONGLONG;
2670 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2671 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2673 atomic_type = ATOMIC_TYPE_ULONGLONG;
2676 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2677 atomic_type = unsigned_int8_type_kind;
2680 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2681 atomic_type = unsigned_int16_type_kind;
2684 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2685 atomic_type = unsigned_int32_type_kind;
2688 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2689 atomic_type = unsigned_int64_type_kind;
2692 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2693 atomic_type = unsigned_int128_type_kind;
2696 case SPECIFIER_INT8:
2697 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2698 atomic_type = int8_type_kind;
2701 case SPECIFIER_INT16:
2702 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2703 atomic_type = int16_type_kind;
2706 case SPECIFIER_INT32:
2707 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2708 atomic_type = int32_type_kind;
2711 case SPECIFIER_INT64:
2712 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2713 atomic_type = int64_type_kind;
2716 case SPECIFIER_INT128:
2717 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2718 atomic_type = int128_type_kind;
2721 case SPECIFIER_FLOAT:
2722 atomic_type = ATOMIC_TYPE_FLOAT;
2724 case SPECIFIER_DOUBLE:
2725 atomic_type = ATOMIC_TYPE_DOUBLE;
2727 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2728 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2730 case SPECIFIER_BOOL:
2731 atomic_type = ATOMIC_TYPE_BOOL;
2733 #ifdef PROVIDE_COMPLEX
2734 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2735 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2737 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2738 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2740 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2741 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2743 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2744 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2746 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2747 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2749 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2750 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2754 /* invalid specifier combination, give an error message */
2755 if(type_specifiers == 0) {
2756 if (! strict_mode) {
2757 if (warning.implicit_int) {
2758 warningf(HERE, "no type specifiers in declaration, using 'int'");
2760 atomic_type = ATOMIC_TYPE_INT;
2763 errorf(HERE, "no type specifiers given in declaration");
2765 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2766 (type_specifiers & SPECIFIER_UNSIGNED)) {
2767 errorf(HERE, "signed and unsigned specifiers gives");
2768 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2769 errorf(HERE, "only integer types can be signed or unsigned");
2771 errorf(HERE, "multiple datatypes in declaration");
2773 atomic_type = ATOMIC_TYPE_INVALID;
2776 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2777 type->atomic.akind = atomic_type;
2780 if(type_specifiers != 0) {
2781 errorf(HERE, "multiple datatypes in declaration");
2785 type->base.qualifiers = type_qualifiers;
2786 /* FIXME: check type qualifiers here */
2788 type_t *result = typehash_insert(type);
2789 if(newtype && result != type) {
2793 specifiers->type = result;
2798 static type_qualifiers_t parse_type_qualifiers(void)
2800 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2803 switch(token.type) {
2804 /* type qualifiers */
2805 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2806 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2807 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2808 /* microsoft extended type modifiers */
2809 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2810 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2811 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2812 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2813 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2816 return type_qualifiers;
2821 static declaration_t *parse_identifier_list(void)
2823 declaration_t *declarations = NULL;
2824 declaration_t *last_declaration = NULL;
2826 declaration_t *const declaration = allocate_declaration_zero();
2827 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2828 declaration->source_position = token.source_position;
2829 declaration->symbol = token.v.symbol;
2832 if(last_declaration != NULL) {
2833 last_declaration->next = declaration;
2835 declarations = declaration;
2837 last_declaration = declaration;
2839 if(token.type != ',')
2842 } while(token.type == T_IDENTIFIER);
2844 return declarations;
2847 static void semantic_parameter(declaration_t *declaration)
2849 /* TODO: improve error messages */
2851 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2852 errorf(HERE, "typedef not allowed in parameter list");
2853 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2854 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2855 errorf(HERE, "parameter may only have none or register storage class");
2858 type_t *const orig_type = declaration->type;
2859 type_t * type = skip_typeref(orig_type);
2861 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2862 * into a pointer. § 6.7.5.3 (7) */
2863 if (is_type_array(type)) {
2864 type_t *const element_type = type->array.element_type;
2866 type = make_pointer_type(element_type, type->base.qualifiers);
2868 declaration->type = type;
2871 if(is_type_incomplete(type)) {
2872 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2873 orig_type, declaration->symbol);
2877 static declaration_t *parse_parameter(void)
2879 declaration_specifiers_t specifiers;
2880 memset(&specifiers, 0, sizeof(specifiers));
2882 parse_declaration_specifiers(&specifiers);
2884 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2886 semantic_parameter(declaration);
2891 static declaration_t *parse_parameters(function_type_t *type)
2893 if(token.type == T_IDENTIFIER) {
2894 symbol_t *symbol = token.v.symbol;
2895 if(!is_typedef_symbol(symbol)) {
2896 type->kr_style_parameters = true;
2897 return parse_identifier_list();
2901 if(token.type == ')') {
2902 type->unspecified_parameters = 1;
2905 if(token.type == T_void && look_ahead(1)->type == ')') {
2910 declaration_t *declarations = NULL;
2911 declaration_t *declaration;
2912 declaration_t *last_declaration = NULL;
2913 function_parameter_t *parameter;
2914 function_parameter_t *last_parameter = NULL;
2917 switch(token.type) {
2921 return declarations;
2924 case T___extension__:
2926 declaration = parse_parameter();
2928 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2929 memset(parameter, 0, sizeof(parameter[0]));
2930 parameter->type = declaration->type;
2932 if(last_parameter != NULL) {
2933 last_declaration->next = declaration;
2934 last_parameter->next = parameter;
2936 type->parameters = parameter;
2937 declarations = declaration;
2939 last_parameter = parameter;
2940 last_declaration = declaration;
2944 return declarations;
2946 if(token.type != ',')
2947 return declarations;
2957 } construct_type_kind_t;
2959 typedef struct construct_type_t construct_type_t;
2960 struct construct_type_t {
2961 construct_type_kind_t kind;
2962 construct_type_t *next;
2965 typedef struct parsed_pointer_t parsed_pointer_t;
2966 struct parsed_pointer_t {
2967 construct_type_t construct_type;
2968 type_qualifiers_t type_qualifiers;
2971 typedef struct construct_function_type_t construct_function_type_t;
2972 struct construct_function_type_t {
2973 construct_type_t construct_type;
2974 type_t *function_type;
2977 typedef struct parsed_array_t parsed_array_t;
2978 struct parsed_array_t {
2979 construct_type_t construct_type;
2980 type_qualifiers_t type_qualifiers;
2986 typedef struct construct_base_type_t construct_base_type_t;
2987 struct construct_base_type_t {
2988 construct_type_t construct_type;
2992 static construct_type_t *parse_pointer_declarator(void)
2996 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2997 memset(pointer, 0, sizeof(pointer[0]));
2998 pointer->construct_type.kind = CONSTRUCT_POINTER;
2999 pointer->type_qualifiers = parse_type_qualifiers();
3001 return (construct_type_t*) pointer;
3004 static construct_type_t *parse_array_declarator(void)
3007 add_anchor_token(']');
3009 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3010 memset(array, 0, sizeof(array[0]));
3011 array->construct_type.kind = CONSTRUCT_ARRAY;
3013 if(token.type == T_static) {
3014 array->is_static = true;
3018 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3019 if(type_qualifiers != 0) {
3020 if(token.type == T_static) {
3021 array->is_static = true;
3025 array->type_qualifiers = type_qualifiers;
3027 if(token.type == '*' && look_ahead(1)->type == ']') {
3028 array->is_variable = true;
3030 } else if(token.type != ']') {
3031 array->size = parse_assignment_expression();
3034 rem_anchor_token(']');
3037 return (construct_type_t*) array;
3042 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3045 add_anchor_token(')');
3048 if(declaration != NULL) {
3049 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
3051 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
3054 declaration_t *parameters = parse_parameters(&type->function);
3055 if(declaration != NULL) {
3056 declaration->scope.declarations = parameters;
3059 construct_function_type_t *construct_function_type =
3060 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3061 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3062 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3063 construct_function_type->function_type = type;
3065 rem_anchor_token(')');
3069 return (construct_type_t*) construct_function_type;
3072 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3073 bool may_be_abstract)
3075 /* construct a single linked list of construct_type_t's which describe
3076 * how to construct the final declarator type */
3077 construct_type_t *first = NULL;
3078 construct_type_t *last = NULL;
3081 while(token.type == '*') {
3082 construct_type_t *type = parse_pointer_declarator();
3093 /* TODO: find out if this is correct */
3096 construct_type_t *inner_types = NULL;
3098 switch(token.type) {
3100 if(declaration == NULL) {
3101 errorf(HERE, "no identifier expected in typename");
3103 declaration->symbol = token.v.symbol;
3104 declaration->source_position = token.source_position;
3110 add_anchor_token(')');
3111 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3112 rem_anchor_token(')');
3118 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3119 /* avoid a loop in the outermost scope, because eat_statement doesn't
3121 if(token.type == '}' && current_function == NULL) {
3129 construct_type_t *p = last;
3132 construct_type_t *type;
3133 switch(token.type) {
3135 type = parse_function_declarator(declaration);
3138 type = parse_array_declarator();
3141 goto declarator_finished;
3144 /* insert in the middle of the list (behind p) */
3146 type->next = p->next;
3157 declarator_finished:
3160 /* append inner_types at the end of the list, we don't to set last anymore
3161 * as it's not needed anymore */
3163 assert(first == NULL);
3164 first = inner_types;
3166 last->next = inner_types;
3174 static type_t *construct_declarator_type(construct_type_t *construct_list,
3177 construct_type_t *iter = construct_list;
3178 for( ; iter != NULL; iter = iter->next) {
3179 switch(iter->kind) {
3180 case CONSTRUCT_INVALID:
3181 internal_errorf(HERE, "invalid type construction found");
3182 case CONSTRUCT_FUNCTION: {
3183 construct_function_type_t *construct_function_type
3184 = (construct_function_type_t*) iter;
3186 type_t *function_type = construct_function_type->function_type;
3188 function_type->function.return_type = type;
3190 type_t *skipped_return_type = skip_typeref(type);
3191 if (is_type_function(skipped_return_type)) {
3192 errorf(HERE, "function returning function is not allowed");
3193 type = type_error_type;
3194 } else if (is_type_array(skipped_return_type)) {
3195 errorf(HERE, "function returning array is not allowed");
3196 type = type_error_type;
3198 type = function_type;
3203 case CONSTRUCT_POINTER: {
3204 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3205 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3206 pointer_type->pointer.points_to = type;
3207 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3209 type = pointer_type;
3213 case CONSTRUCT_ARRAY: {
3214 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3215 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3217 expression_t *size_expression = parsed_array->size;
3218 if(size_expression != NULL) {
3220 = create_implicit_cast(size_expression, type_size_t);
3223 array_type->base.qualifiers = parsed_array->type_qualifiers;
3224 array_type->array.element_type = type;
3225 array_type->array.is_static = parsed_array->is_static;
3226 array_type->array.is_variable = parsed_array->is_variable;
3227 array_type->array.size_expression = size_expression;
3229 if(size_expression != NULL) {
3230 if(is_constant_expression(size_expression)) {
3231 array_type->array.size_constant = true;
3232 array_type->array.size
3233 = fold_constant(size_expression);
3235 array_type->array.is_vla = true;
3239 type_t *skipped_type = skip_typeref(type);
3240 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3241 errorf(HERE, "array of void is not allowed");
3242 type = type_error_type;
3250 type_t *hashed_type = typehash_insert(type);
3251 if(hashed_type != type) {
3252 /* the function type was constructed earlier freeing it here will
3253 * destroy other types... */
3254 if(iter->kind != CONSTRUCT_FUNCTION) {
3264 static declaration_t *parse_declarator(
3265 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3267 declaration_t *const declaration = allocate_declaration_zero();
3268 declaration->declared_storage_class = specifiers->declared_storage_class;
3269 declaration->modifiers = specifiers->decl_modifiers;
3270 declaration->deprecated = specifiers->deprecated;
3271 declaration->deprecated_string = specifiers->deprecated_string;
3272 declaration->get_property_sym = specifiers->get_property_sym;
3273 declaration->put_property_sym = specifiers->put_property_sym;
3274 declaration->is_inline = specifiers->is_inline;
3276 declaration->storage_class = specifiers->declared_storage_class;
3277 if(declaration->storage_class == STORAGE_CLASS_NONE
3278 && scope != global_scope) {
3279 declaration->storage_class = STORAGE_CLASS_AUTO;
3282 if(specifiers->alignment != 0) {
3283 /* TODO: add checks here */
3284 declaration->alignment = specifiers->alignment;
3287 construct_type_t *construct_type
3288 = parse_inner_declarator(declaration, may_be_abstract);
3289 type_t *const type = specifiers->type;
3290 declaration->type = construct_declarator_type(construct_type, type);
3292 if(construct_type != NULL) {
3293 obstack_free(&temp_obst, construct_type);
3299 static type_t *parse_abstract_declarator(type_t *base_type)
3301 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3303 type_t *result = construct_declarator_type(construct_type, base_type);
3304 if(construct_type != NULL) {
3305 obstack_free(&temp_obst, construct_type);
3311 static declaration_t *append_declaration(declaration_t* const declaration)
3313 if (last_declaration != NULL) {
3314 last_declaration->next = declaration;
3316 scope->declarations = declaration;
3318 last_declaration = declaration;
3323 * Check if the declaration of main is suspicious. main should be a
3324 * function with external linkage, returning int, taking either zero
3325 * arguments, two, or three arguments of appropriate types, ie.
3327 * int main([ int argc, char **argv [, char **env ] ]).
3329 * @param decl the declaration to check
3330 * @param type the function type of the declaration
3332 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3334 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3335 warningf(decl->source_position, "'main' is normally a non-static function");
3337 if (skip_typeref(func_type->return_type) != type_int) {
3338 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3340 const function_parameter_t *parm = func_type->parameters;
3342 type_t *const first_type = parm->type;
3343 if (!types_compatible(skip_typeref(first_type), type_int)) {
3344 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3348 type_t *const second_type = parm->type;
3349 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3350 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3354 type_t *const third_type = parm->type;
3355 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3356 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3360 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3364 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3370 * Check if a symbol is the equal to "main".
3372 static bool is_sym_main(const symbol_t *const sym)
3374 return strcmp(sym->string, "main") == 0;
3377 static declaration_t *internal_record_declaration(
3378 declaration_t *const declaration,
3379 const bool is_function_definition)
3381 const symbol_t *const symbol = declaration->symbol;
3382 const namespace_t namespc = (namespace_t)declaration->namespc;
3384 type_t *const orig_type = declaration->type;
3385 type_t *const type = skip_typeref(orig_type);
3386 if (is_type_function(type) &&
3387 type->function.unspecified_parameters &&
3388 warning.strict_prototypes) {
3389 warningf(declaration->source_position,
3390 "function declaration '%#T' is not a prototype",
3391 orig_type, declaration->symbol);
3394 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3395 check_type_of_main(declaration, &type->function);
3398 assert(declaration->symbol != NULL);
3399 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3401 assert(declaration != previous_declaration);
3402 if (previous_declaration != NULL) {
3403 if (previous_declaration->parent_scope == scope) {
3404 /* can happen for K&R style declarations */
3405 if(previous_declaration->type == NULL) {
3406 previous_declaration->type = declaration->type;
3409 const type_t *prev_type = skip_typeref(previous_declaration->type);
3410 if (!types_compatible(type, prev_type)) {
3411 errorf(declaration->source_position,
3412 "declaration '%#T' is incompatible with "
3413 "previous declaration '%#T'",
3414 orig_type, symbol, previous_declaration->type, symbol);
3415 errorf(previous_declaration->source_position,
3416 "previous declaration of '%Y' was here", symbol);
3418 unsigned old_storage_class = previous_declaration->storage_class;
3419 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3420 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3421 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3422 return previous_declaration;
3425 unsigned new_storage_class = declaration->storage_class;
3427 if(is_type_incomplete(prev_type)) {
3428 previous_declaration->type = type;
3432 /* pretend no storage class means extern for function
3433 * declarations (except if the previous declaration is neither
3434 * none nor extern) */
3435 if (is_type_function(type)) {
3436 switch (old_storage_class) {
3437 case STORAGE_CLASS_NONE:
3438 old_storage_class = STORAGE_CLASS_EXTERN;
3440 case STORAGE_CLASS_EXTERN:
3441 if (is_function_definition) {
3442 if (warning.missing_prototypes &&
3443 prev_type->function.unspecified_parameters &&
3444 !is_sym_main(symbol)) {
3445 warningf(declaration->source_position,
3446 "no previous prototype for '%#T'",
3449 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3450 new_storage_class = STORAGE_CLASS_EXTERN;
3458 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3459 new_storage_class == STORAGE_CLASS_EXTERN) {
3460 warn_redundant_declaration:
3461 if (warning.redundant_decls) {
3462 warningf(declaration->source_position,
3463 "redundant declaration for '%Y'", symbol);
3464 warningf(previous_declaration->source_position,
3465 "previous declaration of '%Y' was here",
3468 } else if (current_function == NULL) {
3469 if (old_storage_class != STORAGE_CLASS_STATIC &&
3470 new_storage_class == STORAGE_CLASS_STATIC) {
3471 errorf(declaration->source_position,
3472 "static declaration of '%Y' follows non-static declaration",
3474 errorf(previous_declaration->source_position,
3475 "previous declaration of '%Y' was here", symbol);
3477 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3478 goto warn_redundant_declaration;
3480 if (new_storage_class == STORAGE_CLASS_NONE) {
3481 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3482 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3486 if (old_storage_class == new_storage_class) {
3487 errorf(declaration->source_position,
3488 "redeclaration of '%Y'", symbol);
3490 errorf(declaration->source_position,
3491 "redeclaration of '%Y' with different linkage",
3494 errorf(previous_declaration->source_position,
3495 "previous declaration of '%Y' was here", symbol);
3498 return previous_declaration;
3500 } else if (is_function_definition) {
3501 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3502 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3503 warningf(declaration->source_position,
3504 "no previous prototype for '%#T'", orig_type, symbol);
3505 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3506 warningf(declaration->source_position,
3507 "no previous declaration for '%#T'", orig_type,
3511 } else if (warning.missing_declarations &&
3512 scope == global_scope &&
3513 !is_type_function(type) && (
3514 declaration->storage_class == STORAGE_CLASS_NONE ||
3515 declaration->storage_class == STORAGE_CLASS_THREAD
3517 warningf(declaration->source_position,
3518 "no previous declaration for '%#T'", orig_type, symbol);
3521 assert(declaration->parent_scope == NULL);
3522 assert(scope != NULL);
3524 declaration->parent_scope = scope;
3526 environment_push(declaration);
3527 return append_declaration(declaration);
3530 static declaration_t *record_declaration(declaration_t *declaration)
3532 return internal_record_declaration(declaration, false);
3535 static declaration_t *record_function_definition(declaration_t *declaration)
3537 return internal_record_declaration(declaration, true);
3540 static void parser_error_multiple_definition(declaration_t *declaration,
3541 const source_position_t source_position)
3543 errorf(source_position, "multiple definition of symbol '%Y'",
3544 declaration->symbol);
3545 errorf(declaration->source_position,
3546 "this is the location of the previous definition.");
3549 static bool is_declaration_specifier(const token_t *token,
3550 bool only_type_specifiers)
3552 switch(token->type) {
3556 return is_typedef_symbol(token->v.symbol);
3558 case T___extension__:
3561 return !only_type_specifiers;
3568 static void parse_init_declarator_rest(declaration_t *declaration)
3572 type_t *orig_type = declaration->type;
3573 type_t *type = skip_typeref(orig_type);
3575 if(declaration->init.initializer != NULL) {
3576 parser_error_multiple_definition(declaration, token.source_position);
3579 bool must_be_constant = false;
3580 if(declaration->storage_class == STORAGE_CLASS_STATIC
3581 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3582 || declaration->parent_scope == global_scope) {
3583 must_be_constant = true;
3586 parse_initializer_env_t env;
3587 env.type = orig_type;
3588 env.must_be_constant = must_be_constant;
3589 env.declaration = declaration;
3591 initializer_t *initializer = parse_initializer(&env);
3593 if(env.type != orig_type) {
3594 orig_type = env.type;
3595 type = skip_typeref(orig_type);
3596 declaration->type = env.type;
3599 if(is_type_function(type)) {
3600 errorf(declaration->source_position,
3601 "initializers not allowed for function types at declator '%Y' (type '%T')",
3602 declaration->symbol, orig_type);
3604 declaration->init.initializer = initializer;
3608 /* parse rest of a declaration without any declarator */
3609 static void parse_anonymous_declaration_rest(
3610 const declaration_specifiers_t *specifiers,
3611 parsed_declaration_func finished_declaration)
3615 declaration_t *const declaration = allocate_declaration_zero();
3616 declaration->type = specifiers->type;
3617 declaration->declared_storage_class = specifiers->declared_storage_class;
3618 declaration->source_position = specifiers->source_position;
3619 declaration->modifiers = specifiers->decl_modifiers;
3621 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3622 warningf(declaration->source_position, "useless storage class in empty declaration");
3624 declaration->storage_class = STORAGE_CLASS_NONE;
3626 type_t *type = declaration->type;
3627 switch (type->kind) {
3628 case TYPE_COMPOUND_STRUCT:
3629 case TYPE_COMPOUND_UNION: {
3630 if (type->compound.declaration->symbol == NULL) {
3631 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3640 warningf(declaration->source_position, "empty declaration");
3644 finished_declaration(declaration);
3647 static void parse_declaration_rest(declaration_t *ndeclaration,
3648 const declaration_specifiers_t *specifiers,
3649 parsed_declaration_func finished_declaration)
3651 add_anchor_token(';');
3652 add_anchor_token('=');
3653 add_anchor_token(',');
3655 declaration_t *declaration = finished_declaration(ndeclaration);
3657 type_t *orig_type = declaration->type;
3658 type_t *type = skip_typeref(orig_type);
3660 if (type->kind != TYPE_FUNCTION &&
3661 declaration->is_inline &&
3662 is_type_valid(type)) {
3663 warningf(declaration->source_position,
3664 "variable '%Y' declared 'inline'\n", declaration->symbol);
3667 if(token.type == '=') {
3668 parse_init_declarator_rest(declaration);
3671 if(token.type != ',')
3675 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3680 rem_anchor_token(';');
3681 rem_anchor_token('=');
3682 rem_anchor_token(',');
3685 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3687 symbol_t *symbol = declaration->symbol;
3688 if(symbol == NULL) {
3689 errorf(HERE, "anonymous declaration not valid as function parameter");
3692 namespace_t namespc = (namespace_t) declaration->namespc;
3693 if(namespc != NAMESPACE_NORMAL) {
3694 return record_declaration(declaration);
3697 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3698 if(previous_declaration == NULL ||
3699 previous_declaration->parent_scope != scope) {
3700 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3705 if(previous_declaration->type == NULL) {
3706 previous_declaration->type = declaration->type;
3707 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3708 previous_declaration->storage_class = declaration->storage_class;
3709 previous_declaration->parent_scope = scope;
3710 return previous_declaration;
3712 return record_declaration(declaration);
3716 static void parse_declaration(parsed_declaration_func finished_declaration)
3718 declaration_specifiers_t specifiers;
3719 memset(&specifiers, 0, sizeof(specifiers));
3720 parse_declaration_specifiers(&specifiers);
3722 if(token.type == ';') {
3723 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3725 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3726 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3730 static void parse_kr_declaration_list(declaration_t *declaration)
3732 type_t *type = skip_typeref(declaration->type);
3733 if(!is_type_function(type))
3736 if(!type->function.kr_style_parameters)
3739 /* push function parameters */
3740 int top = environment_top();
3741 scope_t *last_scope = scope;
3742 set_scope(&declaration->scope);
3744 declaration_t *parameter = declaration->scope.declarations;
3745 for( ; parameter != NULL; parameter = parameter->next) {
3746 assert(parameter->parent_scope == NULL);
3747 parameter->parent_scope = scope;
3748 environment_push(parameter);
3751 /* parse declaration list */
3752 while(is_declaration_specifier(&token, false)) {
3753 parse_declaration(finished_kr_declaration);
3756 /* pop function parameters */
3757 assert(scope == &declaration->scope);
3758 set_scope(last_scope);
3759 environment_pop_to(top);
3761 /* update function type */
3762 type_t *new_type = duplicate_type(type);
3763 new_type->function.kr_style_parameters = false;
3765 function_parameter_t *parameters = NULL;
3766 function_parameter_t *last_parameter = NULL;
3768 declaration_t *parameter_declaration = declaration->scope.declarations;
3769 for( ; parameter_declaration != NULL;
3770 parameter_declaration = parameter_declaration->next) {
3771 type_t *parameter_type = parameter_declaration->type;
3772 if(parameter_type == NULL) {
3774 errorf(HERE, "no type specified for function parameter '%Y'",
3775 parameter_declaration->symbol);
3777 if (warning.implicit_int) {
3778 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3779 parameter_declaration->symbol);
3781 parameter_type = type_int;
3782 parameter_declaration->type = parameter_type;
3786 semantic_parameter(parameter_declaration);
3787 parameter_type = parameter_declaration->type;
3789 function_parameter_t *function_parameter
3790 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3791 memset(function_parameter, 0, sizeof(function_parameter[0]));
3793 function_parameter->type = parameter_type;
3794 if(last_parameter != NULL) {
3795 last_parameter->next = function_parameter;
3797 parameters = function_parameter;
3799 last_parameter = function_parameter;
3801 new_type->function.parameters = parameters;
3803 type = typehash_insert(new_type);
3804 if(type != new_type) {
3805 obstack_free(type_obst, new_type);
3808 declaration->type = type;
3811 static bool first_err = true;
3814 * When called with first_err set, prints the name of the current function,
3817 static void print_in_function(void) {
3820 diagnosticf("%s: In function '%Y':\n",
3821 current_function->source_position.input_name,
3822 current_function->symbol);
3827 * Check if all labels are defined in the current function.
3828 * Check if all labels are used in the current function.
3830 static void check_labels(void)
3832 for (const goto_statement_t *goto_statement = goto_first;
3833 goto_statement != NULL;
3834 goto_statement = goto_statement->next) {
3835 declaration_t *label = goto_statement->label;
3838 if (label->source_position.input_name == NULL) {
3839 print_in_function();
3840 errorf(goto_statement->base.source_position,
3841 "label '%Y' used but not defined", label->symbol);
3844 goto_first = goto_last = NULL;
3846 if (warning.unused_label) {
3847 for (const label_statement_t *label_statement = label_first;
3848 label_statement != NULL;
3849 label_statement = label_statement->next) {
3850 const declaration_t *label = label_statement->label;
3852 if (! label->used) {
3853 print_in_function();
3854 warningf(label_statement->base.source_position,
3855 "label '%Y' defined but not used", label->symbol);
3859 label_first = label_last = NULL;
3863 * Check declarations of current_function for unused entities.
3865 static void check_declarations(void)
3867 if (warning.unused_parameter) {
3868 const scope_t *scope = ¤t_function->scope;
3870 const declaration_t *parameter = scope->declarations;
3871 for (; parameter != NULL; parameter = parameter->next) {
3872 if (! parameter->used) {
3873 print_in_function();
3874 warningf(parameter->source_position,
3875 "unused parameter '%Y'", parameter->symbol);
3879 if (warning.unused_variable) {
3883 static void parse_external_declaration(void)
3885 /* function-definitions and declarations both start with declaration
3887 declaration_specifiers_t specifiers;
3888 memset(&specifiers, 0, sizeof(specifiers));
3890 add_anchor_token(';');
3891 parse_declaration_specifiers(&specifiers);
3892 rem_anchor_token(';');
3894 /* must be a declaration */
3895 if(token.type == ';') {
3896 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3900 add_anchor_token(',');
3901 add_anchor_token('=');
3902 rem_anchor_token(';');
3904 /* declarator is common to both function-definitions and declarations */
3905 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3907 rem_anchor_token(',');
3908 rem_anchor_token('=');
3909 rem_anchor_token(';');
3911 /* must be a declaration */
3912 if(token.type == ',' || token.type == '=' || token.type == ';') {
3913 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3917 /* must be a function definition */
3918 parse_kr_declaration_list(ndeclaration);
3920 if(token.type != '{') {
3921 parse_error_expected("while parsing function definition", '{', 0);
3922 eat_until_matching_token(';');
3926 type_t *type = ndeclaration->type;
3928 /* note that we don't skip typerefs: the standard doesn't allow them here
3929 * (so we can't use is_type_function here) */
3930 if(type->kind != TYPE_FUNCTION) {
3931 if (is_type_valid(type)) {
3932 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3933 type, ndeclaration->symbol);
3939 /* § 6.7.5.3 (14) a function definition with () means no
3940 * parameters (and not unspecified parameters) */
3941 if(type->function.unspecified_parameters) {
3942 type_t *duplicate = duplicate_type(type);
3943 duplicate->function.unspecified_parameters = false;
3945 type = typehash_insert(duplicate);
3946 if(type != duplicate) {
3947 obstack_free(type_obst, duplicate);
3949 ndeclaration->type = type;
3952 declaration_t *const declaration = record_function_definition(ndeclaration);
3953 if(ndeclaration != declaration) {
3954 declaration->scope = ndeclaration->scope;
3956 type = skip_typeref(declaration->type);
3958 /* push function parameters and switch scope */
3959 int top = environment_top();
3960 scope_t *last_scope = scope;
3961 set_scope(&declaration->scope);
3963 declaration_t *parameter = declaration->scope.declarations;
3964 for( ; parameter != NULL; parameter = parameter->next) {
3965 if(parameter->parent_scope == &ndeclaration->scope) {
3966 parameter->parent_scope = scope;
3968 assert(parameter->parent_scope == NULL
3969 || parameter->parent_scope == scope);
3970 parameter->parent_scope = scope;
3971 environment_push(parameter);
3974 if(declaration->init.statement != NULL) {
3975 parser_error_multiple_definition(declaration, token.source_position);
3977 goto end_of_parse_external_declaration;
3979 /* parse function body */
3980 int label_stack_top = label_top();
3981 declaration_t *old_current_function = current_function;
3982 current_function = declaration;
3984 declaration->init.statement = parse_compound_statement();
3987 check_declarations();
3989 assert(current_function == declaration);
3990 current_function = old_current_function;
3991 label_pop_to(label_stack_top);
3994 end_of_parse_external_declaration:
3995 assert(scope == &declaration->scope);
3996 set_scope(last_scope);
3997 environment_pop_to(top);
4000 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4001 source_position_t source_position)
4003 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4004 type->bitfield.base = base;
4005 type->bitfield.size = size;
4010 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4013 declaration_t *iter = compound_declaration->scope.declarations;
4014 for( ; iter != NULL; iter = iter->next) {
4015 if(iter->namespc != NAMESPACE_NORMAL)
4018 if(iter->symbol == NULL) {
4019 type_t *type = skip_typeref(iter->type);
4020 if(is_type_compound(type)) {
4021 declaration_t *result
4022 = find_compound_entry(type->compound.declaration, symbol);
4029 if(iter->symbol == symbol) {
4037 static void parse_compound_declarators(declaration_t *struct_declaration,
4038 const declaration_specifiers_t *specifiers)
4040 declaration_t *last_declaration = struct_declaration->scope.declarations;
4041 if(last_declaration != NULL) {
4042 while(last_declaration->next != NULL) {
4043 last_declaration = last_declaration->next;
4048 declaration_t *declaration;
4050 if(token.type == ':') {
4051 source_position_t source_position = HERE;
4054 type_t *base_type = specifiers->type;
4055 expression_t *size = parse_constant_expression();
4057 if(!is_type_integer(skip_typeref(base_type))) {
4058 errorf(HERE, "bitfield base type '%T' is not an integer type",
4062 type_t *type = make_bitfield_type(base_type, size, source_position);
4064 declaration = allocate_declaration_zero();
4065 declaration->namespc = NAMESPACE_NORMAL;
4066 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4067 declaration->storage_class = STORAGE_CLASS_NONE;
4068 declaration->source_position = source_position;
4069 declaration->modifiers = specifiers->decl_modifiers;
4070 declaration->type = type;
4072 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4074 type_t *orig_type = declaration->type;
4075 type_t *type = skip_typeref(orig_type);
4077 if(token.type == ':') {
4078 source_position_t source_position = HERE;
4080 expression_t *size = parse_constant_expression();
4082 if(!is_type_integer(type)) {
4083 errorf(HERE, "bitfield base type '%T' is not an "
4084 "integer type", orig_type);
4087 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
4088 declaration->type = bitfield_type;
4090 /* TODO we ignore arrays for now... what is missing is a check
4091 * that they're at the end of the struct */
4092 if(is_type_incomplete(type) && !is_type_array(type)) {
4094 "compound member '%Y' has incomplete type '%T'",
4095 declaration->symbol, orig_type);
4096 } else if(is_type_function(type)) {
4097 errorf(HERE, "compound member '%Y' must not have function "
4098 "type '%T'", declaration->symbol, orig_type);
4103 /* make sure we don't define a symbol multiple times */
4104 symbol_t *symbol = declaration->symbol;
4105 if(symbol != NULL) {
4106 declaration_t *prev_decl
4107 = find_compound_entry(struct_declaration, symbol);
4109 if(prev_decl != NULL) {
4110 assert(prev_decl->symbol == symbol);
4111 errorf(declaration->source_position,
4112 "multiple declarations of symbol '%Y'", symbol);
4113 errorf(prev_decl->source_position,
4114 "previous declaration of '%Y' was here", symbol);
4118 /* append declaration */
4119 if(last_declaration != NULL) {
4120 last_declaration->next = declaration;
4122 struct_declaration->scope.declarations = declaration;
4124 last_declaration = declaration;
4126 if(token.type != ',')
4136 static void parse_compound_type_entries(declaration_t *compound_declaration)
4139 add_anchor_token('}');
4141 while(token.type != '}' && token.type != T_EOF) {
4142 declaration_specifiers_t specifiers;
4143 memset(&specifiers, 0, sizeof(specifiers));
4144 parse_declaration_specifiers(&specifiers);
4146 parse_compound_declarators(compound_declaration, &specifiers);
4148 rem_anchor_token('}');
4150 if(token.type == T_EOF) {
4151 errorf(HERE, "EOF while parsing struct");
4156 static type_t *parse_typename(void)
4158 declaration_specifiers_t specifiers;
4159 memset(&specifiers, 0, sizeof(specifiers));
4160 parse_declaration_specifiers(&specifiers);
4161 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4162 /* TODO: improve error message, user does probably not know what a
4163 * storage class is...
4165 errorf(HERE, "typename may not have a storage class");
4168 type_t *result = parse_abstract_declarator(specifiers.type);
4176 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4177 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4178 expression_t *left);
4180 typedef struct expression_parser_function_t expression_parser_function_t;
4181 struct expression_parser_function_t {
4182 unsigned precedence;
4183 parse_expression_function parser;
4184 unsigned infix_precedence;
4185 parse_expression_infix_function infix_parser;
4188 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4191 * Prints an error message if an expression was expected but not read
4193 static expression_t *expected_expression_error(void)
4195 /* skip the error message if the error token was read */
4196 if (token.type != T_ERROR) {
4197 errorf(HERE, "expected expression, got token '%K'", &token);
4201 return create_invalid_expression();
4205 * Parse a string constant.
4207 static expression_t *parse_string_const(void)
4210 if (token.type == T_STRING_LITERAL) {
4211 string_t res = token.v.string;
4213 while (token.type == T_STRING_LITERAL) {
4214 res = concat_strings(&res, &token.v.string);
4217 if (token.type != T_WIDE_STRING_LITERAL) {
4218 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4219 /* note: that we use type_char_ptr here, which is already the
4220 * automatic converted type. revert_automatic_type_conversion
4221 * will construct the array type */
4222 cnst->base.type = type_char_ptr;
4223 cnst->string.value = res;
4227 wres = concat_string_wide_string(&res, &token.v.wide_string);
4229 wres = token.v.wide_string;
4234 switch (token.type) {
4235 case T_WIDE_STRING_LITERAL:
4236 wres = concat_wide_strings(&wres, &token.v.wide_string);
4239 case T_STRING_LITERAL:
4240 wres = concat_wide_string_string(&wres, &token.v.string);
4244 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4245 cnst->base.type = type_wchar_t_ptr;
4246 cnst->wide_string.value = wres;
4255 * Parse an integer constant.
4257 static expression_t *parse_int_const(void)
4259 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4260 cnst->base.source_position = HERE;
4261 cnst->base.type = token.datatype;
4262 cnst->conste.v.int_value = token.v.intvalue;
4270 * Parse a character constant.
4272 static expression_t *parse_character_constant(void)
4274 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4276 cnst->base.source_position = HERE;
4277 cnst->base.type = token.datatype;
4278 cnst->conste.v.character = token.v.string;
4280 if (cnst->conste.v.character.size != 1) {
4281 if (warning.multichar && (c_mode & _GNUC)) {
4283 warningf(HERE, "multi-character character constant");
4285 errorf(HERE, "more than 1 characters in character constant");
4294 * Parse a wide character constant.
4296 static expression_t *parse_wide_character_constant(void)
4298 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4300 cnst->base.source_position = HERE;
4301 cnst->base.type = token.datatype;
4302 cnst->conste.v.wide_character = token.v.wide_string;
4304 if (cnst->conste.v.wide_character.size != 1) {
4305 if (warning.multichar && (c_mode & _GNUC)) {
4307 warningf(HERE, "multi-character character constant");
4309 errorf(HERE, "more than 1 characters in character constant");
4318 * Parse a float constant.
4320 static expression_t *parse_float_const(void)
4322 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4323 cnst->base.type = token.datatype;
4324 cnst->conste.v.float_value = token.v.floatvalue;
4331 static declaration_t *create_implicit_function(symbol_t *symbol,
4332 const source_position_t source_position)
4334 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4335 ntype->function.return_type = type_int;
4336 ntype->function.unspecified_parameters = true;
4338 type_t *type = typehash_insert(ntype);
4343 declaration_t *const declaration = allocate_declaration_zero();
4344 declaration->storage_class = STORAGE_CLASS_EXTERN;
4345 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4346 declaration->type = type;
4347 declaration->symbol = symbol;
4348 declaration->source_position = source_position;
4349 declaration->parent_scope = global_scope;
4351 scope_t *old_scope = scope;
4352 set_scope(global_scope);
4354 environment_push(declaration);
4355 /* prepends the declaration to the global declarations list */
4356 declaration->next = scope->declarations;
4357 scope->declarations = declaration;
4359 assert(scope == global_scope);
4360 set_scope(old_scope);
4366 * Creates a return_type (func)(argument_type) function type if not
4369 * @param return_type the return type
4370 * @param argument_type the argument type
4372 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4374 function_parameter_t *parameter
4375 = obstack_alloc(type_obst, sizeof(parameter[0]));
4376 memset(parameter, 0, sizeof(parameter[0]));
4377 parameter->type = argument_type;
4379 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4380 type->function.return_type = return_type;
4381 type->function.parameters = parameter;
4383 type_t *result = typehash_insert(type);
4384 if(result != type) {
4392 * Creates a function type for some function like builtins.
4394 * @param symbol the symbol describing the builtin
4396 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4398 switch(symbol->ID) {
4399 case T___builtin_alloca:
4400 return make_function_1_type(type_void_ptr, type_size_t);
4401 case T___builtin_nan:
4402 return make_function_1_type(type_double, type_char_ptr);
4403 case T___builtin_nanf:
4404 return make_function_1_type(type_float, type_char_ptr);
4405 case T___builtin_nand:
4406 return make_function_1_type(type_long_double, type_char_ptr);
4407 case T___builtin_va_end:
4408 return make_function_1_type(type_void, type_valist);
4410 internal_errorf(HERE, "not implemented builtin symbol found");
4415 * Performs automatic type cast as described in § 6.3.2.1.
4417 * @param orig_type the original type
4419 static type_t *automatic_type_conversion(type_t *orig_type)
4421 type_t *type = skip_typeref(orig_type);
4422 if(is_type_array(type)) {
4423 array_type_t *array_type = &type->array;
4424 type_t *element_type = array_type->element_type;
4425 unsigned qualifiers = array_type->type.qualifiers;
4427 return make_pointer_type(element_type, qualifiers);
4430 if(is_type_function(type)) {
4431 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4438 * reverts the automatic casts of array to pointer types and function
4439 * to function-pointer types as defined § 6.3.2.1
4441 type_t *revert_automatic_type_conversion(const expression_t *expression)
4443 switch (expression->kind) {
4444 case EXPR_REFERENCE: return expression->reference.declaration->type;
4445 case EXPR_SELECT: return expression->select.compound_entry->type;
4447 case EXPR_UNARY_DEREFERENCE: {
4448 const expression_t *const value = expression->unary.value;
4449 type_t *const type = skip_typeref(value->base.type);
4450 assert(is_type_pointer(type));
4451 return type->pointer.points_to;
4454 case EXPR_BUILTIN_SYMBOL:
4455 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4457 case EXPR_ARRAY_ACCESS: {
4458 const expression_t *array_ref = expression->array_access.array_ref;
4459 type_t *type_left = skip_typeref(array_ref->base.type);
4460 if (!is_type_valid(type_left))
4462 assert(is_type_pointer(type_left));
4463 return type_left->pointer.points_to;
4466 case EXPR_STRING_LITERAL: {
4467 size_t size = expression->string.value.size;
4468 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4471 case EXPR_WIDE_STRING_LITERAL: {
4472 size_t size = expression->wide_string.value.size;
4473 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4476 case EXPR_COMPOUND_LITERAL:
4477 return expression->compound_literal.type;
4482 return expression->base.type;
4485 static expression_t *parse_reference(void)
4487 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4489 reference_expression_t *ref = &expression->reference;
4490 ref->symbol = token.v.symbol;
4492 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4494 source_position_t source_position = token.source_position;
4497 if(declaration == NULL) {
4498 if (! strict_mode && token.type == '(') {
4499 /* an implicitly defined function */
4500 if (warning.implicit_function_declaration) {
4501 warningf(HERE, "implicit declaration of function '%Y'",
4505 declaration = create_implicit_function(ref->symbol,
4508 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4509 return create_invalid_expression();
4513 type_t *type = declaration->type;
4515 /* we always do the auto-type conversions; the & and sizeof parser contains
4516 * code to revert this! */
4517 type = automatic_type_conversion(type);
4519 ref->declaration = declaration;
4520 ref->base.type = type;
4522 /* this declaration is used */
4523 declaration->used = true;
4525 /* check for deprecated functions */
4526 if(declaration->deprecated != 0) {
4527 const char *prefix = "";
4528 if (is_type_function(declaration->type))
4529 prefix = "function ";
4531 if (declaration->deprecated_string != NULL) {
4532 warningf(source_position,
4533 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4534 declaration->deprecated_string);
4536 warningf(source_position,
4537 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4544 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4548 /* TODO check if explicit cast is allowed and issue warnings/errors */
4551 static expression_t *parse_compound_literal(type_t *type)
4553 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4555 parse_initializer_env_t env;
4557 env.declaration = NULL;
4558 env.must_be_constant = false;
4559 initializer_t *initializer = parse_initializer(&env);
4562 expression->compound_literal.initializer = initializer;
4563 expression->compound_literal.type = type;
4564 expression->base.type = automatic_type_conversion(type);
4570 * Parse a cast expression.
4572 static expression_t *parse_cast(void)
4574 source_position_t source_position = token.source_position;
4576 type_t *type = parse_typename();
4578 /* matching add_anchor_token() is at call site */
4579 rem_anchor_token(')');
4582 if(token.type == '{') {
4583 return parse_compound_literal(type);
4586 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4587 cast->base.source_position = source_position;
4589 expression_t *value = parse_sub_expression(20);
4591 check_cast_allowed(value, type);
4593 cast->base.type = type;
4594 cast->unary.value = value;
4598 return create_invalid_expression();
4602 * Parse a statement expression.
4604 static expression_t *parse_statement_expression(void)
4606 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4608 statement_t *statement = parse_compound_statement();
4609 expression->statement.statement = statement;
4610 expression->base.source_position = statement->base.source_position;
4612 /* find last statement and use its type */
4613 type_t *type = type_void;
4614 const statement_t *stmt = statement->compound.statements;
4616 while (stmt->base.next != NULL)
4617 stmt = stmt->base.next;
4619 if (stmt->kind == STATEMENT_EXPRESSION) {
4620 type = stmt->expression.expression->base.type;
4623 warningf(expression->base.source_position, "empty statement expression ({})");
4625 expression->base.type = type;
4631 return create_invalid_expression();
4635 * Parse a braced expression.
4637 static expression_t *parse_brace_expression(void)
4640 add_anchor_token(')');
4642 switch(token.type) {
4644 /* gcc extension: a statement expression */
4645 return parse_statement_expression();
4649 return parse_cast();
4651 if(is_typedef_symbol(token.v.symbol)) {
4652 return parse_cast();
4656 expression_t *result = parse_expression();
4657 rem_anchor_token(')');
4662 return create_invalid_expression();
4665 static expression_t *parse_function_keyword(void)
4670 if (current_function == NULL) {
4671 errorf(HERE, "'__func__' used outside of a function");
4674 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4675 expression->base.type = type_char_ptr;
4676 expression->funcname.kind = FUNCNAME_FUNCTION;
4681 static expression_t *parse_pretty_function_keyword(void)
4683 eat(T___PRETTY_FUNCTION__);
4685 if (current_function == NULL) {
4686 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4689 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4690 expression->base.type = type_char_ptr;
4691 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
4696 static expression_t *parse_funcsig_keyword(void)
4700 if (current_function == NULL) {
4701 errorf(HERE, "'__FUNCSIG__' used outside of a function");
4704 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4705 expression->base.type = type_char_ptr;
4706 expression->funcname.kind = FUNCNAME_FUNCSIG;
4711 static expression_t *parse_funcdname_keyword(void)
4713 eat(T___FUNCDNAME__);
4715 if (current_function == NULL) {
4716 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
4719 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4720 expression->base.type = type_char_ptr;
4721 expression->funcname.kind = FUNCNAME_FUNCDNAME;
4726 static designator_t *parse_designator(void)
4728 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4729 result->source_position = HERE;
4731 if(token.type != T_IDENTIFIER) {
4732 parse_error_expected("while parsing member designator",
4736 result->symbol = token.v.symbol;
4739 designator_t *last_designator = result;
4741 if(token.type == '.') {
4743 if(token.type != T_IDENTIFIER) {
4744 parse_error_expected("while parsing member designator",
4748 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4749 designator->source_position = HERE;
4750 designator->symbol = token.v.symbol;
4753 last_designator->next = designator;
4754 last_designator = designator;
4757 if(token.type == '[') {
4759 add_anchor_token(']');
4760 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4761 designator->source_position = HERE;
4762 designator->array_index = parse_expression();
4763 rem_anchor_token(']');
4765 if(designator->array_index == NULL) {
4769 last_designator->next = designator;
4770 last_designator = designator;
4782 * Parse the __builtin_offsetof() expression.
4784 static expression_t *parse_offsetof(void)
4786 eat(T___builtin_offsetof);
4788 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4789 expression->base.type = type_size_t;
4792 add_anchor_token(',');
4793 type_t *type = parse_typename();
4794 rem_anchor_token(',');
4796 add_anchor_token(')');
4797 designator_t *designator = parse_designator();
4798 rem_anchor_token(')');
4801 expression->offsetofe.type = type;
4802 expression->offsetofe.designator = designator;
4805 memset(&path, 0, sizeof(path));
4806 path.top_type = type;
4807 path.path = NEW_ARR_F(type_path_entry_t, 0);
4809 descend_into_subtype(&path);
4811 if(!walk_designator(&path, designator, true)) {
4812 return create_invalid_expression();
4815 DEL_ARR_F(path.path);
4819 return create_invalid_expression();
4823 * Parses a _builtin_va_start() expression.
4825 static expression_t *parse_va_start(void)
4827 eat(T___builtin_va_start);
4829 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4832 add_anchor_token(',');
4833 expression->va_starte.ap = parse_assignment_expression();
4834 rem_anchor_token(',');
4836 expression_t *const expr = parse_assignment_expression();
4837 if (expr->kind == EXPR_REFERENCE) {
4838 declaration_t *const decl = expr->reference.declaration;
4840 return create_invalid_expression();
4841 if (decl->parent_scope == ¤t_function->scope &&
4842 decl->next == NULL) {
4843 expression->va_starte.parameter = decl;
4848 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4850 return create_invalid_expression();
4854 * Parses a _builtin_va_arg() expression.
4856 static expression_t *parse_va_arg(void)
4858 eat(T___builtin_va_arg);
4860 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4863 expression->va_arge.ap = parse_assignment_expression();
4865 expression->base.type = parse_typename();
4870 return create_invalid_expression();
4873 static expression_t *parse_builtin_symbol(void)
4875 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4877 symbol_t *symbol = token.v.symbol;
4879 expression->builtin_symbol.symbol = symbol;
4882 type_t *type = get_builtin_symbol_type(symbol);
4883 type = automatic_type_conversion(type);
4885 expression->base.type = type;
4890 * Parses a __builtin_constant() expression.
4892 static expression_t *parse_builtin_constant(void)
4894 eat(T___builtin_constant_p);
4896 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4899 add_anchor_token(')');
4900 expression->builtin_constant.value = parse_assignment_expression();
4901 rem_anchor_token(')');
4903 expression->base.type = type_int;
4907 return create_invalid_expression();
4911 * Parses a __builtin_prefetch() expression.
4913 static expression_t *parse_builtin_prefetch(void)
4915 eat(T___builtin_prefetch);
4917 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4920 add_anchor_token(')');
4921 expression->builtin_prefetch.adr = parse_assignment_expression();
4922 if (token.type == ',') {
4924 expression->builtin_prefetch.rw = parse_assignment_expression();
4926 if (token.type == ',') {
4928 expression->builtin_prefetch.locality = parse_assignment_expression();
4930 rem_anchor_token(')');
4932 expression->base.type = type_void;
4936 return create_invalid_expression();
4940 * Parses a __builtin_is_*() compare expression.
4942 static expression_t *parse_compare_builtin(void)
4944 expression_t *expression;
4946 switch(token.type) {
4947 case T___builtin_isgreater:
4948 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4950 case T___builtin_isgreaterequal:
4951 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4953 case T___builtin_isless:
4954 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4956 case T___builtin_islessequal:
4957 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4959 case T___builtin_islessgreater:
4960 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4962 case T___builtin_isunordered:
4963 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4966 internal_errorf(HERE, "invalid compare builtin found");
4969 expression->base.source_position = HERE;
4973 expression->binary.left = parse_assignment_expression();
4975 expression->binary.right = parse_assignment_expression();
4978 type_t *const orig_type_left = expression->binary.left->base.type;
4979 type_t *const orig_type_right = expression->binary.right->base.type;
4981 type_t *const type_left = skip_typeref(orig_type_left);
4982 type_t *const type_right = skip_typeref(orig_type_right);
4983 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4984 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4985 type_error_incompatible("invalid operands in comparison",
4986 expression->base.source_position, orig_type_left, orig_type_right);
4989 semantic_comparison(&expression->binary);
4994 return create_invalid_expression();
4998 * Parses a __builtin_expect() expression.
5000 static expression_t *parse_builtin_expect(void)
5002 eat(T___builtin_expect);
5004 expression_t *expression
5005 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5008 expression->binary.left = parse_assignment_expression();
5010 expression->binary.right = parse_constant_expression();
5013 expression->base.type = expression->binary.left->base.type;
5017 return create_invalid_expression();
5021 * Parses a MS assume() expression.
5023 static expression_t *parse_assume(void) {
5026 expression_t *expression
5027 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5030 add_anchor_token(')');
5031 expression->unary.value = parse_assignment_expression();
5032 rem_anchor_token(')');
5035 expression->base.type = type_void;
5038 return create_invalid_expression();
5042 * Parse a microsoft __noop expression.
5044 static expression_t *parse_noop_expression(void) {
5045 source_position_t source_position = HERE;
5048 if (token.type == '(') {
5049 /* parse arguments */
5051 add_anchor_token(')');
5052 add_anchor_token(',');
5054 if(token.type != ')') {
5056 (void)parse_assignment_expression();
5057 if(token.type != ',')
5063 rem_anchor_token(',');
5064 rem_anchor_token(')');
5067 /* the result is a (int)0 */
5068 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5069 cnst->base.source_position = source_position;
5070 cnst->base.type = type_int;
5071 cnst->conste.v.int_value = 0;
5072 cnst->conste.is_ms_noop = true;
5077 return create_invalid_expression();
5081 * Parses a primary expression.
5083 static expression_t *parse_primary_expression(void)
5085 switch (token.type) {
5086 case T_INTEGER: return parse_int_const();
5087 case T_CHARACTER_CONSTANT: return parse_character_constant();
5088 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5089 case T_FLOATINGPOINT: return parse_float_const();
5090 case T_STRING_LITERAL:
5091 case T_WIDE_STRING_LITERAL: return parse_string_const();
5092 case T_IDENTIFIER: return parse_reference();
5093 case T___FUNCTION__:
5094 case T___func__: return parse_function_keyword();
5095 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5096 case T___FUNCSIG__: return parse_funcsig_keyword();
5097 case T___FUNCDNAME__: return parse_funcdname_keyword();
5098 case T___builtin_offsetof: return parse_offsetof();
5099 case T___builtin_va_start: return parse_va_start();
5100 case T___builtin_va_arg: return parse_va_arg();
5101 case T___builtin_expect: return parse_builtin_expect();
5102 case T___builtin_alloca:
5103 case T___builtin_nan:
5104 case T___builtin_nand:
5105 case T___builtin_nanf:
5106 case T___builtin_va_end: return parse_builtin_symbol();
5107 case T___builtin_isgreater:
5108 case T___builtin_isgreaterequal:
5109 case T___builtin_isless:
5110 case T___builtin_islessequal:
5111 case T___builtin_islessgreater:
5112 case T___builtin_isunordered: return parse_compare_builtin();
5113 case T___builtin_constant_p: return parse_builtin_constant();
5114 case T___builtin_prefetch: return parse_builtin_prefetch();
5115 case T__assume: return parse_assume();
5117 case '(': return parse_brace_expression();
5118 case T___noop: return parse_noop_expression();
5121 errorf(HERE, "unexpected token %K, expected an expression", &token);
5122 return create_invalid_expression();
5126 * Check if the expression has the character type and issue a warning then.
5128 static void check_for_char_index_type(const expression_t *expression) {
5129 type_t *const type = expression->base.type;
5130 const type_t *const base_type = skip_typeref(type);
5132 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5133 warning.char_subscripts) {
5134 warningf(expression->base.source_position,
5135 "array subscript has type '%T'", type);
5139 static expression_t *parse_array_expression(unsigned precedence,
5145 add_anchor_token(']');
5147 expression_t *inside = parse_expression();
5149 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5151 array_access_expression_t *array_access = &expression->array_access;
5153 type_t *const orig_type_left = left->base.type;
5154 type_t *const orig_type_inside = inside->base.type;
5156 type_t *const type_left = skip_typeref(orig_type_left);
5157 type_t *const type_inside = skip_typeref(orig_type_inside);
5159 type_t *return_type;
5160 if (is_type_pointer(type_left)) {
5161 return_type = type_left->pointer.points_to;
5162 array_access->array_ref = left;
5163 array_access->index = inside;
5164 check_for_char_index_type(inside);
5165 } else if (is_type_pointer(type_inside)) {
5166 return_type = type_inside->pointer.points_to;
5167 array_access->array_ref = inside;
5168 array_access->index = left;
5169 array_access->flipped = true;
5170 check_for_char_index_type(left);
5172 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5174 "array access on object with non-pointer types '%T', '%T'",
5175 orig_type_left, orig_type_inside);
5177 return_type = type_error_type;
5178 array_access->array_ref = create_invalid_expression();
5181 rem_anchor_token(']');
5182 if(token.type != ']') {
5183 parse_error_expected("Problem while parsing array access", ']', 0);
5188 return_type = automatic_type_conversion(return_type);
5189 expression->base.type = return_type;
5194 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5196 expression_t *tp_expression = allocate_expression_zero(kind);
5197 tp_expression->base.type = type_size_t;
5199 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5201 add_anchor_token(')');
5202 tp_expression->typeprop.type = parse_typename();
5203 rem_anchor_token(')');
5206 expression_t *expression = parse_sub_expression(precedence);
5207 expression->base.type = revert_automatic_type_conversion(expression);
5209 tp_expression->typeprop.type = expression->base.type;
5210 tp_expression->typeprop.tp_expression = expression;
5213 return tp_expression;
5215 return create_invalid_expression();
5218 static expression_t *parse_sizeof(unsigned precedence)
5221 return parse_typeprop(EXPR_SIZEOF, precedence);
5224 static expression_t *parse_alignof(unsigned precedence)
5227 return parse_typeprop(EXPR_SIZEOF, precedence);
5230 static expression_t *parse_select_expression(unsigned precedence,
5231 expression_t *compound)
5234 assert(token.type == '.' || token.type == T_MINUSGREATER);
5236 bool is_pointer = (token.type == T_MINUSGREATER);
5239 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5240 select->select.compound = compound;
5242 if(token.type != T_IDENTIFIER) {
5243 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5246 symbol_t *symbol = token.v.symbol;
5247 select->select.symbol = symbol;
5250 type_t *const orig_type = compound->base.type;
5251 type_t *const type = skip_typeref(orig_type);
5253 type_t *type_left = type;
5255 if (!is_type_pointer(type)) {
5256 if (is_type_valid(type)) {
5257 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5259 return create_invalid_expression();
5261 type_left = type->pointer.points_to;
5263 type_left = skip_typeref(type_left);
5265 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5266 type_left->kind != TYPE_COMPOUND_UNION) {
5267 if (is_type_valid(type_left)) {
5268 errorf(HERE, "request for member '%Y' in something not a struct or "
5269 "union, but '%T'", symbol, type_left);
5271 return create_invalid_expression();
5274 declaration_t *const declaration = type_left->compound.declaration;
5276 if(!declaration->init.is_defined) {
5277 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5279 return create_invalid_expression();
5282 declaration_t *iter = find_compound_entry(declaration, symbol);
5284 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5285 return create_invalid_expression();
5288 /* we always do the auto-type conversions; the & and sizeof parser contains
5289 * code to revert this! */
5290 type_t *expression_type = automatic_type_conversion(iter->type);
5292 select->select.compound_entry = iter;
5293 select->base.type = expression_type;
5295 if(expression_type->kind == TYPE_BITFIELD) {
5296 expression_t *extract
5297 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5298 extract->unary.value = select;
5299 extract->base.type = expression_type->bitfield.base;
5308 * Parse a call expression, ie. expression '( ... )'.
5310 * @param expression the function address
5312 static expression_t *parse_call_expression(unsigned precedence,
5313 expression_t *expression)
5316 expression_t *result = allocate_expression_zero(EXPR_CALL);
5317 result->base.source_position = expression->base.source_position;
5319 call_expression_t *call = &result->call;
5320 call->function = expression;
5322 type_t *const orig_type = expression->base.type;
5323 type_t *const type = skip_typeref(orig_type);
5325 function_type_t *function_type = NULL;
5326 if (is_type_pointer(type)) {
5327 type_t *const to_type = skip_typeref(type->pointer.points_to);
5329 if (is_type_function(to_type)) {
5330 function_type = &to_type->function;
5331 call->base.type = function_type->return_type;
5335 if (function_type == NULL && is_type_valid(type)) {
5336 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5339 /* parse arguments */
5341 add_anchor_token(')');
5342 add_anchor_token(',');
5344 if(token.type != ')') {
5345 call_argument_t *last_argument = NULL;
5348 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5350 argument->expression = parse_assignment_expression();
5351 if(last_argument == NULL) {
5352 call->arguments = argument;
5354 last_argument->next = argument;
5356 last_argument = argument;
5358 if(token.type != ',')
5363 rem_anchor_token(',');
5364 rem_anchor_token(')');
5367 if(function_type != NULL) {
5368 function_parameter_t *parameter = function_type->parameters;
5369 call_argument_t *argument = call->arguments;
5370 for( ; parameter != NULL && argument != NULL;
5371 parameter = parameter->next, argument = argument->next) {
5372 type_t *expected_type = parameter->type;
5373 /* TODO report scope in error messages */
5374 expression_t *const arg_expr = argument->expression;
5375 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
5376 if (res_type == NULL) {
5377 /* TODO improve error message */
5378 errorf(arg_expr->base.source_position,
5379 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5380 arg_expr, arg_expr->base.type, expected_type);
5382 argument->expression = create_implicit_cast(argument->expression, expected_type);
5385 /* too few parameters */
5386 if(parameter != NULL) {
5387 errorf(HERE, "too few arguments to function '%E'", expression);
5388 } else if(argument != NULL) {
5389 /* too many parameters */
5390 if(!function_type->variadic
5391 && !function_type->unspecified_parameters) {
5392 errorf(HERE, "too many arguments to function '%E'", expression);
5394 /* do default promotion */
5395 for( ; argument != NULL; argument = argument->next) {
5396 type_t *type = argument->expression->base.type;
5398 type = skip_typeref(type);
5399 if(is_type_integer(type)) {
5400 type = promote_integer(type);
5401 } else if(type == type_float) {
5405 argument->expression
5406 = create_implicit_cast(argument->expression, type);
5409 check_format(&result->call);
5412 check_format(&result->call);
5418 return create_invalid_expression();
5421 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5423 static bool same_compound_type(const type_t *type1, const type_t *type2)
5426 is_type_compound(type1) &&
5427 type1->kind == type2->kind &&
5428 type1->compound.declaration == type2->compound.declaration;
5432 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5434 * @param expression the conditional expression
5436 static expression_t *parse_conditional_expression(unsigned precedence,
5437 expression_t *expression)
5440 add_anchor_token(':');
5442 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5444 conditional_expression_t *conditional = &result->conditional;
5445 conditional->condition = expression;
5448 type_t *const condition_type_orig = expression->base.type;
5449 type_t *const condition_type = skip_typeref(condition_type_orig);
5450 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5451 type_error("expected a scalar type in conditional condition",
5452 expression->base.source_position, condition_type_orig);
5455 expression_t *true_expression = parse_expression();
5456 rem_anchor_token(':');
5458 expression_t *false_expression = parse_sub_expression(precedence);
5460 type_t *const orig_true_type = true_expression->base.type;
5461 type_t *const orig_false_type = false_expression->base.type;
5462 type_t *const true_type = skip_typeref(orig_true_type);
5463 type_t *const false_type = skip_typeref(orig_false_type);
5466 type_t *result_type;
5467 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5468 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5469 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5470 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5471 warningf(expression->base.source_position,
5472 "ISO C forbids conditional expression with only one void side");
5474 result_type = type_void;
5475 } else if (is_type_arithmetic(true_type)
5476 && is_type_arithmetic(false_type)) {
5477 result_type = semantic_arithmetic(true_type, false_type);
5479 true_expression = create_implicit_cast(true_expression, result_type);
5480 false_expression = create_implicit_cast(false_expression, result_type);
5482 conditional->true_expression = true_expression;
5483 conditional->false_expression = false_expression;
5484 conditional->base.type = result_type;
5485 } else if (same_compound_type(true_type, false_type)) {
5486 /* just take 1 of the 2 types */
5487 result_type = true_type;
5488 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5489 type_t *pointer_type;
5491 expression_t *other_expression;
5492 if (is_type_pointer(true_type)) {
5493 pointer_type = true_type;
5494 other_type = false_type;
5495 other_expression = false_expression;
5497 pointer_type = false_type;
5498 other_type = true_type;
5499 other_expression = true_expression;
5502 if(is_type_pointer(other_type)) {
5503 if(!pointers_compatible(true_type, false_type)) {
5504 warningf(expression->base.source_position,
5505 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5507 result_type = true_type;
5508 } else if(is_null_pointer_constant(other_expression)) {
5509 result_type = pointer_type;
5510 } else if(is_type_integer(other_type)) {
5511 warningf(expression->base.source_position,
5512 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5513 result_type = pointer_type;
5515 type_error_incompatible("while parsing conditional",
5516 expression->base.source_position, true_type, false_type);
5517 result_type = type_error_type;
5520 /* TODO: one pointer to void*, other some pointer */
5522 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5523 type_error_incompatible("while parsing conditional",
5524 expression->base.source_position, true_type,
5527 result_type = type_error_type;
5530 conditional->true_expression
5531 = create_implicit_cast(true_expression, result_type);
5532 conditional->false_expression
5533 = create_implicit_cast(false_expression, result_type);
5534 conditional->base.type = result_type;
5537 return create_invalid_expression();
5541 * Parse an extension expression.
5543 static expression_t *parse_extension(unsigned precedence)
5545 eat(T___extension__);
5547 /* TODO enable extensions */
5548 expression_t *expression = parse_sub_expression(precedence);
5549 /* TODO disable extensions */
5554 * Parse a __builtin_classify_type() expression.
5556 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5558 eat(T___builtin_classify_type);
5560 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5561 result->base.type = type_int;
5564 add_anchor_token(')');
5565 expression_t *expression = parse_sub_expression(precedence);
5566 rem_anchor_token(')');
5568 result->classify_type.type_expression = expression;
5572 return create_invalid_expression();
5575 static void semantic_incdec(unary_expression_t *expression)
5577 type_t *const orig_type = expression->value->base.type;
5578 type_t *const type = skip_typeref(orig_type);
5579 /* TODO !is_type_real && !is_type_pointer */
5580 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5581 if (is_type_valid(type)) {
5582 /* TODO: improve error message */
5583 errorf(HERE, "operation needs an arithmetic or pointer type");
5588 expression->base.type = orig_type;
5591 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5593 type_t *const orig_type = expression->value->base.type;
5594 type_t *const type = skip_typeref(orig_type);
5595 if(!is_type_arithmetic(type)) {
5596 if (is_type_valid(type)) {
5597 /* TODO: improve error message */
5598 errorf(HERE, "operation needs an arithmetic type");
5603 expression->base.type = orig_type;
5606 static void semantic_unexpr_scalar(unary_expression_t *expression)
5608 type_t *const orig_type = expression->value->base.type;
5609 type_t *const type = skip_typeref(orig_type);
5610 if (!is_type_scalar(type)) {
5611 if (is_type_valid(type)) {
5612 errorf(HERE, "operand of ! must be of scalar type");
5617 expression->base.type = orig_type;
5620 static void semantic_unexpr_integer(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_integer(type)) {
5625 if (is_type_valid(type)) {
5626 errorf(HERE, "operand of ~ must be of integer type");
5631 expression->base.type = orig_type;
5634 static void semantic_dereference(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_pointer(type)) {
5639 if (is_type_valid(type)) {
5640 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5645 type_t *result_type = type->pointer.points_to;
5646 result_type = automatic_type_conversion(result_type);
5647 expression->base.type = result_type;
5651 * Check the semantic of the address taken expression.
5653 static void semantic_take_addr(unary_expression_t *expression)
5655 expression_t *value = expression->value;
5656 value->base.type = revert_automatic_type_conversion(value);
5658 type_t *orig_type = value->base.type;
5659 if(!is_type_valid(orig_type))
5662 if(value->kind == EXPR_REFERENCE) {
5663 declaration_t *const declaration = value->reference.declaration;
5664 if(declaration != NULL) {
5665 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5666 errorf(expression->base.source_position,
5667 "address of register variable '%Y' requested",
5668 declaration->symbol);
5670 declaration->address_taken = 1;
5674 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5677 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5678 static expression_t *parse_##unexpression_type(unsigned precedence) \
5682 expression_t *unary_expression \
5683 = allocate_expression_zero(unexpression_type); \
5684 unary_expression->base.source_position = HERE; \
5685 unary_expression->unary.value = parse_sub_expression(precedence); \
5687 sfunc(&unary_expression->unary); \
5689 return unary_expression; \
5692 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5693 semantic_unexpr_arithmetic)
5694 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5695 semantic_unexpr_arithmetic)
5696 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5697 semantic_unexpr_scalar)
5698 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5699 semantic_dereference)
5700 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5702 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5703 semantic_unexpr_integer)
5704 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5706 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5709 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5711 static expression_t *parse_##unexpression_type(unsigned precedence, \
5712 expression_t *left) \
5714 (void) precedence; \
5717 expression_t *unary_expression \
5718 = allocate_expression_zero(unexpression_type); \
5719 unary_expression->unary.value = left; \
5721 sfunc(&unary_expression->unary); \
5723 return unary_expression; \
5726 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5727 EXPR_UNARY_POSTFIX_INCREMENT,
5729 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5730 EXPR_UNARY_POSTFIX_DECREMENT,
5733 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5735 /* TODO: handle complex + imaginary types */
5737 /* § 6.3.1.8 Usual arithmetic conversions */
5738 if(type_left == type_long_double || type_right == type_long_double) {
5739 return type_long_double;
5740 } else if(type_left == type_double || type_right == type_double) {
5742 } else if(type_left == type_float || type_right == type_float) {
5746 type_right = promote_integer(type_right);
5747 type_left = promote_integer(type_left);
5749 if(type_left == type_right)
5752 bool signed_left = is_type_signed(type_left);
5753 bool signed_right = is_type_signed(type_right);
5754 int rank_left = get_rank(type_left);
5755 int rank_right = get_rank(type_right);
5756 if(rank_left < rank_right) {
5757 if(signed_left == signed_right || !signed_right) {
5763 if(signed_left == signed_right || !signed_left) {
5772 * Check the semantic restrictions for a binary expression.
5774 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5776 expression_t *const left = expression->left;
5777 expression_t *const right = expression->right;
5778 type_t *const orig_type_left = left->base.type;
5779 type_t *const orig_type_right = right->base.type;
5780 type_t *const type_left = skip_typeref(orig_type_left);
5781 type_t *const type_right = skip_typeref(orig_type_right);
5783 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5784 /* TODO: improve error message */
5785 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5786 errorf(HERE, "operation needs arithmetic types");
5791 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5792 expression->left = create_implicit_cast(left, arithmetic_type);
5793 expression->right = create_implicit_cast(right, arithmetic_type);
5794 expression->base.type = arithmetic_type;
5797 static void semantic_shift_op(binary_expression_t *expression)
5799 expression_t *const left = expression->left;
5800 expression_t *const right = expression->right;
5801 type_t *const orig_type_left = left->base.type;
5802 type_t *const orig_type_right = right->base.type;
5803 type_t * type_left = skip_typeref(orig_type_left);
5804 type_t * type_right = skip_typeref(orig_type_right);
5806 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5807 /* TODO: improve error message */
5808 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5809 errorf(HERE, "operation needs integer types");
5814 type_left = promote_integer(type_left);
5815 type_right = promote_integer(type_right);
5817 expression->left = create_implicit_cast(left, type_left);
5818 expression->right = create_implicit_cast(right, type_right);
5819 expression->base.type = type_left;
5822 static void semantic_add(binary_expression_t *expression)
5824 expression_t *const left = expression->left;
5825 expression_t *const right = expression->right;
5826 type_t *const orig_type_left = left->base.type;
5827 type_t *const orig_type_right = right->base.type;
5828 type_t *const type_left = skip_typeref(orig_type_left);
5829 type_t *const type_right = skip_typeref(orig_type_right);
5832 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5833 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5834 expression->left = create_implicit_cast(left, arithmetic_type);
5835 expression->right = create_implicit_cast(right, arithmetic_type);
5836 expression->base.type = arithmetic_type;
5838 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5839 expression->base.type = type_left;
5840 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5841 expression->base.type = type_right;
5842 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5843 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5847 static void semantic_sub(binary_expression_t *expression)
5849 expression_t *const left = expression->left;
5850 expression_t *const right = expression->right;
5851 type_t *const orig_type_left = left->base.type;
5852 type_t *const orig_type_right = right->base.type;
5853 type_t *const type_left = skip_typeref(orig_type_left);
5854 type_t *const type_right = skip_typeref(orig_type_right);
5857 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5858 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5859 expression->left = create_implicit_cast(left, arithmetic_type);
5860 expression->right = create_implicit_cast(right, arithmetic_type);
5861 expression->base.type = arithmetic_type;
5863 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5864 expression->base.type = type_left;
5865 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5866 if(!pointers_compatible(type_left, type_right)) {
5868 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5869 orig_type_left, orig_type_right);
5871 expression->base.type = type_ptrdiff_t;
5873 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5874 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5875 orig_type_left, orig_type_right);
5880 * Check the semantics of comparison expressions.
5882 * @param expression The expression to check.
5884 static void semantic_comparison(binary_expression_t *expression)
5886 expression_t *left = expression->left;
5887 expression_t *right = expression->right;
5888 type_t *orig_type_left = left->base.type;
5889 type_t *orig_type_right = right->base.type;
5891 type_t *type_left = skip_typeref(orig_type_left);
5892 type_t *type_right = skip_typeref(orig_type_right);
5894 /* TODO non-arithmetic types */
5895 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5896 if (warning.sign_compare &&
5897 (expression->base.kind != EXPR_BINARY_EQUAL &&
5898 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5899 (is_type_signed(type_left) != is_type_signed(type_right))) {
5900 warningf(expression->base.source_position,
5901 "comparison between signed and unsigned");
5903 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5904 expression->left = create_implicit_cast(left, arithmetic_type);
5905 expression->right = create_implicit_cast(right, arithmetic_type);
5906 expression->base.type = arithmetic_type;
5907 if (warning.float_equal &&
5908 (expression->base.kind == EXPR_BINARY_EQUAL ||
5909 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5910 is_type_float(arithmetic_type)) {
5911 warningf(expression->base.source_position,
5912 "comparing floating point with == or != is unsafe");
5914 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5915 /* TODO check compatibility */
5916 } else if (is_type_pointer(type_left)) {
5917 expression->right = create_implicit_cast(right, type_left);
5918 } else if (is_type_pointer(type_right)) {
5919 expression->left = create_implicit_cast(left, type_right);
5920 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5921 type_error_incompatible("invalid operands in comparison",
5922 expression->base.source_position,
5923 type_left, type_right);
5925 expression->base.type = type_int;
5928 static void semantic_arithmetic_assign(binary_expression_t *expression)
5930 expression_t *left = expression->left;
5931 expression_t *right = expression->right;
5932 type_t *orig_type_left = left->base.type;
5933 type_t *orig_type_right = right->base.type;
5935 type_t *type_left = skip_typeref(orig_type_left);
5936 type_t *type_right = skip_typeref(orig_type_right);
5938 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5939 /* TODO: improve error message */
5940 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5941 errorf(HERE, "operation needs arithmetic types");
5946 /* combined instructions are tricky. We can't create an implicit cast on
5947 * the left side, because we need the uncasted form for the store.
5948 * The ast2firm pass has to know that left_type must be right_type
5949 * for the arithmetic operation and create a cast by itself */
5950 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5951 expression->right = create_implicit_cast(right, arithmetic_type);
5952 expression->base.type = type_left;
5955 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5957 expression_t *const left = expression->left;
5958 expression_t *const right = expression->right;
5959 type_t *const orig_type_left = left->base.type;
5960 type_t *const orig_type_right = right->base.type;
5961 type_t *const type_left = skip_typeref(orig_type_left);
5962 type_t *const type_right = skip_typeref(orig_type_right);
5964 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5965 /* combined instructions are tricky. We can't create an implicit cast on
5966 * the left side, because we need the uncasted form for the store.
5967 * The ast2firm pass has to know that left_type must be right_type
5968 * for the arithmetic operation and create a cast by itself */
5969 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5970 expression->right = create_implicit_cast(right, arithmetic_type);
5971 expression->base.type = type_left;
5972 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5973 expression->base.type = type_left;
5974 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5975 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5980 * Check the semantic restrictions of a logical expression.
5982 static void semantic_logical_op(binary_expression_t *expression)
5984 expression_t *const left = expression->left;
5985 expression_t *const right = expression->right;
5986 type_t *const orig_type_left = left->base.type;
5987 type_t *const orig_type_right = right->base.type;
5988 type_t *const type_left = skip_typeref(orig_type_left);
5989 type_t *const type_right = skip_typeref(orig_type_right);
5991 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5992 /* TODO: improve error message */
5993 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5994 errorf(HERE, "operation needs scalar types");
5999 expression->base.type = type_int;
6003 * Checks if a compound type has constant fields.
6005 static bool has_const_fields(const compound_type_t *type)
6007 const scope_t *scope = &type->declaration->scope;
6008 const declaration_t *declaration = scope->declarations;
6010 for (; declaration != NULL; declaration = declaration->next) {
6011 if (declaration->namespc != NAMESPACE_NORMAL)
6014 const type_t *decl_type = skip_typeref(declaration->type);
6015 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6023 * Check the semantic restrictions of a binary assign expression.
6025 static void semantic_binexpr_assign(binary_expression_t *expression)
6027 expression_t *left = expression->left;
6028 type_t *orig_type_left = left->base.type;
6030 type_t *type_left = revert_automatic_type_conversion(left);
6031 type_left = skip_typeref(orig_type_left);
6033 /* must be a modifiable lvalue */
6034 if (is_type_array(type_left)) {
6035 errorf(HERE, "cannot assign to arrays ('%E')", left);
6038 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6039 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6043 if(is_type_incomplete(type_left)) {
6045 "left-hand side of assignment '%E' has incomplete type '%T'",
6046 left, orig_type_left);
6049 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6050 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6051 left, orig_type_left);
6055 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6057 if (res_type == NULL) {
6058 errorf(expression->base.source_position,
6059 "cannot assign to '%T' from '%T'",
6060 orig_type_left, expression->right->base.type);
6062 expression->right = create_implicit_cast(expression->right, res_type);
6065 expression->base.type = orig_type_left;
6069 * Determine if the outermost operation (or parts thereof) of the given
6070 * expression has no effect in order to generate a warning about this fact.
6071 * Therefore in some cases this only examines some of the operands of the
6072 * expression (see comments in the function and examples below).
6074 * f() + 23; // warning, because + has no effect
6075 * x || f(); // no warning, because x controls execution of f()
6076 * x ? y : f(); // warning, because y has no effect
6077 * (void)x; // no warning to be able to suppress the warning
6078 * This function can NOT be used for an "expression has definitely no effect"-
6080 static bool expression_has_effect(const expression_t *const expr)
6082 switch (expr->kind) {
6083 case EXPR_UNKNOWN: break;
6084 case EXPR_INVALID: return true; /* do NOT warn */
6085 case EXPR_REFERENCE: return false;
6086 /* suppress the warning for microsoft __noop operations */
6087 case EXPR_CONST: return expr->conste.is_ms_noop;
6088 case EXPR_CHARACTER_CONSTANT: return false;
6089 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6090 case EXPR_STRING_LITERAL: return false;
6091 case EXPR_WIDE_STRING_LITERAL: return false;
6094 const call_expression_t *const call = &expr->call;
6095 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6098 switch (call->function->builtin_symbol.symbol->ID) {
6099 case T___builtin_va_end: return true;
6100 default: return false;
6104 /* Generate the warning if either the left or right hand side of a
6105 * conditional expression has no effect */
6106 case EXPR_CONDITIONAL: {
6107 const conditional_expression_t *const cond = &expr->conditional;
6109 expression_has_effect(cond->true_expression) &&
6110 expression_has_effect(cond->false_expression);
6113 case EXPR_SELECT: return false;
6114 case EXPR_ARRAY_ACCESS: return false;
6115 case EXPR_SIZEOF: return false;
6116 case EXPR_CLASSIFY_TYPE: return false;
6117 case EXPR_ALIGNOF: return false;
6119 case EXPR_FUNCNAME: return false;
6120 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6121 case EXPR_BUILTIN_CONSTANT_P: return false;
6122 case EXPR_BUILTIN_PREFETCH: return true;
6123 case EXPR_OFFSETOF: return false;
6124 case EXPR_VA_START: return true;
6125 case EXPR_VA_ARG: return true;
6126 case EXPR_STATEMENT: return true; // TODO
6127 case EXPR_COMPOUND_LITERAL: return false;
6129 case EXPR_UNARY_NEGATE: return false;
6130 case EXPR_UNARY_PLUS: return false;
6131 case EXPR_UNARY_BITWISE_NEGATE: return false;
6132 case EXPR_UNARY_NOT: return false;
6133 case EXPR_UNARY_DEREFERENCE: return false;
6134 case EXPR_UNARY_TAKE_ADDRESS: return false;
6135 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6136 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6137 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6138 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6140 /* Treat void casts as if they have an effect in order to being able to
6141 * suppress the warning */
6142 case EXPR_UNARY_CAST: {
6143 type_t *const type = skip_typeref(expr->base.type);
6144 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6147 case EXPR_UNARY_CAST_IMPLICIT: return true;
6148 case EXPR_UNARY_ASSUME: return true;
6149 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6151 case EXPR_BINARY_ADD: return false;
6152 case EXPR_BINARY_SUB: return false;
6153 case EXPR_BINARY_MUL: return false;
6154 case EXPR_BINARY_DIV: return false;
6155 case EXPR_BINARY_MOD: return false;
6156 case EXPR_BINARY_EQUAL: return false;
6157 case EXPR_BINARY_NOTEQUAL: return false;
6158 case EXPR_BINARY_LESS: return false;
6159 case EXPR_BINARY_LESSEQUAL: return false;
6160 case EXPR_BINARY_GREATER: return false;
6161 case EXPR_BINARY_GREATEREQUAL: return false;
6162 case EXPR_BINARY_BITWISE_AND: return false;
6163 case EXPR_BINARY_BITWISE_OR: return false;
6164 case EXPR_BINARY_BITWISE_XOR: return false;
6165 case EXPR_BINARY_SHIFTLEFT: return false;
6166 case EXPR_BINARY_SHIFTRIGHT: return false;
6167 case EXPR_BINARY_ASSIGN: return true;
6168 case EXPR_BINARY_MUL_ASSIGN: return true;
6169 case EXPR_BINARY_DIV_ASSIGN: return true;
6170 case EXPR_BINARY_MOD_ASSIGN: return true;
6171 case EXPR_BINARY_ADD_ASSIGN: return true;
6172 case EXPR_BINARY_SUB_ASSIGN: return true;
6173 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6174 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6175 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6176 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6177 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6179 /* Only examine the right hand side of && and ||, because the left hand
6180 * side already has the effect of controlling the execution of the right
6182 case EXPR_BINARY_LOGICAL_AND:
6183 case EXPR_BINARY_LOGICAL_OR:
6184 /* Only examine the right hand side of a comma expression, because the left
6185 * hand side has a separate warning */
6186 case EXPR_BINARY_COMMA:
6187 return expression_has_effect(expr->binary.right);
6189 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6190 case EXPR_BINARY_ISGREATER: return false;
6191 case EXPR_BINARY_ISGREATEREQUAL: return false;
6192 case EXPR_BINARY_ISLESS: return false;
6193 case EXPR_BINARY_ISLESSEQUAL: return false;
6194 case EXPR_BINARY_ISLESSGREATER: return false;
6195 case EXPR_BINARY_ISUNORDERED: return false;
6198 internal_errorf(HERE, "unexpected expression");
6201 static void semantic_comma(binary_expression_t *expression)
6203 if (warning.unused_value) {
6204 const expression_t *const left = expression->left;
6205 if (!expression_has_effect(left)) {
6206 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6209 expression->base.type = expression->right->base.type;
6212 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6213 static expression_t *parse_##binexpression_type(unsigned precedence, \
6214 expression_t *left) \
6217 source_position_t pos = HERE; \
6219 expression_t *right = parse_sub_expression(precedence + lr); \
6221 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6222 binexpr->base.source_position = pos; \
6223 binexpr->binary.left = left; \
6224 binexpr->binary.right = right; \
6225 sfunc(&binexpr->binary); \
6230 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6231 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6232 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6233 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6234 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6235 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6236 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6237 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6238 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6240 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6241 semantic_comparison, 1)
6242 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6243 semantic_comparison, 1)
6244 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6245 semantic_comparison, 1)
6246 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6247 semantic_comparison, 1)
6249 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6250 semantic_binexpr_arithmetic, 1)
6251 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6252 semantic_binexpr_arithmetic, 1)
6253 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6254 semantic_binexpr_arithmetic, 1)
6255 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6256 semantic_logical_op, 1)
6257 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6258 semantic_logical_op, 1)
6259 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6260 semantic_shift_op, 1)
6261 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6262 semantic_shift_op, 1)
6263 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6264 semantic_arithmetic_addsubb_assign, 0)
6265 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6266 semantic_arithmetic_addsubb_assign, 0)
6267 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6268 semantic_arithmetic_assign, 0)
6269 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6270 semantic_arithmetic_assign, 0)
6271 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6272 semantic_arithmetic_assign, 0)
6273 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6274 semantic_arithmetic_assign, 0)
6275 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6276 semantic_arithmetic_assign, 0)
6277 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6278 semantic_arithmetic_assign, 0)
6279 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6280 semantic_arithmetic_assign, 0)
6281 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6282 semantic_arithmetic_assign, 0)
6284 static expression_t *parse_sub_expression(unsigned precedence)
6286 if(token.type < 0) {
6287 return expected_expression_error();
6290 expression_parser_function_t *parser
6291 = &expression_parsers[token.type];
6292 source_position_t source_position = token.source_position;
6295 if(parser->parser != NULL) {
6296 left = parser->parser(parser->precedence);
6298 left = parse_primary_expression();
6300 assert(left != NULL);
6301 left->base.source_position = source_position;
6304 if(token.type < 0) {
6305 return expected_expression_error();
6308 parser = &expression_parsers[token.type];
6309 if(parser->infix_parser == NULL)
6311 if(parser->infix_precedence < precedence)
6314 left = parser->infix_parser(parser->infix_precedence, left);
6316 assert(left != NULL);
6317 assert(left->kind != EXPR_UNKNOWN);
6318 left->base.source_position = source_position;
6325 * Parse an expression.
6327 static expression_t *parse_expression(void)
6329 return parse_sub_expression(1);
6333 * Register a parser for a prefix-like operator with given precedence.
6335 * @param parser the parser function
6336 * @param token_type the token type of the prefix token
6337 * @param precedence the precedence of the operator
6339 static void register_expression_parser(parse_expression_function parser,
6340 int token_type, unsigned precedence)
6342 expression_parser_function_t *entry = &expression_parsers[token_type];
6344 if(entry->parser != NULL) {
6345 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6346 panic("trying to register multiple expression parsers for a token");
6348 entry->parser = parser;
6349 entry->precedence = precedence;
6353 * Register a parser for an infix operator with given precedence.
6355 * @param parser the parser function
6356 * @param token_type the token type of the infix operator
6357 * @param precedence the precedence of the operator
6359 static void register_infix_parser(parse_expression_infix_function parser,
6360 int token_type, unsigned precedence)
6362 expression_parser_function_t *entry = &expression_parsers[token_type];
6364 if(entry->infix_parser != NULL) {
6365 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6366 panic("trying to register multiple infix expression parsers for a "
6369 entry->infix_parser = parser;
6370 entry->infix_precedence = precedence;
6374 * Initialize the expression parsers.
6376 static void init_expression_parsers(void)
6378 memset(&expression_parsers, 0, sizeof(expression_parsers));
6380 register_infix_parser(parse_array_expression, '[', 30);
6381 register_infix_parser(parse_call_expression, '(', 30);
6382 register_infix_parser(parse_select_expression, '.', 30);
6383 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6384 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6386 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6389 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6390 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6391 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6392 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6393 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6394 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6395 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6396 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6397 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6398 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6399 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6400 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6401 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6402 T_EXCLAMATIONMARKEQUAL, 13);
6403 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6404 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6405 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6406 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6407 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6408 register_infix_parser(parse_conditional_expression, '?', 7);
6409 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6410 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6411 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6412 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6413 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6414 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6415 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6416 T_LESSLESSEQUAL, 2);
6417 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6418 T_GREATERGREATEREQUAL, 2);
6419 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6421 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6423 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6426 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6428 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6429 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6430 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6431 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6432 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6433 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6434 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6436 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6438 register_expression_parser(parse_sizeof, T_sizeof, 25);
6439 register_expression_parser(parse_alignof, T___alignof__, 25);
6440 register_expression_parser(parse_extension, T___extension__, 25);
6441 register_expression_parser(parse_builtin_classify_type,
6442 T___builtin_classify_type, 25);
6446 * Parse a asm statement constraints specification.
6448 static asm_constraint_t *parse_asm_constraints(void)
6450 asm_constraint_t *result = NULL;
6451 asm_constraint_t *last = NULL;
6453 while(token.type == T_STRING_LITERAL || token.type == '[') {
6454 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6455 memset(constraint, 0, sizeof(constraint[0]));
6457 if(token.type == '[') {
6459 if(token.type != T_IDENTIFIER) {
6460 parse_error_expected("while parsing asm constraint",
6464 constraint->symbol = token.v.symbol;
6469 constraint->constraints = parse_string_literals();
6471 constraint->expression = parse_expression();
6475 last->next = constraint;
6477 result = constraint;
6481 if(token.type != ',')
6492 * Parse a asm statement clobber specification.
6494 static asm_clobber_t *parse_asm_clobbers(void)
6496 asm_clobber_t *result = NULL;
6497 asm_clobber_t *last = NULL;
6499 while(token.type == T_STRING_LITERAL) {
6500 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6501 clobber->clobber = parse_string_literals();
6504 last->next = clobber;
6510 if(token.type != ',')
6519 * Parse an asm statement.
6521 static statement_t *parse_asm_statement(void)
6525 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6526 statement->base.source_position = token.source_position;
6528 asm_statement_t *asm_statement = &statement->asms;
6530 if(token.type == T_volatile) {
6532 asm_statement->is_volatile = true;
6536 add_anchor_token(')');
6537 add_anchor_token(':');
6538 asm_statement->asm_text = parse_string_literals();
6540 if(token.type != ':') {
6541 rem_anchor_token(':');
6546 asm_statement->inputs = parse_asm_constraints();
6547 if(token.type != ':') {
6548 rem_anchor_token(':');
6553 asm_statement->outputs = parse_asm_constraints();
6554 if(token.type != ':') {
6555 rem_anchor_token(':');
6558 rem_anchor_token(':');
6561 asm_statement->clobbers = parse_asm_clobbers();
6564 rem_anchor_token(')');
6569 return create_invalid_statement();
6573 * Parse a case statement.
6575 static statement_t *parse_case_statement(void)
6579 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6581 statement->base.source_position = token.source_position;
6582 statement->case_label.expression = parse_expression();
6584 if (c_mode & _GNUC) {
6585 if (token.type == T_DOTDOTDOT) {
6587 statement->case_label.end_range = parse_expression();
6593 if (! is_constant_expression(statement->case_label.expression)) {
6594 errorf(statement->base.source_position,
6595 "case label does not reduce to an integer constant");
6597 /* TODO: check if the case label is already known */
6598 if (current_switch != NULL) {
6599 /* link all cases into the switch statement */
6600 if (current_switch->last_case == NULL) {
6601 current_switch->first_case =
6602 current_switch->last_case = &statement->case_label;
6604 current_switch->last_case->next = &statement->case_label;
6607 errorf(statement->base.source_position,
6608 "case label not within a switch statement");
6611 statement->case_label.statement = parse_statement();
6615 return create_invalid_statement();
6619 * Finds an existing default label of a switch statement.
6621 static case_label_statement_t *
6622 find_default_label(const switch_statement_t *statement)
6624 case_label_statement_t *label = statement->first_case;
6625 for ( ; label != NULL; label = label->next) {
6626 if (label->expression == NULL)
6633 * Parse a default statement.
6635 static statement_t *parse_default_statement(void)
6639 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6641 statement->base.source_position = token.source_position;
6644 if (current_switch != NULL) {
6645 const case_label_statement_t *def_label = find_default_label(current_switch);
6646 if (def_label != NULL) {
6647 errorf(HERE, "multiple default labels in one switch");
6648 errorf(def_label->base.source_position,
6649 "this is the first default label");
6651 /* link all cases into the switch statement */
6652 if (current_switch->last_case == NULL) {
6653 current_switch->first_case =
6654 current_switch->last_case = &statement->case_label;
6656 current_switch->last_case->next = &statement->case_label;
6660 errorf(statement->base.source_position,
6661 "'default' label not within a switch statement");
6663 statement->case_label.statement = parse_statement();
6667 return create_invalid_statement();
6671 * Return the declaration for a given label symbol or create a new one.
6673 static declaration_t *get_label(symbol_t *symbol)
6675 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6676 assert(current_function != NULL);
6677 /* if we found a label in the same function, then we already created the
6679 if(candidate != NULL
6680 && candidate->parent_scope == ¤t_function->scope) {
6684 /* otherwise we need to create a new one */
6685 declaration_t *const declaration = allocate_declaration_zero();
6686 declaration->namespc = NAMESPACE_LABEL;
6687 declaration->symbol = symbol;
6689 label_push(declaration);
6695 * Parse a label statement.
6697 static statement_t *parse_label_statement(void)
6699 assert(token.type == T_IDENTIFIER);
6700 symbol_t *symbol = token.v.symbol;
6703 declaration_t *label = get_label(symbol);
6705 /* if source position is already set then the label is defined twice,
6706 * otherwise it was just mentioned in a goto so far */
6707 if(label->source_position.input_name != NULL) {
6708 errorf(HERE, "duplicate label '%Y'", symbol);
6709 errorf(label->source_position, "previous definition of '%Y' was here",
6712 label->source_position = token.source_position;
6715 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6717 statement->base.source_position = token.source_position;
6718 statement->label.label = label;
6722 if(token.type == '}') {
6723 /* TODO only warn? */
6725 warningf(HERE, "label at end of compound statement");
6726 statement->label.statement = create_empty_statement();
6728 errorf(HERE, "label at end of compound statement");
6729 statement->label.statement = create_invalid_statement();
6733 if (token.type == ';') {
6734 /* eat an empty statement here, to avoid the warning about an empty
6735 * after a label. label:; is commonly used to have a label before
6737 statement->label.statement = create_empty_statement();
6740 statement->label.statement = parse_statement();
6744 /* remember the labels's in a list for later checking */
6745 if (label_last == NULL) {
6746 label_first = &statement->label;
6748 label_last->next = &statement->label;
6750 label_last = &statement->label;
6756 * Parse an if statement.
6758 static statement_t *parse_if(void)
6762 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6763 statement->base.source_position = token.source_position;
6766 add_anchor_token(')');
6767 statement->ifs.condition = parse_expression();
6768 rem_anchor_token(')');
6771 add_anchor_token(T_else);
6772 statement->ifs.true_statement = parse_statement();
6773 rem_anchor_token(T_else);
6775 if(token.type == T_else) {
6777 statement->ifs.false_statement = parse_statement();
6782 return create_invalid_statement();
6786 * Parse a switch statement.
6788 static statement_t *parse_switch(void)
6792 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6793 statement->base.source_position = token.source_position;
6796 expression_t *const expr = parse_expression();
6797 type_t * type = skip_typeref(expr->base.type);
6798 if (is_type_integer(type)) {
6799 type = promote_integer(type);
6800 } else if (is_type_valid(type)) {
6801 errorf(expr->base.source_position,
6802 "switch quantity is not an integer, but '%T'", type);
6803 type = type_error_type;
6805 statement->switchs.expression = create_implicit_cast(expr, type);
6808 switch_statement_t *rem = current_switch;
6809 current_switch = &statement->switchs;
6810 statement->switchs.body = parse_statement();
6811 current_switch = rem;
6813 if (warning.switch_default
6814 && find_default_label(&statement->switchs) == NULL) {
6815 warningf(statement->base.source_position, "switch has no default case");
6820 return create_invalid_statement();
6823 static statement_t *parse_loop_body(statement_t *const loop)
6825 statement_t *const rem = current_loop;
6826 current_loop = loop;
6828 statement_t *const body = parse_statement();
6835 * Parse a while statement.
6837 static statement_t *parse_while(void)
6841 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6842 statement->base.source_position = token.source_position;
6845 add_anchor_token(')');
6846 statement->whiles.condition = parse_expression();
6847 rem_anchor_token(')');
6850 statement->whiles.body = parse_loop_body(statement);
6854 return create_invalid_statement();
6858 * Parse a do statement.
6860 static statement_t *parse_do(void)
6864 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6866 statement->base.source_position = token.source_position;
6868 add_anchor_token(T_while);
6869 statement->do_while.body = parse_loop_body(statement);
6870 rem_anchor_token(T_while);
6874 add_anchor_token(')');
6875 statement->do_while.condition = parse_expression();
6876 rem_anchor_token(')');
6882 return create_invalid_statement();
6886 * Parse a for statement.
6888 static statement_t *parse_for(void)
6892 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6893 statement->base.source_position = token.source_position;
6895 int top = environment_top();
6896 scope_t *last_scope = scope;
6897 set_scope(&statement->fors.scope);
6900 add_anchor_token(')');
6902 if(token.type != ';') {
6903 if(is_declaration_specifier(&token, false)) {
6904 parse_declaration(record_declaration);
6906 expression_t *const init = parse_expression();
6907 statement->fors.initialisation = init;
6908 if (warning.unused_value && !expression_has_effect(init)) {
6909 warningf(init->base.source_position,
6910 "initialisation of 'for'-statement has no effect");
6918 if(token.type != ';') {
6919 statement->fors.condition = parse_expression();
6922 if(token.type != ')') {
6923 expression_t *const step = parse_expression();
6924 statement->fors.step = step;
6925 if (warning.unused_value && !expression_has_effect(step)) {
6926 warningf(step->base.source_position,
6927 "step of 'for'-statement has no effect");
6930 rem_anchor_token(')');
6932 statement->fors.body = parse_loop_body(statement);
6934 assert(scope == &statement->fors.scope);
6935 set_scope(last_scope);
6936 environment_pop_to(top);
6941 rem_anchor_token(')');
6942 assert(scope == &statement->fors.scope);
6943 set_scope(last_scope);
6944 environment_pop_to(top);
6946 return create_invalid_statement();
6950 * Parse a goto statement.
6952 static statement_t *parse_goto(void)
6956 if(token.type != T_IDENTIFIER) {
6957 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6961 symbol_t *symbol = token.v.symbol;
6964 declaration_t *label = get_label(symbol);
6966 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6967 statement->base.source_position = token.source_position;
6969 statement->gotos.label = label;
6971 /* remember the goto's in a list for later checking */
6972 if (goto_last == NULL) {
6973 goto_first = &statement->gotos;
6975 goto_last->next = &statement->gotos;
6977 goto_last = &statement->gotos;
6983 return create_invalid_statement();
6987 * Parse a continue statement.
6989 static statement_t *parse_continue(void)
6991 statement_t *statement;
6992 if (current_loop == NULL) {
6993 errorf(HERE, "continue statement not within loop");
6996 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6998 statement->base.source_position = token.source_position;
7006 return create_invalid_statement();
7010 * Parse a break statement.
7012 static statement_t *parse_break(void)
7014 statement_t *statement;
7015 if (current_switch == NULL && current_loop == NULL) {
7016 errorf(HERE, "break statement not within loop or switch");
7019 statement = allocate_statement_zero(STATEMENT_BREAK);
7021 statement->base.source_position = token.source_position;
7029 return create_invalid_statement();
7033 * Check if a given declaration represents a local variable.
7035 static bool is_local_var_declaration(const declaration_t *declaration) {
7036 switch ((storage_class_tag_t) declaration->storage_class) {
7037 case STORAGE_CLASS_AUTO:
7038 case STORAGE_CLASS_REGISTER: {
7039 const type_t *type = skip_typeref(declaration->type);
7040 if(is_type_function(type)) {
7052 * Check if a given declaration represents a variable.
7054 static bool is_var_declaration(const declaration_t *declaration) {
7055 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7058 const type_t *type = skip_typeref(declaration->type);
7059 return !is_type_function(type);
7063 * Check if a given expression represents a local variable.
7065 static bool is_local_variable(const expression_t *expression)
7067 if (expression->base.kind != EXPR_REFERENCE) {
7070 const declaration_t *declaration = expression->reference.declaration;
7071 return is_local_var_declaration(declaration);
7075 * Check if a given expression represents a local variable and
7076 * return its declaration then, else return NULL.
7078 declaration_t *expr_is_variable(const expression_t *expression)
7080 if (expression->base.kind != EXPR_REFERENCE) {
7083 declaration_t *declaration = expression->reference.declaration;
7084 if (is_var_declaration(declaration))
7090 * Parse a return statement.
7092 static statement_t *parse_return(void)
7096 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7097 statement->base.source_position = token.source_position;
7099 expression_t *return_value = NULL;
7100 if(token.type != ';') {
7101 return_value = parse_expression();
7105 const type_t *const func_type = current_function->type;
7106 assert(is_type_function(func_type));
7107 type_t *const return_type = skip_typeref(func_type->function.return_type);
7109 if(return_value != NULL) {
7110 type_t *return_value_type = skip_typeref(return_value->base.type);
7112 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7113 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7114 warningf(statement->base.source_position,
7115 "'return' with a value, in function returning void");
7116 return_value = NULL;
7118 type_t *const res_type = semantic_assign(return_type,
7119 return_value, "'return'");
7120 if (res_type == NULL) {
7121 errorf(statement->base.source_position,
7122 "cannot return something of type '%T' in function returning '%T'",
7123 return_value->base.type, return_type);
7125 return_value = create_implicit_cast(return_value, res_type);
7128 /* check for returning address of a local var */
7129 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7130 const expression_t *expression = return_value->unary.value;
7131 if (is_local_variable(expression)) {
7132 warningf(statement->base.source_position,
7133 "function returns address of local variable");
7137 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7138 warningf(statement->base.source_position,
7139 "'return' without value, in function returning non-void");
7142 statement->returns.value = return_value;
7146 return create_invalid_statement();
7150 * Parse a declaration statement.
7152 static statement_t *parse_declaration_statement(void)
7154 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7156 statement->base.source_position = token.source_position;
7158 declaration_t *before = last_declaration;
7159 parse_declaration(record_declaration);
7161 if(before == NULL) {
7162 statement->declaration.declarations_begin = scope->declarations;
7164 statement->declaration.declarations_begin = before->next;
7166 statement->declaration.declarations_end = last_declaration;
7172 * Parse an expression statement, ie. expr ';'.
7174 static statement_t *parse_expression_statement(void)
7176 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7178 statement->base.source_position = token.source_position;
7179 expression_t *const expr = parse_expression();
7180 statement->expression.expression = expr;
7182 if (warning.unused_value && !expression_has_effect(expr)) {
7183 warningf(expr->base.source_position, "statement has no effect");
7190 return create_invalid_statement();
7194 * Parse a statement.
7196 static statement_t *parse_statement(void)
7198 statement_t *statement = NULL;
7200 /* declaration or statement */
7201 add_anchor_token(';');
7202 switch(token.type) {
7204 statement = parse_asm_statement();
7208 statement = parse_case_statement();
7212 statement = parse_default_statement();
7216 statement = parse_compound_statement();
7220 statement = parse_if();
7224 statement = parse_switch();
7228 statement = parse_while();
7232 statement = parse_do();
7236 statement = parse_for();
7240 statement = parse_goto();
7244 statement = parse_continue();
7248 statement = parse_break();
7252 statement = parse_return();
7256 if(warning.empty_statement) {
7257 warningf(HERE, "statement is empty");
7259 statement = create_empty_statement();
7264 if(look_ahead(1)->type == ':') {
7265 statement = parse_label_statement();
7269 if(is_typedef_symbol(token.v.symbol)) {
7270 statement = parse_declaration_statement();
7274 statement = parse_expression_statement();
7277 case T___extension__:
7278 /* this can be a prefix to a declaration or an expression statement */
7279 /* we simply eat it now and parse the rest with tail recursion */
7282 } while(token.type == T___extension__);
7283 statement = parse_statement();
7287 statement = parse_declaration_statement();
7291 statement = parse_expression_statement();
7294 rem_anchor_token(';');
7296 assert(statement != NULL
7297 && statement->base.source_position.input_name != NULL);
7303 * Parse a compound statement.
7305 static statement_t *parse_compound_statement(void)
7307 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7309 statement->base.source_position = token.source_position;
7312 add_anchor_token('}');
7314 int top = environment_top();
7315 scope_t *last_scope = scope;
7316 set_scope(&statement->compound.scope);
7318 statement_t *last_statement = NULL;
7320 while(token.type != '}' && token.type != T_EOF) {
7321 statement_t *sub_statement = parse_statement();
7322 if(is_invalid_statement(sub_statement)) {
7323 /* an error occurred. if we are at an anchor, return */
7329 if(last_statement != NULL) {
7330 last_statement->base.next = sub_statement;
7332 statement->compound.statements = sub_statement;
7335 while(sub_statement->base.next != NULL)
7336 sub_statement = sub_statement->base.next;
7338 last_statement = sub_statement;
7341 if(token.type == '}') {
7344 errorf(statement->base.source_position,
7345 "end of file while looking for closing '}'");
7349 rem_anchor_token('}');
7350 assert(scope == &statement->compound.scope);
7351 set_scope(last_scope);
7352 environment_pop_to(top);
7358 * Initialize builtin types.
7360 static void initialize_builtin_types(void)
7362 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7363 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7364 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7365 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7366 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7367 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7368 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7369 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7371 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7372 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7373 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7374 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7378 * Check for unused global static functions and variables
7380 static void check_unused_globals(void)
7382 if (!warning.unused_function && !warning.unused_variable)
7385 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7386 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7389 type_t *const type = decl->type;
7391 if (is_type_function(skip_typeref(type))) {
7392 if (!warning.unused_function || decl->is_inline)
7395 s = (decl->init.statement != NULL ? "defined" : "declared");
7397 if (!warning.unused_variable)
7403 warningf(decl->source_position, "'%#T' %s but not used",
7404 type, decl->symbol, s);
7409 * Parse a translation unit.
7411 static translation_unit_t *parse_translation_unit(void)
7413 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7415 assert(global_scope == NULL);
7416 global_scope = &unit->scope;
7418 assert(scope == NULL);
7419 set_scope(&unit->scope);
7421 initialize_builtin_types();
7423 while(token.type != T_EOF) {
7424 if (token.type == ';') {
7425 /* TODO error in strict mode */
7426 warningf(HERE, "stray ';' outside of function");
7429 parse_external_declaration();
7433 assert(scope == &unit->scope);
7435 last_declaration = NULL;
7437 assert(global_scope == &unit->scope);
7438 check_unused_globals();
7439 global_scope = NULL;
7447 * @return the translation unit or NULL if errors occurred.
7449 translation_unit_t *parse(void)
7451 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7452 label_stack = NEW_ARR_F(stack_entry_t, 0);
7453 diagnostic_count = 0;
7457 type_set_output(stderr);
7458 ast_set_output(stderr);
7460 lookahead_bufpos = 0;
7461 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7464 translation_unit_t *unit = parse_translation_unit();
7466 DEL_ARR_F(environment_stack);
7467 DEL_ARR_F(label_stack);
7473 * Initialize the parser.
7475 void init_parser(void)
7478 /* add predefined symbols for extended-decl-modifier */
7479 sym_align = symbol_table_insert("align");
7480 sym_allocate = symbol_table_insert("allocate");
7481 sym_dllimport = symbol_table_insert("dllimport");
7482 sym_dllexport = symbol_table_insert("dllexport");
7483 sym_naked = symbol_table_insert("naked");
7484 sym_noinline = symbol_table_insert("noinline");
7485 sym_noreturn = symbol_table_insert("noreturn");
7486 sym_nothrow = symbol_table_insert("nothrow");
7487 sym_novtable = symbol_table_insert("novtable");
7488 sym_property = symbol_table_insert("property");
7489 sym_get = symbol_table_insert("get");
7490 sym_put = symbol_table_insert("put");
7491 sym_selectany = symbol_table_insert("selectany");
7492 sym_thread = symbol_table_insert("thread");
7493 sym_uuid = symbol_table_insert("uuid");
7494 sym_deprecated = symbol_table_insert("deprecated");
7495 sym_restrict = symbol_table_insert("restrict");
7496 sym_noalias = symbol_table_insert("noalias");
7498 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7500 init_expression_parsers();
7501 obstack_init(&temp_obst);
7503 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7504 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7508 * Terminate the parser.
7510 void exit_parser(void)
7512 obstack_free(&temp_obst, NULL);