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. */
57 decl_modifiers_t decl_modifiers; /**< MS __declspec extended modifier mask */
58 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
59 symbol_t *get_property_sym; /**< the name of the get property if set. */
60 symbol_t *put_property_sym; /**< the name of the put property if set. */
65 * An environment for parsing initializers (and compound literals).
67 typedef struct parse_initializer_env_t {
68 type_t *type; /**< the type of the initializer. In case of an
69 array type with unspecified size this gets
70 adjusted to the actual size. */
71 declaration_t *declaration; /**< the declaration that is initialized if any */
72 bool must_be_constant;
73 } parse_initializer_env_t;
75 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
78 static token_t lookahead_buffer[MAX_LOOKAHEAD];
79 static int lookahead_bufpos;
80 static stack_entry_t *environment_stack = NULL;
81 static stack_entry_t *label_stack = NULL;
82 static scope_t *global_scope = NULL;
83 static scope_t *scope = NULL;
84 static declaration_t *last_declaration = NULL;
85 static declaration_t *current_function = NULL;
86 static switch_statement_t *current_switch = NULL;
87 static statement_t *current_loop = NULL;
88 static goto_statement_t *goto_first = NULL;
89 static goto_statement_t *goto_last = NULL;
90 static label_statement_t *label_first = NULL;
91 static label_statement_t *label_last = NULL;
92 static struct obstack temp_obst;
94 /* symbols for Microsoft extended-decl-modifier */
95 static const symbol_t *sym_align = NULL;
96 static const symbol_t *sym_allocate = NULL;
97 static const symbol_t *sym_dllimport = NULL;
98 static const symbol_t *sym_dllexport = NULL;
99 static const symbol_t *sym_naked = NULL;
100 static const symbol_t *sym_noinline = NULL;
101 static const symbol_t *sym_noreturn = NULL;
102 static const symbol_t *sym_nothrow = NULL;
103 static const symbol_t *sym_novtable = NULL;
104 static const symbol_t *sym_property = NULL;
105 static const symbol_t *sym_get = NULL;
106 static const symbol_t *sym_put = NULL;
107 static const symbol_t *sym_selectany = NULL;
108 static const symbol_t *sym_thread = NULL;
109 static const symbol_t *sym_uuid = NULL;
110 static const symbol_t *sym_deprecated = NULL;
112 /** The token anchor set */
113 static unsigned char token_anchor_set[T_LAST_TOKEN];
115 /** The current source position. */
116 #define HERE token.source_position
118 static type_t *type_valist;
120 static statement_t *parse_compound_statement(void);
121 static statement_t *parse_statement(void);
123 static expression_t *parse_sub_expression(unsigned precedence);
124 static expression_t *parse_expression(void);
125 static type_t *parse_typename(void);
127 static void parse_compound_type_entries(declaration_t *compound_declaration);
128 static declaration_t *parse_declarator(
129 const declaration_specifiers_t *specifiers, bool may_be_abstract);
130 static declaration_t *record_declaration(declaration_t *declaration);
132 static void semantic_comparison(binary_expression_t *expression);
134 #define STORAGE_CLASSES \
141 #define TYPE_QUALIFIERS \
148 #ifdef PROVIDE_COMPLEX
149 #define COMPLEX_SPECIFIERS \
151 #define IMAGINARY_SPECIFIERS \
154 #define COMPLEX_SPECIFIERS
155 #define IMAGINARY_SPECIFIERS
158 #define TYPE_SPECIFIERS \
173 case T___builtin_va_list: \
177 #define DECLARATION_START \
182 #define TYPENAME_START \
187 * Allocate an AST node with given size and
188 * initialize all fields with zero.
190 static void *allocate_ast_zero(size_t size)
192 void *res = allocate_ast(size);
193 memset(res, 0, size);
197 static declaration_t *allocate_declaration_zero(void)
199 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
200 declaration->type = type_error_type;
201 declaration->alignment = 0;
206 * Returns the size of a statement node.
208 * @param kind the statement kind
210 static size_t get_statement_struct_size(statement_kind_t kind)
212 static const size_t sizes[] = {
213 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
214 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
215 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
216 [STATEMENT_RETURN] = sizeof(return_statement_t),
217 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
218 [STATEMENT_IF] = sizeof(if_statement_t),
219 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
220 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
221 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
222 [STATEMENT_BREAK] = sizeof(statement_base_t),
223 [STATEMENT_GOTO] = sizeof(goto_statement_t),
224 [STATEMENT_LABEL] = sizeof(label_statement_t),
225 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
226 [STATEMENT_WHILE] = sizeof(while_statement_t),
227 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
228 [STATEMENT_FOR] = sizeof(for_statement_t),
229 [STATEMENT_ASM] = sizeof(asm_statement_t)
231 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
232 assert(sizes[kind] != 0);
237 * Allocate a statement node of given kind and initialize all
240 static statement_t *allocate_statement_zero(statement_kind_t kind)
242 size_t size = get_statement_struct_size(kind);
243 statement_t *res = allocate_ast_zero(size);
245 res->base.kind = kind;
250 * Creates a new invalid statement.
252 static statement_t *create_invalid_statement(void)
254 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
255 statement->base.source_position = token.source_position;
260 * Allocate a new empty statement.
262 static statement_t *create_empty_statement(void)
264 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
265 statement->base.source_position = token.source_position;
270 * Returns the size of an expression node.
272 * @param kind the expression kind
274 static size_t get_expression_struct_size(expression_kind_t kind)
276 static const size_t sizes[] = {
277 [EXPR_INVALID] = sizeof(expression_base_t),
278 [EXPR_REFERENCE] = sizeof(reference_expression_t),
279 [EXPR_CONST] = sizeof(const_expression_t),
280 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
281 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
282 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
283 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
284 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
285 [EXPR_CALL] = sizeof(call_expression_t),
286 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
287 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
288 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
289 [EXPR_SELECT] = sizeof(select_expression_t),
290 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
291 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
292 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
293 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
294 [EXPR_FUNCTION] = sizeof(string_literal_expression_t),
295 [EXPR_PRETTY_FUNCTION] = sizeof(string_literal_expression_t),
296 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
297 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
298 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
299 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
300 [EXPR_VA_START] = sizeof(va_start_expression_t),
301 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
302 [EXPR_STATEMENT] = sizeof(statement_expression_t),
304 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
305 return sizes[EXPR_UNARY_FIRST];
307 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
308 return sizes[EXPR_BINARY_FIRST];
310 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
311 assert(sizes[kind] != 0);
316 * Allocate an expression node of given kind and initialize all
319 static expression_t *allocate_expression_zero(expression_kind_t kind)
321 size_t size = get_expression_struct_size(kind);
322 expression_t *res = allocate_ast_zero(size);
324 res->base.kind = kind;
325 res->base.type = type_error_type;
330 * Returns the size of a type node.
332 * @param kind the type kind
334 static size_t get_type_struct_size(type_kind_t kind)
336 static const size_t sizes[] = {
337 [TYPE_ATOMIC] = sizeof(atomic_type_t),
338 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
339 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
340 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
341 [TYPE_ENUM] = sizeof(enum_type_t),
342 [TYPE_FUNCTION] = sizeof(function_type_t),
343 [TYPE_POINTER] = sizeof(pointer_type_t),
344 [TYPE_ARRAY] = sizeof(array_type_t),
345 [TYPE_BUILTIN] = sizeof(builtin_type_t),
346 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
347 [TYPE_TYPEOF] = sizeof(typeof_type_t),
349 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
350 assert(kind <= TYPE_TYPEOF);
351 assert(sizes[kind] != 0);
356 * Allocate a type node of given kind and initialize all
359 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
361 size_t size = get_type_struct_size(kind);
362 type_t *res = obstack_alloc(type_obst, size);
363 memset(res, 0, size);
365 res->base.kind = kind;
366 res->base.source_position = source_position;
371 * Returns the size of an initializer node.
373 * @param kind the initializer kind
375 static size_t get_initializer_size(initializer_kind_t kind)
377 static const size_t sizes[] = {
378 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
379 [INITIALIZER_STRING] = sizeof(initializer_string_t),
380 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
381 [INITIALIZER_LIST] = sizeof(initializer_list_t),
382 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
384 assert(kind < sizeof(sizes) / sizeof(*sizes));
385 assert(sizes[kind] != 0);
390 * Allocate an initializer node of given kind and initialize all
393 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
395 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
402 * Free a type from the type obstack.
404 static void free_type(void *type)
406 obstack_free(type_obst, type);
410 * Returns the index of the top element of the environment stack.
412 static size_t environment_top(void)
414 return ARR_LEN(environment_stack);
418 * Returns the index of the top element of the label stack.
420 static size_t label_top(void)
422 return ARR_LEN(label_stack);
426 * Return the next token.
428 static inline void next_token(void)
430 token = lookahead_buffer[lookahead_bufpos];
431 lookahead_buffer[lookahead_bufpos] = lexer_token;
434 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
437 print_token(stderr, &token);
438 fprintf(stderr, "\n");
443 * Return the next token with a given lookahead.
445 static inline const token_t *look_ahead(int num)
447 assert(num > 0 && num <= MAX_LOOKAHEAD);
448 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
449 return &lookahead_buffer[pos];
453 * Adds a token to the token anchor set (a multi-set).
455 static void add_anchor_token(int token_type) {
456 assert(0 <= token_type && token_type < T_LAST_TOKEN);
457 ++token_anchor_set[token_type];
461 * Remove a token from the token anchor set (a multi-set).
463 static void rem_anchor_token(int token_type) {
464 assert(0 <= token_type && token_type < T_LAST_TOKEN);
465 --token_anchor_set[token_type];
468 static bool at_anchor(void) {
471 return token_anchor_set[token.type];
475 * Eat tokens until a matching token is found.
477 static void eat_until_matching_token(int type) {
478 unsigned parenthesis_count = 0;
479 unsigned brace_count = 0;
480 unsigned bracket_count = 0;
481 int end_token = type;
490 while(token.type != end_token ||
491 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
495 case '(': ++parenthesis_count; break;
496 case '{': ++brace_count; break;
497 case '[': ++bracket_count; break;
499 if(parenthesis_count > 0)
507 if(bracket_count > 0)
518 * Eat input tokens until an anchor is found.
520 static void eat_until_anchor(void) {
521 if(token.type == T_EOF)
523 while(token_anchor_set[token.type] == 0) {
524 if(token.type == '(' || token.type == '{' || token.type == '[')
525 eat_until_matching_token(token.type);
526 if(token.type == T_EOF)
532 static void eat_block(void) {
533 eat_until_matching_token('{');
534 if(token.type == '}')
539 * eat all token until a ';' is reached
540 * or a stop token is found.
542 static void eat_statement(void) {
543 eat_until_matching_token(';');
544 if(token.type == ';')
548 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
551 * Report a parse error because an expected token was not found.
553 static void parse_error_expected(const char *message, ...)
555 if(message != NULL) {
556 errorf(HERE, "%s", message);
559 va_start(ap, message);
560 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
565 * Report a type error.
567 static void type_error(const char *msg, const source_position_t source_position,
570 errorf(source_position, "%s, but found type '%T'", msg, type);
574 * Report an incompatible type.
576 static void type_error_incompatible(const char *msg,
577 const source_position_t source_position, type_t *type1, type_t *type2)
579 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
583 * Expect the the current token is the expected token.
584 * If not, generate an error, eat the current statement,
585 * and goto the end_error label.
587 #define expect(expected) \
589 if(UNLIKELY(token.type != (expected))) { \
590 parse_error_expected(NULL, (expected), 0); \
591 add_anchor_token(expected); \
592 eat_until_anchor(); \
593 rem_anchor_token(expected); \
599 static void set_scope(scope_t *new_scope)
602 scope->last_declaration = last_declaration;
606 last_declaration = new_scope->last_declaration;
610 * Search a symbol in a given namespace and returns its declaration or
611 * NULL if this symbol was not found.
613 static declaration_t *get_declaration(const symbol_t *const symbol,
614 const namespace_t namespc)
616 declaration_t *declaration = symbol->declaration;
617 for( ; declaration != NULL; declaration = declaration->symbol_next) {
618 if(declaration->namespc == namespc)
626 * pushs an environment_entry on the environment stack and links the
627 * corresponding symbol to the new entry
629 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
631 symbol_t *symbol = declaration->symbol;
632 namespace_t namespc = (namespace_t) declaration->namespc;
634 /* replace/add declaration into declaration list of the symbol */
635 declaration_t *iter = symbol->declaration;
637 symbol->declaration = declaration;
639 declaration_t *iter_last = NULL;
640 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
641 /* replace an entry? */
642 if(iter->namespc == namespc) {
643 if(iter_last == NULL) {
644 symbol->declaration = declaration;
646 iter_last->symbol_next = declaration;
648 declaration->symbol_next = iter->symbol_next;
653 assert(iter_last->symbol_next == NULL);
654 iter_last->symbol_next = declaration;
658 /* remember old declaration */
660 entry.symbol = symbol;
661 entry.old_declaration = iter;
662 entry.namespc = (unsigned short) namespc;
663 ARR_APP1(stack_entry_t, *stack_ptr, entry);
666 static void environment_push(declaration_t *declaration)
668 assert(declaration->source_position.input_name != NULL);
669 assert(declaration->parent_scope != NULL);
670 stack_push(&environment_stack, declaration);
673 static void label_push(declaration_t *declaration)
675 declaration->parent_scope = ¤t_function->scope;
676 stack_push(&label_stack, declaration);
680 * pops symbols from the environment stack until @p new_top is the top element
682 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
684 stack_entry_t *stack = *stack_ptr;
685 size_t top = ARR_LEN(stack);
688 assert(new_top <= top);
692 for(i = top; i > new_top; --i) {
693 stack_entry_t *entry = &stack[i - 1];
695 declaration_t *old_declaration = entry->old_declaration;
696 symbol_t *symbol = entry->symbol;
697 namespace_t namespc = (namespace_t)entry->namespc;
699 /* replace/remove declaration */
700 declaration_t *declaration = symbol->declaration;
701 assert(declaration != NULL);
702 if(declaration->namespc == namespc) {
703 if(old_declaration == NULL) {
704 symbol->declaration = declaration->symbol_next;
706 symbol->declaration = old_declaration;
709 declaration_t *iter_last = declaration;
710 declaration_t *iter = declaration->symbol_next;
711 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
712 /* replace an entry? */
713 if(iter->namespc == namespc) {
714 assert(iter_last != NULL);
715 iter_last->symbol_next = old_declaration;
716 if(old_declaration != NULL) {
717 old_declaration->symbol_next = iter->symbol_next;
722 assert(iter != NULL);
726 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
729 static void environment_pop_to(size_t new_top)
731 stack_pop_to(&environment_stack, new_top);
734 static void label_pop_to(size_t new_top)
736 stack_pop_to(&label_stack, new_top);
740 static int get_rank(const type_t *type)
742 assert(!is_typeref(type));
743 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
744 * and esp. footnote 108). However we can't fold constants (yet), so we
745 * can't decide whether unsigned int is possible, while int always works.
746 * (unsigned int would be preferable when possible... for stuff like
747 * struct { enum { ... } bla : 4; } ) */
748 if(type->kind == TYPE_ENUM)
749 return ATOMIC_TYPE_INT;
751 assert(type->kind == TYPE_ATOMIC);
752 return type->atomic.akind;
755 static type_t *promote_integer(type_t *type)
757 if(type->kind == TYPE_BITFIELD)
758 type = type->bitfield.base;
760 if(get_rank(type) < ATOMIC_TYPE_INT)
767 * Create a cast expression.
769 * @param expression the expression to cast
770 * @param dest_type the destination type
772 static expression_t *create_cast_expression(expression_t *expression,
775 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
777 cast->unary.value = expression;
778 cast->base.type = dest_type;
784 * Check if a given expression represents the 0 pointer constant.
786 static bool is_null_pointer_constant(const expression_t *expression)
788 /* skip void* cast */
789 if(expression->kind == EXPR_UNARY_CAST
790 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
791 expression = expression->unary.value;
794 /* TODO: not correct yet, should be any constant integer expression
795 * which evaluates to 0 */
796 if (expression->kind != EXPR_CONST)
799 type_t *const type = skip_typeref(expression->base.type);
800 if (!is_type_integer(type))
803 return expression->conste.v.int_value == 0;
807 * Create an implicit cast expression.
809 * @param expression the expression to cast
810 * @param dest_type the destination type
812 static expression_t *create_implicit_cast(expression_t *expression,
815 type_t *const source_type = expression->base.type;
817 if (source_type == dest_type)
820 return create_cast_expression(expression, dest_type);
823 /** Implements the rules from § 6.5.16.1 */
824 static type_t *semantic_assign(type_t *orig_type_left,
825 const expression_t *const right,
828 type_t *const orig_type_right = right->base.type;
829 type_t *const type_left = skip_typeref(orig_type_left);
830 type_t *const type_right = skip_typeref(orig_type_right);
832 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
833 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
834 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
835 && is_type_pointer(type_right))) {
836 return orig_type_left;
839 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
840 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
841 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
843 /* the left type has all qualifiers from the right type */
844 unsigned missing_qualifiers
845 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
846 if(missing_qualifiers != 0) {
847 errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
848 return orig_type_left;
851 points_to_left = get_unqualified_type(points_to_left);
852 points_to_right = get_unqualified_type(points_to_right);
854 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
855 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
856 return orig_type_left;
859 if (!types_compatible(points_to_left, points_to_right)) {
860 warningf(right->base.source_position,
861 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
862 orig_type_left, context, right, orig_type_right);
865 return orig_type_left;
868 if ((is_type_compound(type_left) && is_type_compound(type_right))
869 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
870 type_t *const unqual_type_left = get_unqualified_type(type_left);
871 type_t *const unqual_type_right = get_unqualified_type(type_right);
872 if (types_compatible(unqual_type_left, unqual_type_right)) {
873 return orig_type_left;
877 if (!is_type_valid(type_left))
880 if (!is_type_valid(type_right))
881 return orig_type_right;
886 static expression_t *parse_constant_expression(void)
888 /* start parsing at precedence 7 (conditional expression) */
889 expression_t *result = parse_sub_expression(7);
891 if(!is_constant_expression(result)) {
892 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
898 static expression_t *parse_assignment_expression(void)
900 /* start parsing at precedence 2 (assignment expression) */
901 return parse_sub_expression(2);
904 static type_t *make_global_typedef(const char *name, type_t *type)
906 symbol_t *const symbol = symbol_table_insert(name);
908 declaration_t *const declaration = allocate_declaration_zero();
909 declaration->namespc = NAMESPACE_NORMAL;
910 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
911 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
912 declaration->type = type;
913 declaration->symbol = symbol;
914 declaration->source_position = builtin_source_position;
916 record_declaration(declaration);
918 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
919 typedef_type->typedeft.declaration = declaration;
924 static string_t parse_string_literals(void)
926 assert(token.type == T_STRING_LITERAL);
927 string_t result = token.v.string;
931 while (token.type == T_STRING_LITERAL) {
932 result = concat_strings(&result, &token.v.string);
939 static void parse_attributes(void)
943 case T___attribute__: {
951 errorf(HERE, "EOF while parsing attribute");
970 if(token.type != T_STRING_LITERAL) {
971 parse_error_expected("while parsing assembler attribute",
973 eat_until_matching_token('(');
976 parse_string_literals();
981 goto attributes_finished;
990 static designator_t *parse_designation(void)
992 designator_t *result = NULL;
993 designator_t *last = NULL;
996 designator_t *designator;
999 designator = allocate_ast_zero(sizeof(designator[0]));
1000 designator->source_position = token.source_position;
1002 add_anchor_token(']');
1003 designator->array_index = parse_constant_expression();
1004 rem_anchor_token(']');
1008 designator = allocate_ast_zero(sizeof(designator[0]));
1009 designator->source_position = token.source_position;
1011 if(token.type != T_IDENTIFIER) {
1012 parse_error_expected("while parsing designator",
1016 designator->symbol = token.v.symbol;
1024 assert(designator != NULL);
1026 last->next = designator;
1028 result = designator;
1036 static initializer_t *initializer_from_string(array_type_t *type,
1037 const string_t *const string)
1039 /* TODO: check len vs. size of array type */
1042 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1043 initializer->string.string = *string;
1048 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1049 wide_string_t *const string)
1051 /* TODO: check len vs. size of array type */
1054 initializer_t *const initializer =
1055 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1056 initializer->wide_string.string = *string;
1062 * Build an initializer from a given expression.
1064 static initializer_t *initializer_from_expression(type_t *orig_type,
1065 expression_t *expression)
1067 /* TODO check that expression is a constant expression */
1069 /* § 6.7.8.14/15 char array may be initialized by string literals */
1070 type_t *type = skip_typeref(orig_type);
1071 type_t *expr_type_orig = expression->base.type;
1072 type_t *expr_type = skip_typeref(expr_type_orig);
1073 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1074 array_type_t *const array_type = &type->array;
1075 type_t *const element_type = skip_typeref(array_type->element_type);
1077 if (element_type->kind == TYPE_ATOMIC) {
1078 atomic_type_kind_t akind = element_type->atomic.akind;
1079 switch (expression->kind) {
1080 case EXPR_STRING_LITERAL:
1081 if (akind == ATOMIC_TYPE_CHAR
1082 || akind == ATOMIC_TYPE_SCHAR
1083 || akind == ATOMIC_TYPE_UCHAR) {
1084 return initializer_from_string(array_type,
1085 &expression->string.value);
1088 case EXPR_WIDE_STRING_LITERAL: {
1089 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1090 if (get_unqualified_type(element_type) == bare_wchar_type) {
1091 return initializer_from_wide_string(array_type,
1092 &expression->wide_string.value);
1102 type_t *const res_type = semantic_assign(type, expression, "initializer");
1103 if (res_type == NULL)
1106 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1107 result->value.value = create_implicit_cast(expression, res_type);
1113 * Checks if a given expression can be used as an constant initializer.
1115 static bool is_initializer_constant(const expression_t *expression)
1117 return is_constant_expression(expression)
1118 || is_address_constant(expression);
1122 * Parses an scalar initializer.
1124 * § 6.7.8.11; eat {} without warning
1126 static initializer_t *parse_scalar_initializer(type_t *type,
1127 bool must_be_constant)
1129 /* there might be extra {} hierarchies */
1131 while(token.type == '{') {
1134 warningf(HERE, "extra curly braces around scalar initializer");
1139 expression_t *expression = parse_assignment_expression();
1140 if(must_be_constant && !is_initializer_constant(expression)) {
1141 errorf(expression->base.source_position,
1142 "Initialisation expression '%E' is not constant\n",
1146 initializer_t *initializer = initializer_from_expression(type, expression);
1148 if(initializer == NULL) {
1149 errorf(expression->base.source_position,
1150 "expression '%E' doesn't match expected type '%T'",
1156 bool additional_warning_displayed = false;
1158 if(token.type == ',') {
1161 if(token.type != '}') {
1162 if(!additional_warning_displayed) {
1163 warningf(HERE, "additional elements in scalar initializer");
1164 additional_warning_displayed = true;
1175 * An entry in the type path.
1177 typedef struct type_path_entry_t type_path_entry_t;
1178 struct type_path_entry_t {
1179 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1181 size_t index; /**< For array types: the current index. */
1182 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1187 * A type path expression a position inside compound or array types.
1189 typedef struct type_path_t type_path_t;
1190 struct type_path_t {
1191 type_path_entry_t *path; /**< An flexible array containing the current path. */
1192 type_t *top_type; /**< type of the element the path points */
1193 size_t max_index; /**< largest index in outermost array */
1197 * Prints a type path for debugging.
1199 static __attribute__((unused)) void debug_print_type_path(
1200 const type_path_t *path)
1202 size_t len = ARR_LEN(path->path);
1204 for(size_t i = 0; i < len; ++i) {
1205 const type_path_entry_t *entry = & path->path[i];
1207 type_t *type = skip_typeref(entry->type);
1208 if(is_type_compound(type)) {
1209 /* in gcc mode structs can have no members */
1210 if(entry->v.compound_entry == NULL) {
1214 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1215 } else if(is_type_array(type)) {
1216 fprintf(stderr, "[%u]", entry->v.index);
1218 fprintf(stderr, "-INVALID-");
1221 if(path->top_type != NULL) {
1222 fprintf(stderr, " (");
1223 print_type(path->top_type);
1224 fprintf(stderr, ")");
1229 * Return the top type path entry, ie. in a path
1230 * (type).a.b returns the b.
1232 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1234 size_t len = ARR_LEN(path->path);
1236 return &path->path[len-1];
1240 * Enlarge the type path by an (empty) element.
1242 static type_path_entry_t *append_to_type_path(type_path_t *path)
1244 size_t len = ARR_LEN(path->path);
1245 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1247 type_path_entry_t *result = & path->path[len];
1248 memset(result, 0, sizeof(result[0]));
1253 * Descending into a sub-type. Enter the scope of the current
1256 static void descend_into_subtype(type_path_t *path)
1258 type_t *orig_top_type = path->top_type;
1259 type_t *top_type = skip_typeref(orig_top_type);
1261 assert(is_type_compound(top_type) || is_type_array(top_type));
1263 type_path_entry_t *top = append_to_type_path(path);
1264 top->type = top_type;
1266 if(is_type_compound(top_type)) {
1267 declaration_t *declaration = top_type->compound.declaration;
1268 declaration_t *entry = declaration->scope.declarations;
1269 top->v.compound_entry = entry;
1272 path->top_type = entry->type;
1274 path->top_type = NULL;
1277 assert(is_type_array(top_type));
1280 path->top_type = top_type->array.element_type;
1285 * Pop an entry from the given type path, ie. returning from
1286 * (type).a.b to (type).a
1288 static void ascend_from_subtype(type_path_t *path)
1290 type_path_entry_t *top = get_type_path_top(path);
1292 path->top_type = top->type;
1294 size_t len = ARR_LEN(path->path);
1295 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1299 * Pop entries from the given type path until the given
1300 * path level is reached.
1302 static void ascend_to(type_path_t *path, size_t top_path_level)
1304 size_t len = ARR_LEN(path->path);
1306 while(len > top_path_level) {
1307 ascend_from_subtype(path);
1308 len = ARR_LEN(path->path);
1312 static bool walk_designator(type_path_t *path, const designator_t *designator,
1313 bool used_in_offsetof)
1315 for( ; designator != NULL; designator = designator->next) {
1316 type_path_entry_t *top = get_type_path_top(path);
1317 type_t *orig_type = top->type;
1319 type_t *type = skip_typeref(orig_type);
1321 if(designator->symbol != NULL) {
1322 symbol_t *symbol = designator->symbol;
1323 if(!is_type_compound(type)) {
1324 if(is_type_valid(type)) {
1325 errorf(designator->source_position,
1326 "'.%Y' designator used for non-compound type '%T'",
1332 declaration_t *declaration = type->compound.declaration;
1333 declaration_t *iter = declaration->scope.declarations;
1334 for( ; iter != NULL; iter = iter->next) {
1335 if(iter->symbol == symbol) {
1340 errorf(designator->source_position,
1341 "'%T' has no member named '%Y'", orig_type, symbol);
1344 if(used_in_offsetof) {
1345 type_t *real_type = skip_typeref(iter->type);
1346 if(real_type->kind == TYPE_BITFIELD) {
1347 errorf(designator->source_position,
1348 "offsetof designator '%Y' may not specify bitfield",
1354 top->type = orig_type;
1355 top->v.compound_entry = iter;
1356 orig_type = iter->type;
1358 expression_t *array_index = designator->array_index;
1359 assert(designator->array_index != NULL);
1361 if(!is_type_array(type)) {
1362 if(is_type_valid(type)) {
1363 errorf(designator->source_position,
1364 "[%E] designator used for non-array type '%T'",
1365 array_index, orig_type);
1369 if(!is_type_valid(array_index->base.type)) {
1373 long index = fold_constant(array_index);
1374 if(!used_in_offsetof) {
1376 errorf(designator->source_position,
1377 "array index [%E] must be positive", array_index);
1380 if(type->array.size_constant == true) {
1381 long array_size = type->array.size;
1382 if(index >= array_size) {
1383 errorf(designator->source_position,
1384 "designator [%E] (%d) exceeds array size %d",
1385 array_index, index, array_size);
1391 top->type = orig_type;
1392 top->v.index = (size_t) index;
1393 orig_type = type->array.element_type;
1395 path->top_type = orig_type;
1397 if(designator->next != NULL) {
1398 descend_into_subtype(path);
1407 static void advance_current_object(type_path_t *path, size_t top_path_level)
1409 type_path_entry_t *top = get_type_path_top(path);
1411 type_t *type = skip_typeref(top->type);
1412 if(is_type_union(type)) {
1413 /* in unions only the first element is initialized */
1414 top->v.compound_entry = NULL;
1415 } else if(is_type_struct(type)) {
1416 declaration_t *entry = top->v.compound_entry;
1418 entry = entry->next;
1419 top->v.compound_entry = entry;
1421 path->top_type = entry->type;
1425 assert(is_type_array(type));
1429 if(!type->array.size_constant || top->v.index < type->array.size) {
1434 /* we're past the last member of the current sub-aggregate, try if we
1435 * can ascend in the type hierarchy and continue with another subobject */
1436 size_t len = ARR_LEN(path->path);
1438 if(len > top_path_level) {
1439 ascend_from_subtype(path);
1440 advance_current_object(path, top_path_level);
1442 path->top_type = NULL;
1447 * skip until token is found.
1449 static void skip_until(int type) {
1450 while(token.type != type) {
1451 if(token.type == T_EOF)
1458 * skip any {...} blocks until a closing braket is reached.
1460 static void skip_initializers(void)
1462 if(token.type == '{')
1465 while(token.type != '}') {
1466 if(token.type == T_EOF)
1468 if(token.type == '{') {
1477 * Parse a part of an initialiser for a struct or union,
1479 static initializer_t *parse_sub_initializer(type_path_t *path,
1480 type_t *outer_type, size_t top_path_level,
1481 parse_initializer_env_t *env)
1483 if(token.type == '}') {
1484 /* empty initializer */
1488 type_t *orig_type = path->top_type;
1489 type_t *type = NULL;
1491 if (orig_type == NULL) {
1492 /* We are initializing an empty compound. */
1494 type = skip_typeref(orig_type);
1496 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1497 * initializers in this case. */
1498 if(!is_type_valid(type)) {
1499 skip_initializers();
1504 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1507 designator_t *designator = NULL;
1508 if(token.type == '.' || token.type == '[') {
1509 designator = parse_designation();
1511 /* reset path to toplevel, evaluate designator from there */
1512 ascend_to(path, top_path_level);
1513 if(!walk_designator(path, designator, false)) {
1514 /* can't continue after designation error */
1518 initializer_t *designator_initializer
1519 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1520 designator_initializer->designator.designator = designator;
1521 ARR_APP1(initializer_t*, initializers, designator_initializer);
1526 if(token.type == '{') {
1527 if(type != NULL && is_type_scalar(type)) {
1528 sub = parse_scalar_initializer(type, env->must_be_constant);
1532 if (env->declaration != NULL)
1533 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1534 env->declaration->symbol);
1536 errorf(HERE, "extra brace group at end of initializer");
1538 descend_into_subtype(path);
1540 add_anchor_token('}');
1541 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1543 rem_anchor_token('}');
1546 ascend_from_subtype(path);
1550 goto error_parse_next;
1554 /* must be an expression */
1555 expression_t *expression = parse_assignment_expression();
1557 if(env->must_be_constant && !is_initializer_constant(expression)) {
1558 errorf(expression->base.source_position,
1559 "Initialisation expression '%E' is not constant\n",
1564 /* we are already outside, ... */
1568 /* handle { "string" } special case */
1569 if((expression->kind == EXPR_STRING_LITERAL
1570 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1571 && outer_type != NULL) {
1572 sub = initializer_from_expression(outer_type, expression);
1574 if(token.type == ',') {
1577 if(token.type != '}') {
1578 warningf(HERE, "excessive elements in initializer for type '%T'",
1581 /* TODO: eat , ... */
1586 /* descend into subtypes until expression matches type */
1588 orig_type = path->top_type;
1589 type = skip_typeref(orig_type);
1591 sub = initializer_from_expression(orig_type, expression);
1595 if(!is_type_valid(type)) {
1598 if(is_type_scalar(type)) {
1599 errorf(expression->base.source_position,
1600 "expression '%E' doesn't match expected type '%T'",
1601 expression, orig_type);
1605 descend_into_subtype(path);
1609 /* update largest index of top array */
1610 const type_path_entry_t *first = &path->path[0];
1611 type_t *first_type = first->type;
1612 first_type = skip_typeref(first_type);
1613 if(is_type_array(first_type)) {
1614 size_t index = first->v.index;
1615 if(index > path->max_index)
1616 path->max_index = index;
1620 /* append to initializers list */
1621 ARR_APP1(initializer_t*, initializers, sub);
1624 if(env->declaration != NULL)
1625 warningf(HERE, "excess elements in struct initializer for '%Y'",
1626 env->declaration->symbol);
1628 warningf(HERE, "excess elements in struct initializer");
1632 if(token.type == '}') {
1636 if(token.type == '}') {
1641 /* advance to the next declaration if we are not at the end */
1642 advance_current_object(path, top_path_level);
1643 orig_type = path->top_type;
1644 if(orig_type != NULL)
1645 type = skip_typeref(orig_type);
1651 size_t len = ARR_LEN(initializers);
1652 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1653 initializer_t *result = allocate_ast_zero(size);
1654 result->kind = INITIALIZER_LIST;
1655 result->list.len = len;
1656 memcpy(&result->list.initializers, initializers,
1657 len * sizeof(initializers[0]));
1659 DEL_ARR_F(initializers);
1660 ascend_to(path, top_path_level);
1665 skip_initializers();
1666 DEL_ARR_F(initializers);
1667 ascend_to(path, top_path_level);
1672 * Parses an initializer. Parsers either a compound literal
1673 * (env->declaration == NULL) or an initializer of a declaration.
1675 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1677 type_t *type = skip_typeref(env->type);
1678 initializer_t *result = NULL;
1681 if(is_type_scalar(type)) {
1682 result = parse_scalar_initializer(type, env->must_be_constant);
1683 } else if(token.type == '{') {
1687 memset(&path, 0, sizeof(path));
1688 path.top_type = env->type;
1689 path.path = NEW_ARR_F(type_path_entry_t, 0);
1691 descend_into_subtype(&path);
1693 add_anchor_token('}');
1694 result = parse_sub_initializer(&path, env->type, 1, env);
1695 rem_anchor_token('}');
1697 max_index = path.max_index;
1698 DEL_ARR_F(path.path);
1702 /* parse_scalar_initializer() also works in this case: we simply
1703 * have an expression without {} around it */
1704 result = parse_scalar_initializer(type, env->must_be_constant);
1707 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1708 * the array type size */
1709 if(is_type_array(type) && type->array.size_expression == NULL
1710 && result != NULL) {
1712 switch (result->kind) {
1713 case INITIALIZER_LIST:
1714 size = max_index + 1;
1717 case INITIALIZER_STRING:
1718 size = result->string.string.size;
1721 case INITIALIZER_WIDE_STRING:
1722 size = result->wide_string.string.size;
1726 panic("invalid initializer type");
1729 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1730 cnst->base.type = type_size_t;
1731 cnst->conste.v.int_value = size;
1733 type_t *new_type = duplicate_type(type);
1735 new_type->array.size_expression = cnst;
1736 new_type->array.size_constant = true;
1737 new_type->array.size = size;
1738 env->type = new_type;
1746 static declaration_t *append_declaration(declaration_t *declaration);
1748 static declaration_t *parse_compound_type_specifier(bool is_struct)
1756 symbol_t *symbol = NULL;
1757 declaration_t *declaration = NULL;
1759 if (token.type == T___attribute__) {
1764 if(token.type == T_IDENTIFIER) {
1765 symbol = token.v.symbol;
1769 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1771 declaration = get_declaration(symbol, NAMESPACE_UNION);
1773 } else if(token.type != '{') {
1775 parse_error_expected("while parsing struct type specifier",
1776 T_IDENTIFIER, '{', 0);
1778 parse_error_expected("while parsing union type specifier",
1779 T_IDENTIFIER, '{', 0);
1785 if(declaration == NULL) {
1786 declaration = allocate_declaration_zero();
1787 declaration->namespc =
1788 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1789 declaration->source_position = token.source_position;
1790 declaration->symbol = symbol;
1791 declaration->parent_scope = scope;
1792 if (symbol != NULL) {
1793 environment_push(declaration);
1795 append_declaration(declaration);
1798 if(token.type == '{') {
1799 if(declaration->init.is_defined) {
1800 assert(symbol != NULL);
1801 errorf(HERE, "multiple definitions of '%s %Y'",
1802 is_struct ? "struct" : "union", symbol);
1803 declaration->scope.declarations = NULL;
1805 declaration->init.is_defined = true;
1807 parse_compound_type_entries(declaration);
1814 static void parse_enum_entries(type_t *const enum_type)
1818 if(token.type == '}') {
1820 errorf(HERE, "empty enum not allowed");
1824 add_anchor_token('}');
1826 if(token.type != T_IDENTIFIER) {
1827 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1829 rem_anchor_token('}');
1833 declaration_t *const entry = allocate_declaration_zero();
1834 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1835 entry->type = enum_type;
1836 entry->symbol = token.v.symbol;
1837 entry->source_position = token.source_position;
1840 if(token.type == '=') {
1842 expression_t *value = parse_constant_expression();
1844 value = create_implicit_cast(value, enum_type);
1845 entry->init.enum_value = value;
1850 record_declaration(entry);
1852 if(token.type != ',')
1855 } while(token.type != '}');
1856 rem_anchor_token('}');
1864 static type_t *parse_enum_specifier(void)
1868 declaration_t *declaration;
1871 if(token.type == T_IDENTIFIER) {
1872 symbol = token.v.symbol;
1875 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1876 } else if(token.type != '{') {
1877 parse_error_expected("while parsing enum type specifier",
1878 T_IDENTIFIER, '{', 0);
1885 if(declaration == NULL) {
1886 declaration = allocate_declaration_zero();
1887 declaration->namespc = NAMESPACE_ENUM;
1888 declaration->source_position = token.source_position;
1889 declaration->symbol = symbol;
1890 declaration->parent_scope = scope;
1893 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1894 type->enumt.declaration = declaration;
1896 if(token.type == '{') {
1897 if(declaration->init.is_defined) {
1898 errorf(HERE, "multiple definitions of enum %Y", symbol);
1900 if (symbol != NULL) {
1901 environment_push(declaration);
1903 append_declaration(declaration);
1904 declaration->init.is_defined = 1;
1906 parse_enum_entries(type);
1914 * if a symbol is a typedef to another type, return true
1916 static bool is_typedef_symbol(symbol_t *symbol)
1918 const declaration_t *const declaration =
1919 get_declaration(symbol, NAMESPACE_NORMAL);
1921 declaration != NULL &&
1922 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1925 static type_t *parse_typeof(void)
1932 add_anchor_token(')');
1934 expression_t *expression = NULL;
1937 switch(token.type) {
1938 case T___extension__:
1939 /* this can be a prefix to a typename or an expression */
1940 /* we simply eat it now. */
1943 } while(token.type == T___extension__);
1947 if(is_typedef_symbol(token.v.symbol)) {
1948 type = parse_typename();
1950 expression = parse_expression();
1951 type = expression->base.type;
1956 type = parse_typename();
1960 expression = parse_expression();
1961 type = expression->base.type;
1965 rem_anchor_token(')');
1968 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1969 typeof_type->typeoft.expression = expression;
1970 typeof_type->typeoft.typeof_type = type;
1978 SPECIFIER_SIGNED = 1 << 0,
1979 SPECIFIER_UNSIGNED = 1 << 1,
1980 SPECIFIER_LONG = 1 << 2,
1981 SPECIFIER_INT = 1 << 3,
1982 SPECIFIER_DOUBLE = 1 << 4,
1983 SPECIFIER_CHAR = 1 << 5,
1984 SPECIFIER_SHORT = 1 << 6,
1985 SPECIFIER_LONG_LONG = 1 << 7,
1986 SPECIFIER_FLOAT = 1 << 8,
1987 SPECIFIER_BOOL = 1 << 9,
1988 SPECIFIER_VOID = 1 << 10,
1989 #ifdef PROVIDE_COMPLEX
1990 SPECIFIER_COMPLEX = 1 << 11,
1991 SPECIFIER_IMAGINARY = 1 << 12,
1995 static type_t *create_builtin_type(symbol_t *const symbol,
1996 type_t *const real_type)
1998 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1999 type->builtin.symbol = symbol;
2000 type->builtin.real_type = real_type;
2002 type_t *result = typehash_insert(type);
2003 if (type != result) {
2010 static type_t *get_typedef_type(symbol_t *symbol)
2012 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2013 if(declaration == NULL
2014 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2017 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2018 type->typedeft.declaration = declaration;
2024 * check for the allowed MS alignment values.
2026 static bool check_elignment_value(long long intvalue) {
2027 if(intvalue < 1 || intvalue > 8192) {
2028 errorf(HERE, "illegal alignment value");
2031 unsigned v = (unsigned)intvalue;
2032 for(unsigned i = 1; i <= 8192; i += i) {
2036 errorf(HERE, "alignment must be power of two");
2040 #define DET_MOD(name, tag) do { \
2041 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2042 *modifiers |= tag; \
2045 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2048 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2050 while(token.type == T_IDENTIFIER) {
2051 symbol = token.v.symbol;
2052 if(symbol == sym_align) {
2055 if(token.type != T_INTEGER)
2057 if(check_elignment_value(token.v.intvalue)) {
2058 if(specifiers->alignment != 0)
2059 warningf(HERE, "align used more than once");
2060 specifiers->alignment = (unsigned char)token.v.intvalue;
2064 } else if(symbol == sym_allocate) {
2067 if(token.type != T_IDENTIFIER)
2069 (void)token.v.symbol;
2071 } else if(symbol == sym_dllimport) {
2073 DET_MOD(dllimport, DM_DLLIMPORT);
2074 } else if(symbol == sym_dllexport) {
2076 DET_MOD(dllexport, DM_DLLEXPORT);
2077 } else if(symbol == sym_thread) {
2079 DET_MOD(thread, DM_THREAD);
2080 } else if(symbol == sym_naked) {
2082 DET_MOD(naked, DM_NAKED);
2083 } else if(symbol == sym_noinline) {
2085 DET_MOD(noinline, DM_NOINLINE);
2086 } else if(symbol == sym_noreturn) {
2088 DET_MOD(noreturn, DM_NORETURN);
2089 } else if(symbol == sym_nothrow) {
2091 DET_MOD(nothrow, DM_NOTHROW);
2092 } else if(symbol == sym_novtable) {
2094 DET_MOD(novtable, DM_NOVTABLE);
2095 } else if(symbol == sym_property) {
2099 bool is_get = false;
2100 if(token.type != T_IDENTIFIER)
2102 if(token.v.symbol == sym_get) {
2104 } else if(token.v.symbol == sym_put) {
2106 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2111 if(token.type != T_IDENTIFIER)
2114 if(specifiers->get_property_sym != NULL) {
2115 errorf(HERE, "get property name already specified");
2117 specifiers->get_property_sym = token.v.symbol;
2120 if(specifiers->put_property_sym != NULL) {
2121 errorf(HERE, "put property name already specified");
2123 specifiers->put_property_sym = token.v.symbol;
2127 if(token.type == ',') {
2134 } else if(symbol == sym_selectany) {
2136 DET_MOD(selectany, DM_SELECTANY);
2137 } else if(symbol == sym_uuid) {
2140 if(token.type != T_STRING_LITERAL)
2144 } else if(symbol == sym_deprecated) {
2146 DET_MOD(deprecated, DM_DEPRECATED);
2147 if(token.type == '(') {
2149 if(token.type == T_STRING_LITERAL) {
2150 specifiers->deprecated_string = token.v.string.begin;
2153 errorf(HERE, "string literal expected");
2158 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2160 if(token.type == '(')
2163 if (token.type == ',')
2170 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2172 type_t *type = NULL;
2173 unsigned type_qualifiers = 0;
2174 unsigned type_specifiers = 0;
2177 specifiers->source_position = token.source_position;
2180 switch(token.type) {
2183 #define MATCH_STORAGE_CLASS(token, class) \
2185 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2186 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2188 specifiers->declared_storage_class = class; \
2192 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2193 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2194 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2195 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2196 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2201 add_anchor_token(')');
2202 parse_microsoft_extended_decl_modifier(specifiers);
2203 rem_anchor_token(')');
2208 switch (specifiers->declared_storage_class) {
2209 case STORAGE_CLASS_NONE:
2210 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2213 case STORAGE_CLASS_EXTERN:
2214 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2217 case STORAGE_CLASS_STATIC:
2218 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2222 errorf(HERE, "multiple storage classes in declaration specifiers");
2228 /* type qualifiers */
2229 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2231 type_qualifiers |= qualifier; \
2235 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2236 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2237 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2239 case T___extension__:
2244 /* type specifiers */
2245 #define MATCH_SPECIFIER(token, specifier, name) \
2248 if(type_specifiers & specifier) { \
2249 errorf(HERE, "multiple " name " type specifiers given"); \
2251 type_specifiers |= specifier; \
2255 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2256 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2257 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2258 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2259 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2260 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2261 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2262 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2263 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2264 #ifdef PROVIDE_COMPLEX
2265 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2266 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2269 /* only in microsoft mode */
2270 specifiers->decl_modifiers |= DM_FORCEINLINE;
2274 specifiers->is_inline = true;
2279 if(type_specifiers & SPECIFIER_LONG_LONG) {
2280 errorf(HERE, "multiple type specifiers given");
2281 } else if(type_specifiers & SPECIFIER_LONG) {
2282 type_specifiers |= SPECIFIER_LONG_LONG;
2284 type_specifiers |= SPECIFIER_LONG;
2289 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2291 type->compound.declaration = parse_compound_type_specifier(true);
2295 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2297 type->compound.declaration = parse_compound_type_specifier(false);
2301 type = parse_enum_specifier();
2304 type = parse_typeof();
2306 case T___builtin_va_list:
2307 type = duplicate_type(type_valist);
2311 case T___attribute__:
2315 case T_IDENTIFIER: {
2316 /* only parse identifier if we haven't found a type yet */
2317 if(type != NULL || type_specifiers != 0)
2318 goto finish_specifiers;
2320 type_t *typedef_type = get_typedef_type(token.v.symbol);
2322 if(typedef_type == NULL)
2323 goto finish_specifiers;
2326 type = typedef_type;
2330 /* function specifier */
2332 goto finish_specifiers;
2339 atomic_type_kind_t atomic_type;
2341 /* match valid basic types */
2342 switch(type_specifiers) {
2343 case SPECIFIER_VOID:
2344 atomic_type = ATOMIC_TYPE_VOID;
2346 case SPECIFIER_CHAR:
2347 atomic_type = ATOMIC_TYPE_CHAR;
2349 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2350 atomic_type = ATOMIC_TYPE_SCHAR;
2352 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2353 atomic_type = ATOMIC_TYPE_UCHAR;
2355 case SPECIFIER_SHORT:
2356 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2357 case SPECIFIER_SHORT | SPECIFIER_INT:
2358 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2359 atomic_type = ATOMIC_TYPE_SHORT;
2361 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2362 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2363 atomic_type = ATOMIC_TYPE_USHORT;
2366 case SPECIFIER_SIGNED:
2367 case SPECIFIER_SIGNED | SPECIFIER_INT:
2368 atomic_type = ATOMIC_TYPE_INT;
2370 case SPECIFIER_UNSIGNED:
2371 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2372 atomic_type = ATOMIC_TYPE_UINT;
2374 case SPECIFIER_LONG:
2375 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2376 case SPECIFIER_LONG | SPECIFIER_INT:
2377 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2378 atomic_type = ATOMIC_TYPE_LONG;
2380 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2381 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2382 atomic_type = ATOMIC_TYPE_ULONG;
2384 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2385 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2386 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2387 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2389 atomic_type = ATOMIC_TYPE_LONGLONG;
2391 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2392 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2394 atomic_type = ATOMIC_TYPE_ULONGLONG;
2396 case SPECIFIER_FLOAT:
2397 atomic_type = ATOMIC_TYPE_FLOAT;
2399 case SPECIFIER_DOUBLE:
2400 atomic_type = ATOMIC_TYPE_DOUBLE;
2402 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2403 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2405 case SPECIFIER_BOOL:
2406 atomic_type = ATOMIC_TYPE_BOOL;
2408 #ifdef PROVIDE_COMPLEX
2409 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2410 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2412 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2413 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2415 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2416 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2418 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2419 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2421 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2422 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2424 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2425 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2429 /* invalid specifier combination, give an error message */
2430 if(type_specifiers == 0) {
2431 if (! strict_mode) {
2432 if (warning.implicit_int) {
2433 warningf(HERE, "no type specifiers in declaration, using 'int'");
2435 atomic_type = ATOMIC_TYPE_INT;
2438 errorf(HERE, "no type specifiers given in declaration");
2440 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2441 (type_specifiers & SPECIFIER_UNSIGNED)) {
2442 errorf(HERE, "signed and unsigned specifiers gives");
2443 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2444 errorf(HERE, "only integer types can be signed or unsigned");
2446 errorf(HERE, "multiple datatypes in declaration");
2448 atomic_type = ATOMIC_TYPE_INVALID;
2451 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2452 type->atomic.akind = atomic_type;
2455 if(type_specifiers != 0) {
2456 errorf(HERE, "multiple datatypes in declaration");
2460 type->base.qualifiers = type_qualifiers;
2462 type_t *result = typehash_insert(type);
2463 if(newtype && result != type) {
2467 specifiers->type = result;
2472 static type_qualifiers_t parse_type_qualifiers(void)
2474 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2477 switch(token.type) {
2478 /* type qualifiers */
2479 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2480 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2481 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2484 return type_qualifiers;
2489 static declaration_t *parse_identifier_list(void)
2491 declaration_t *declarations = NULL;
2492 declaration_t *last_declaration = NULL;
2494 declaration_t *const declaration = allocate_declaration_zero();
2495 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2496 declaration->source_position = token.source_position;
2497 declaration->symbol = token.v.symbol;
2500 if(last_declaration != NULL) {
2501 last_declaration->next = declaration;
2503 declarations = declaration;
2505 last_declaration = declaration;
2507 if(token.type != ',')
2510 } while(token.type == T_IDENTIFIER);
2512 return declarations;
2515 static void semantic_parameter(declaration_t *declaration)
2517 /* TODO: improve error messages */
2519 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2520 errorf(HERE, "typedef not allowed in parameter list");
2521 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2522 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2523 errorf(HERE, "parameter may only have none or register storage class");
2526 type_t *const orig_type = declaration->type;
2527 type_t * type = skip_typeref(orig_type);
2529 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2530 * into a pointer. § 6.7.5.3 (7) */
2531 if (is_type_array(type)) {
2532 type_t *const element_type = type->array.element_type;
2534 type = make_pointer_type(element_type, type->base.qualifiers);
2536 declaration->type = type;
2539 if(is_type_incomplete(type)) {
2540 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2541 orig_type, declaration->symbol);
2545 static declaration_t *parse_parameter(void)
2547 declaration_specifiers_t specifiers;
2548 memset(&specifiers, 0, sizeof(specifiers));
2550 parse_declaration_specifiers(&specifiers);
2552 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2554 semantic_parameter(declaration);
2559 static declaration_t *parse_parameters(function_type_t *type)
2561 if(token.type == T_IDENTIFIER) {
2562 symbol_t *symbol = token.v.symbol;
2563 if(!is_typedef_symbol(symbol)) {
2564 type->kr_style_parameters = true;
2565 return parse_identifier_list();
2569 if(token.type == ')') {
2570 type->unspecified_parameters = 1;
2573 if(token.type == T_void && look_ahead(1)->type == ')') {
2578 declaration_t *declarations = NULL;
2579 declaration_t *declaration;
2580 declaration_t *last_declaration = NULL;
2581 function_parameter_t *parameter;
2582 function_parameter_t *last_parameter = NULL;
2585 switch(token.type) {
2589 return declarations;
2592 case T___extension__:
2594 declaration = parse_parameter();
2596 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2597 memset(parameter, 0, sizeof(parameter[0]));
2598 parameter->type = declaration->type;
2600 if(last_parameter != NULL) {
2601 last_declaration->next = declaration;
2602 last_parameter->next = parameter;
2604 type->parameters = parameter;
2605 declarations = declaration;
2607 last_parameter = parameter;
2608 last_declaration = declaration;
2612 return declarations;
2614 if(token.type != ',')
2615 return declarations;
2625 } construct_type_kind_t;
2627 typedef struct construct_type_t construct_type_t;
2628 struct construct_type_t {
2629 construct_type_kind_t kind;
2630 construct_type_t *next;
2633 typedef struct parsed_pointer_t parsed_pointer_t;
2634 struct parsed_pointer_t {
2635 construct_type_t construct_type;
2636 type_qualifiers_t type_qualifiers;
2639 typedef struct construct_function_type_t construct_function_type_t;
2640 struct construct_function_type_t {
2641 construct_type_t construct_type;
2642 type_t *function_type;
2645 typedef struct parsed_array_t parsed_array_t;
2646 struct parsed_array_t {
2647 construct_type_t construct_type;
2648 type_qualifiers_t type_qualifiers;
2654 typedef struct construct_base_type_t construct_base_type_t;
2655 struct construct_base_type_t {
2656 construct_type_t construct_type;
2660 static construct_type_t *parse_pointer_declarator(void)
2664 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2665 memset(pointer, 0, sizeof(pointer[0]));
2666 pointer->construct_type.kind = CONSTRUCT_POINTER;
2667 pointer->type_qualifiers = parse_type_qualifiers();
2669 return (construct_type_t*) pointer;
2672 static construct_type_t *parse_array_declarator(void)
2675 add_anchor_token(']');
2677 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2678 memset(array, 0, sizeof(array[0]));
2679 array->construct_type.kind = CONSTRUCT_ARRAY;
2681 if(token.type == T_static) {
2682 array->is_static = true;
2686 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2687 if(type_qualifiers != 0) {
2688 if(token.type == T_static) {
2689 array->is_static = true;
2693 array->type_qualifiers = type_qualifiers;
2695 if(token.type == '*' && look_ahead(1)->type == ']') {
2696 array->is_variable = true;
2698 } else if(token.type != ']') {
2699 array->size = parse_assignment_expression();
2702 rem_anchor_token(']');
2705 return (construct_type_t*) array;
2710 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2713 add_anchor_token(')');
2716 if(declaration != NULL) {
2717 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2719 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2722 declaration_t *parameters = parse_parameters(&type->function);
2723 if(declaration != NULL) {
2724 declaration->scope.declarations = parameters;
2727 construct_function_type_t *construct_function_type =
2728 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2729 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2730 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2731 construct_function_type->function_type = type;
2733 rem_anchor_token(')');
2737 return (construct_type_t*) construct_function_type;
2740 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2741 bool may_be_abstract)
2743 /* construct a single linked list of construct_type_t's which describe
2744 * how to construct the final declarator type */
2745 construct_type_t *first = NULL;
2746 construct_type_t *last = NULL;
2749 while(token.type == '*') {
2750 construct_type_t *type = parse_pointer_declarator();
2761 /* TODO: find out if this is correct */
2764 construct_type_t *inner_types = NULL;
2766 switch(token.type) {
2768 if(declaration == NULL) {
2769 errorf(HERE, "no identifier expected in typename");
2771 declaration->symbol = token.v.symbol;
2772 declaration->source_position = token.source_position;
2778 add_anchor_token(')');
2779 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2780 rem_anchor_token(')');
2786 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2787 /* avoid a loop in the outermost scope, because eat_statement doesn't
2789 if(token.type == '}' && current_function == NULL) {
2797 construct_type_t *p = last;
2800 construct_type_t *type;
2801 switch(token.type) {
2803 type = parse_function_declarator(declaration);
2806 type = parse_array_declarator();
2809 goto declarator_finished;
2812 /* insert in the middle of the list (behind p) */
2814 type->next = p->next;
2825 declarator_finished:
2828 /* append inner_types at the end of the list, we don't to set last anymore
2829 * as it's not needed anymore */
2831 assert(first == NULL);
2832 first = inner_types;
2834 last->next = inner_types;
2842 static type_t *construct_declarator_type(construct_type_t *construct_list,
2845 construct_type_t *iter = construct_list;
2846 for( ; iter != NULL; iter = iter->next) {
2847 switch(iter->kind) {
2848 case CONSTRUCT_INVALID:
2849 panic("invalid type construction found");
2850 case CONSTRUCT_FUNCTION: {
2851 construct_function_type_t *construct_function_type
2852 = (construct_function_type_t*) iter;
2854 type_t *function_type = construct_function_type->function_type;
2856 function_type->function.return_type = type;
2858 type_t *skipped_return_type = skip_typeref(type);
2859 if (is_type_function(skipped_return_type)) {
2860 errorf(HERE, "function returning function is not allowed");
2861 type = type_error_type;
2862 } else if (is_type_array(skipped_return_type)) {
2863 errorf(HERE, "function returning array is not allowed");
2864 type = type_error_type;
2866 type = function_type;
2871 case CONSTRUCT_POINTER: {
2872 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2873 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2874 pointer_type->pointer.points_to = type;
2875 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2877 type = pointer_type;
2881 case CONSTRUCT_ARRAY: {
2882 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2883 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2885 expression_t *size_expression = parsed_array->size;
2886 if(size_expression != NULL) {
2888 = create_implicit_cast(size_expression, type_size_t);
2891 array_type->base.qualifiers = parsed_array->type_qualifiers;
2892 array_type->array.element_type = type;
2893 array_type->array.is_static = parsed_array->is_static;
2894 array_type->array.is_variable = parsed_array->is_variable;
2895 array_type->array.size_expression = size_expression;
2897 if(size_expression != NULL) {
2898 if(is_constant_expression(size_expression)) {
2899 array_type->array.size_constant = true;
2900 array_type->array.size
2901 = fold_constant(size_expression);
2903 array_type->array.is_vla = true;
2907 type_t *skipped_type = skip_typeref(type);
2908 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2909 errorf(HERE, "array of void is not allowed");
2910 type = type_error_type;
2918 type_t *hashed_type = typehash_insert(type);
2919 if(hashed_type != type) {
2920 /* the function type was constructed earlier freeing it here will
2921 * destroy other types... */
2922 if(iter->kind != CONSTRUCT_FUNCTION) {
2932 static declaration_t *parse_declarator(
2933 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2935 declaration_t *const declaration = allocate_declaration_zero();
2936 declaration->declared_storage_class = specifiers->declared_storage_class;
2937 declaration->modifiers = specifiers->decl_modifiers;
2938 declaration->deprecated_string = specifiers->deprecated_string;
2939 declaration->get_property_sym = specifiers->get_property_sym;
2940 declaration->put_property_sym = specifiers->put_property_sym;
2941 declaration->is_inline = specifiers->is_inline;
2943 declaration->storage_class = specifiers->declared_storage_class;
2944 if(declaration->storage_class == STORAGE_CLASS_NONE
2945 && scope != global_scope) {
2946 declaration->storage_class = STORAGE_CLASS_AUTO;
2949 if(specifiers->alignment != 0) {
2950 /* TODO: add checks here */
2951 declaration->alignment = specifiers->alignment;
2954 construct_type_t *construct_type
2955 = parse_inner_declarator(declaration, may_be_abstract);
2956 type_t *const type = specifiers->type;
2957 declaration->type = construct_declarator_type(construct_type, type);
2959 if(construct_type != NULL) {
2960 obstack_free(&temp_obst, construct_type);
2966 static type_t *parse_abstract_declarator(type_t *base_type)
2968 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2970 type_t *result = construct_declarator_type(construct_type, base_type);
2971 if(construct_type != NULL) {
2972 obstack_free(&temp_obst, construct_type);
2978 static declaration_t *append_declaration(declaration_t* const declaration)
2980 if (last_declaration != NULL) {
2981 last_declaration->next = declaration;
2983 scope->declarations = declaration;
2985 last_declaration = declaration;
2990 * Check if the declaration of main is suspicious. main should be a
2991 * function with external linkage, returning int, taking either zero
2992 * arguments, two, or three arguments of appropriate types, ie.
2994 * int main([ int argc, char **argv [, char **env ] ]).
2996 * @param decl the declaration to check
2997 * @param type the function type of the declaration
2999 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3001 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3002 warningf(decl->source_position, "'main' is normally a non-static function");
3004 if (skip_typeref(func_type->return_type) != type_int) {
3005 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3007 const function_parameter_t *parm = func_type->parameters;
3009 type_t *const first_type = parm->type;
3010 if (!types_compatible(skip_typeref(first_type), type_int)) {
3011 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3015 type_t *const second_type = parm->type;
3016 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3017 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3021 type_t *const third_type = parm->type;
3022 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3023 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3027 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3031 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3037 * Check if a symbol is the equal to "main".
3039 static bool is_sym_main(const symbol_t *const sym)
3041 return strcmp(sym->string, "main") == 0;
3044 static declaration_t *internal_record_declaration(
3045 declaration_t *const declaration,
3046 const bool is_function_definition)
3048 const symbol_t *const symbol = declaration->symbol;
3049 const namespace_t namespc = (namespace_t)declaration->namespc;
3051 type_t *const orig_type = declaration->type;
3052 type_t *const type = skip_typeref(orig_type);
3053 if (is_type_function(type) &&
3054 type->function.unspecified_parameters &&
3055 warning.strict_prototypes) {
3056 warningf(declaration->source_position,
3057 "function declaration '%#T' is not a prototype",
3058 orig_type, declaration->symbol);
3061 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3062 check_type_of_main(declaration, &type->function);
3065 assert(declaration->symbol != NULL);
3066 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3068 assert(declaration != previous_declaration);
3069 if (previous_declaration != NULL) {
3070 if (previous_declaration->parent_scope == scope) {
3071 /* can happen for K&R style declarations */
3072 if(previous_declaration->type == NULL) {
3073 previous_declaration->type = declaration->type;
3076 const type_t *prev_type = skip_typeref(previous_declaration->type);
3077 if (!types_compatible(type, prev_type)) {
3078 errorf(declaration->source_position,
3079 "declaration '%#T' is incompatible with "
3080 "previous declaration '%#T'",
3081 orig_type, symbol, previous_declaration->type, symbol);
3082 errorf(previous_declaration->source_position,
3083 "previous declaration of '%Y' was here", symbol);
3085 unsigned old_storage_class = previous_declaration->storage_class;
3086 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3087 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3088 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3089 return previous_declaration;
3092 unsigned new_storage_class = declaration->storage_class;
3094 if(is_type_incomplete(prev_type)) {
3095 previous_declaration->type = type;
3099 /* pretend no storage class means extern for function
3100 * declarations (except if the previous declaration is neither
3101 * none nor extern) */
3102 if (is_type_function(type)) {
3103 switch (old_storage_class) {
3104 case STORAGE_CLASS_NONE:
3105 old_storage_class = STORAGE_CLASS_EXTERN;
3107 case STORAGE_CLASS_EXTERN:
3108 if (is_function_definition) {
3109 if (warning.missing_prototypes &&
3110 prev_type->function.unspecified_parameters &&
3111 !is_sym_main(symbol)) {
3112 warningf(declaration->source_position,
3113 "no previous prototype for '%#T'",
3116 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3117 new_storage_class = STORAGE_CLASS_EXTERN;
3125 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3126 new_storage_class == STORAGE_CLASS_EXTERN) {
3127 warn_redundant_declaration:
3128 if (warning.redundant_decls) {
3129 warningf(declaration->source_position,
3130 "redundant declaration for '%Y'", symbol);
3131 warningf(previous_declaration->source_position,
3132 "previous declaration of '%Y' was here",
3135 } else if (current_function == NULL) {
3136 if (old_storage_class != STORAGE_CLASS_STATIC &&
3137 new_storage_class == STORAGE_CLASS_STATIC) {
3138 errorf(declaration->source_position,
3139 "static declaration of '%Y' follows non-static declaration",
3141 errorf(previous_declaration->source_position,
3142 "previous declaration of '%Y' was here", symbol);
3144 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3145 goto warn_redundant_declaration;
3147 if (new_storage_class == STORAGE_CLASS_NONE) {
3148 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3149 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3153 if (old_storage_class == new_storage_class) {
3154 errorf(declaration->source_position,
3155 "redeclaration of '%Y'", symbol);
3157 errorf(declaration->source_position,
3158 "redeclaration of '%Y' with different linkage",
3161 errorf(previous_declaration->source_position,
3162 "previous declaration of '%Y' was here", symbol);
3165 return previous_declaration;
3167 } else if (is_function_definition) {
3168 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3169 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3170 warningf(declaration->source_position,
3171 "no previous prototype for '%#T'", orig_type, symbol);
3172 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3173 warningf(declaration->source_position,
3174 "no previous declaration for '%#T'", orig_type,
3178 } else if (warning.missing_declarations &&
3179 scope == global_scope &&
3180 !is_type_function(type) && (
3181 declaration->storage_class == STORAGE_CLASS_NONE ||
3182 declaration->storage_class == STORAGE_CLASS_THREAD
3184 warningf(declaration->source_position,
3185 "no previous declaration for '%#T'", orig_type, symbol);
3188 assert(declaration->parent_scope == NULL);
3189 assert(scope != NULL);
3191 declaration->parent_scope = scope;
3193 environment_push(declaration);
3194 return append_declaration(declaration);
3197 static declaration_t *record_declaration(declaration_t *declaration)
3199 return internal_record_declaration(declaration, false);
3202 static declaration_t *record_function_definition(declaration_t *declaration)
3204 return internal_record_declaration(declaration, true);
3207 static void parser_error_multiple_definition(declaration_t *declaration,
3208 const source_position_t source_position)
3210 errorf(source_position, "multiple definition of symbol '%Y'",
3211 declaration->symbol);
3212 errorf(declaration->source_position,
3213 "this is the location of the previous definition.");
3216 static bool is_declaration_specifier(const token_t *token,
3217 bool only_type_specifiers)
3219 switch(token->type) {
3223 return is_typedef_symbol(token->v.symbol);
3225 case T___extension__:
3228 return !only_type_specifiers;
3235 static void parse_init_declarator_rest(declaration_t *declaration)
3239 type_t *orig_type = declaration->type;
3240 type_t *type = skip_typeref(orig_type);
3242 if(declaration->init.initializer != NULL) {
3243 parser_error_multiple_definition(declaration, token.source_position);
3246 bool must_be_constant = false;
3247 if(declaration->storage_class == STORAGE_CLASS_STATIC
3248 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3249 || declaration->parent_scope == global_scope) {
3250 must_be_constant = true;
3253 parse_initializer_env_t env;
3254 env.type = orig_type;
3255 env.must_be_constant = must_be_constant;
3256 env.declaration = declaration;
3258 initializer_t *initializer = parse_initializer(&env);
3260 if(env.type != orig_type) {
3261 orig_type = env.type;
3262 type = skip_typeref(orig_type);
3263 declaration->type = env.type;
3266 if(is_type_function(type)) {
3267 errorf(declaration->source_position,
3268 "initializers not allowed for function types at declator '%Y' (type '%T')",
3269 declaration->symbol, orig_type);
3271 declaration->init.initializer = initializer;
3275 /* parse rest of a declaration without any declarator */
3276 static void parse_anonymous_declaration_rest(
3277 const declaration_specifiers_t *specifiers,
3278 parsed_declaration_func finished_declaration)
3282 declaration_t *const declaration = allocate_declaration_zero();
3283 declaration->type = specifiers->type;
3284 declaration->declared_storage_class = specifiers->declared_storage_class;
3285 declaration->source_position = specifiers->source_position;
3286 declaration->modifiers = specifiers->decl_modifiers;
3288 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3289 warningf(declaration->source_position, "useless storage class in empty declaration");
3291 declaration->storage_class = STORAGE_CLASS_NONE;
3293 type_t *type = declaration->type;
3294 switch (type->kind) {
3295 case TYPE_COMPOUND_STRUCT:
3296 case TYPE_COMPOUND_UNION: {
3297 if (type->compound.declaration->symbol == NULL) {
3298 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3307 warningf(declaration->source_position, "empty declaration");
3311 finished_declaration(declaration);
3314 static void parse_declaration_rest(declaration_t *ndeclaration,
3315 const declaration_specifiers_t *specifiers,
3316 parsed_declaration_func finished_declaration)
3318 add_anchor_token(';');
3319 add_anchor_token('=');
3320 add_anchor_token(',');
3322 declaration_t *declaration = finished_declaration(ndeclaration);
3324 type_t *orig_type = declaration->type;
3325 type_t *type = skip_typeref(orig_type);
3327 if (type->kind != TYPE_FUNCTION &&
3328 declaration->is_inline &&
3329 is_type_valid(type)) {
3330 warningf(declaration->source_position,
3331 "variable '%Y' declared 'inline'\n", declaration->symbol);
3334 if(token.type == '=') {
3335 parse_init_declarator_rest(declaration);
3338 if(token.type != ',')
3342 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3347 rem_anchor_token(';');
3348 rem_anchor_token('=');
3349 rem_anchor_token(',');
3352 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3354 symbol_t *symbol = declaration->symbol;
3355 if(symbol == NULL) {
3356 errorf(HERE, "anonymous declaration not valid as function parameter");
3359 namespace_t namespc = (namespace_t) declaration->namespc;
3360 if(namespc != NAMESPACE_NORMAL) {
3361 return record_declaration(declaration);
3364 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3365 if(previous_declaration == NULL ||
3366 previous_declaration->parent_scope != scope) {
3367 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3372 if(previous_declaration->type == NULL) {
3373 previous_declaration->type = declaration->type;
3374 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3375 previous_declaration->storage_class = declaration->storage_class;
3376 previous_declaration->parent_scope = scope;
3377 return previous_declaration;
3379 return record_declaration(declaration);
3383 static void parse_declaration(parsed_declaration_func finished_declaration)
3385 declaration_specifiers_t specifiers;
3386 memset(&specifiers, 0, sizeof(specifiers));
3387 parse_declaration_specifiers(&specifiers);
3389 if(token.type == ';') {
3390 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3392 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3393 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3397 static void parse_kr_declaration_list(declaration_t *declaration)
3399 type_t *type = skip_typeref(declaration->type);
3400 if(!is_type_function(type))
3403 if(!type->function.kr_style_parameters)
3406 /* push function parameters */
3407 int top = environment_top();
3408 scope_t *last_scope = scope;
3409 set_scope(&declaration->scope);
3411 declaration_t *parameter = declaration->scope.declarations;
3412 for( ; parameter != NULL; parameter = parameter->next) {
3413 assert(parameter->parent_scope == NULL);
3414 parameter->parent_scope = scope;
3415 environment_push(parameter);
3418 /* parse declaration list */
3419 while(is_declaration_specifier(&token, false)) {
3420 parse_declaration(finished_kr_declaration);
3423 /* pop function parameters */
3424 assert(scope == &declaration->scope);
3425 set_scope(last_scope);
3426 environment_pop_to(top);
3428 /* update function type */
3429 type_t *new_type = duplicate_type(type);
3430 new_type->function.kr_style_parameters = false;
3432 function_parameter_t *parameters = NULL;
3433 function_parameter_t *last_parameter = NULL;
3435 declaration_t *parameter_declaration = declaration->scope.declarations;
3436 for( ; parameter_declaration != NULL;
3437 parameter_declaration = parameter_declaration->next) {
3438 type_t *parameter_type = parameter_declaration->type;
3439 if(parameter_type == NULL) {
3441 errorf(HERE, "no type specified for function parameter '%Y'",
3442 parameter_declaration->symbol);
3444 if (warning.implicit_int) {
3445 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3446 parameter_declaration->symbol);
3448 parameter_type = type_int;
3449 parameter_declaration->type = parameter_type;
3453 semantic_parameter(parameter_declaration);
3454 parameter_type = parameter_declaration->type;
3456 function_parameter_t *function_parameter
3457 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3458 memset(function_parameter, 0, sizeof(function_parameter[0]));
3460 function_parameter->type = parameter_type;
3461 if(last_parameter != NULL) {
3462 last_parameter->next = function_parameter;
3464 parameters = function_parameter;
3466 last_parameter = function_parameter;
3468 new_type->function.parameters = parameters;
3470 type = typehash_insert(new_type);
3471 if(type != new_type) {
3472 obstack_free(type_obst, new_type);
3475 declaration->type = type;
3478 static bool first_err = true;
3481 * When called with first_err set, prints the name of the current function,
3484 static void print_in_function(void) {
3487 diagnosticf("%s: In function '%Y':\n",
3488 current_function->source_position.input_name,
3489 current_function->symbol);
3494 * Check if all labels are defined in the current function.
3495 * Check if all labels are used in the current function.
3497 static void check_labels(void)
3499 for (const goto_statement_t *goto_statement = goto_first;
3500 goto_statement != NULL;
3501 goto_statement = goto_statement->next) {
3502 declaration_t *label = goto_statement->label;
3505 if (label->source_position.input_name == NULL) {
3506 print_in_function();
3507 errorf(goto_statement->base.source_position,
3508 "label '%Y' used but not defined", label->symbol);
3511 goto_first = goto_last = NULL;
3513 if (warning.unused_label) {
3514 for (const label_statement_t *label_statement = label_first;
3515 label_statement != NULL;
3516 label_statement = label_statement->next) {
3517 const declaration_t *label = label_statement->label;
3519 if (! label->used) {
3520 print_in_function();
3521 warningf(label_statement->base.source_position,
3522 "label '%Y' defined but not used", label->symbol);
3526 label_first = label_last = NULL;
3530 * Check declarations of current_function for unused entities.
3532 static void check_declarations(void)
3534 if (warning.unused_parameter) {
3535 const scope_t *scope = ¤t_function->scope;
3537 const declaration_t *parameter = scope->declarations;
3538 for (; parameter != NULL; parameter = parameter->next) {
3539 if (! parameter->used) {
3540 print_in_function();
3541 warningf(parameter->source_position,
3542 "unused parameter '%Y'", parameter->symbol);
3546 if (warning.unused_variable) {
3550 static void parse_external_declaration(void)
3552 /* function-definitions and declarations both start with declaration
3554 declaration_specifiers_t specifiers;
3555 memset(&specifiers, 0, sizeof(specifiers));
3557 add_anchor_token(';');
3558 parse_declaration_specifiers(&specifiers);
3559 rem_anchor_token(';');
3561 /* must be a declaration */
3562 if(token.type == ';') {
3563 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3567 add_anchor_token(',');
3568 add_anchor_token('=');
3569 rem_anchor_token(';');
3571 /* declarator is common to both function-definitions and declarations */
3572 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3574 rem_anchor_token(',');
3575 rem_anchor_token('=');
3576 rem_anchor_token(';');
3578 /* must be a declaration */
3579 if(token.type == ',' || token.type == '=' || token.type == ';') {
3580 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3584 /* must be a function definition */
3585 parse_kr_declaration_list(ndeclaration);
3587 if(token.type != '{') {
3588 parse_error_expected("while parsing function definition", '{', 0);
3589 eat_until_matching_token(';');
3593 type_t *type = ndeclaration->type;
3595 /* note that we don't skip typerefs: the standard doesn't allow them here
3596 * (so we can't use is_type_function here) */
3597 if(type->kind != TYPE_FUNCTION) {
3598 if (is_type_valid(type)) {
3599 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3600 type, ndeclaration->symbol);
3606 /* § 6.7.5.3 (14) a function definition with () means no
3607 * parameters (and not unspecified parameters) */
3608 if(type->function.unspecified_parameters) {
3609 type_t *duplicate = duplicate_type(type);
3610 duplicate->function.unspecified_parameters = false;
3612 type = typehash_insert(duplicate);
3613 if(type != duplicate) {
3614 obstack_free(type_obst, duplicate);
3616 ndeclaration->type = type;
3619 declaration_t *const declaration = record_function_definition(ndeclaration);
3620 if(ndeclaration != declaration) {
3621 declaration->scope = ndeclaration->scope;
3623 type = skip_typeref(declaration->type);
3625 /* push function parameters and switch scope */
3626 int top = environment_top();
3627 scope_t *last_scope = scope;
3628 set_scope(&declaration->scope);
3630 declaration_t *parameter = declaration->scope.declarations;
3631 for( ; parameter != NULL; parameter = parameter->next) {
3632 if(parameter->parent_scope == &ndeclaration->scope) {
3633 parameter->parent_scope = scope;
3635 assert(parameter->parent_scope == NULL
3636 || parameter->parent_scope == scope);
3637 parameter->parent_scope = scope;
3638 environment_push(parameter);
3641 if(declaration->init.statement != NULL) {
3642 parser_error_multiple_definition(declaration, token.source_position);
3644 goto end_of_parse_external_declaration;
3646 /* parse function body */
3647 int label_stack_top = label_top();
3648 declaration_t *old_current_function = current_function;
3649 current_function = declaration;
3651 declaration->init.statement = parse_compound_statement();
3654 check_declarations();
3656 assert(current_function == declaration);
3657 current_function = old_current_function;
3658 label_pop_to(label_stack_top);
3661 end_of_parse_external_declaration:
3662 assert(scope == &declaration->scope);
3663 set_scope(last_scope);
3664 environment_pop_to(top);
3667 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3668 source_position_t source_position)
3670 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3671 type->bitfield.base = base;
3672 type->bitfield.size = size;
3677 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3680 declaration_t *iter = compound_declaration->scope.declarations;
3681 for( ; iter != NULL; iter = iter->next) {
3682 if(iter->namespc != NAMESPACE_NORMAL)
3685 if(iter->symbol == NULL) {
3686 type_t *type = skip_typeref(iter->type);
3687 if(is_type_compound(type)) {
3688 declaration_t *result
3689 = find_compound_entry(type->compound.declaration, symbol);
3696 if(iter->symbol == symbol) {
3704 static void parse_compound_declarators(declaration_t *struct_declaration,
3705 const declaration_specifiers_t *specifiers)
3707 declaration_t *last_declaration = struct_declaration->scope.declarations;
3708 if(last_declaration != NULL) {
3709 while(last_declaration->next != NULL) {
3710 last_declaration = last_declaration->next;
3715 declaration_t *declaration;
3717 if(token.type == ':') {
3718 source_position_t source_position = HERE;
3721 type_t *base_type = specifiers->type;
3722 expression_t *size = parse_constant_expression();
3724 if(!is_type_integer(skip_typeref(base_type))) {
3725 errorf(HERE, "bitfield base type '%T' is not an integer type",
3729 type_t *type = make_bitfield_type(base_type, size, source_position);
3731 declaration = allocate_declaration_zero();
3732 declaration->namespc = NAMESPACE_NORMAL;
3733 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3734 declaration->storage_class = STORAGE_CLASS_NONE;
3735 declaration->source_position = source_position;
3736 declaration->modifiers = specifiers->decl_modifiers;
3737 declaration->type = type;
3739 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3741 type_t *orig_type = declaration->type;
3742 type_t *type = skip_typeref(orig_type);
3744 if(token.type == ':') {
3745 source_position_t source_position = HERE;
3747 expression_t *size = parse_constant_expression();
3749 if(!is_type_integer(type)) {
3750 errorf(HERE, "bitfield base type '%T' is not an "
3751 "integer type", orig_type);
3754 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3755 declaration->type = bitfield_type;
3757 /* TODO we ignore arrays for now... what is missing is a check
3758 * that they're at the end of the struct */
3759 if(is_type_incomplete(type) && !is_type_array(type)) {
3761 "compound member '%Y' has incomplete type '%T'",
3762 declaration->symbol, orig_type);
3763 } else if(is_type_function(type)) {
3764 errorf(HERE, "compound member '%Y' must not have function "
3765 "type '%T'", declaration->symbol, orig_type);
3770 /* make sure we don't define a symbol multiple times */
3771 symbol_t *symbol = declaration->symbol;
3772 if(symbol != NULL) {
3773 declaration_t *prev_decl
3774 = find_compound_entry(struct_declaration, symbol);
3776 if(prev_decl != NULL) {
3777 assert(prev_decl->symbol == symbol);
3778 errorf(declaration->source_position,
3779 "multiple declarations of symbol '%Y'", symbol);
3780 errorf(prev_decl->source_position,
3781 "previous declaration of '%Y' was here", symbol);
3785 /* append declaration */
3786 if(last_declaration != NULL) {
3787 last_declaration->next = declaration;
3789 struct_declaration->scope.declarations = declaration;
3791 last_declaration = declaration;
3793 if(token.type != ',')
3803 static void parse_compound_type_entries(declaration_t *compound_declaration)
3806 add_anchor_token('}');
3808 while(token.type != '}' && token.type != T_EOF) {
3809 declaration_specifiers_t specifiers;
3810 memset(&specifiers, 0, sizeof(specifiers));
3811 parse_declaration_specifiers(&specifiers);
3813 parse_compound_declarators(compound_declaration, &specifiers);
3815 rem_anchor_token('}');
3817 if(token.type == T_EOF) {
3818 errorf(HERE, "EOF while parsing struct");
3823 static type_t *parse_typename(void)
3825 declaration_specifiers_t specifiers;
3826 memset(&specifiers, 0, sizeof(specifiers));
3827 parse_declaration_specifiers(&specifiers);
3828 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3829 /* TODO: improve error message, user does probably not know what a
3830 * storage class is...
3832 errorf(HERE, "typename may not have a storage class");
3835 type_t *result = parse_abstract_declarator(specifiers.type);
3843 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3844 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3845 expression_t *left);
3847 typedef struct expression_parser_function_t expression_parser_function_t;
3848 struct expression_parser_function_t {
3849 unsigned precedence;
3850 parse_expression_function parser;
3851 unsigned infix_precedence;
3852 parse_expression_infix_function infix_parser;
3855 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3858 * Creates a new invalid expression.
3860 static expression_t *create_invalid_expression(void)
3862 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3863 expression->base.source_position = token.source_position;
3868 * Prints an error message if an expression was expected but not read
3870 static expression_t *expected_expression_error(void)
3872 /* skip the error message if the error token was read */
3873 if (token.type != T_ERROR) {
3874 errorf(HERE, "expected expression, got token '%K'", &token);
3878 return create_invalid_expression();
3882 * Parse a string constant.
3884 static expression_t *parse_string_const(void)
3887 if (token.type == T_STRING_LITERAL) {
3888 string_t res = token.v.string;
3890 while (token.type == T_STRING_LITERAL) {
3891 res = concat_strings(&res, &token.v.string);
3894 if (token.type != T_WIDE_STRING_LITERAL) {
3895 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3896 /* note: that we use type_char_ptr here, which is already the
3897 * automatic converted type. revert_automatic_type_conversion
3898 * will construct the array type */
3899 cnst->base.type = type_char_ptr;
3900 cnst->string.value = res;
3904 wres = concat_string_wide_string(&res, &token.v.wide_string);
3906 wres = token.v.wide_string;
3911 switch (token.type) {
3912 case T_WIDE_STRING_LITERAL:
3913 wres = concat_wide_strings(&wres, &token.v.wide_string);
3916 case T_STRING_LITERAL:
3917 wres = concat_wide_string_string(&wres, &token.v.string);
3921 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3922 cnst->base.type = type_wchar_t_ptr;
3923 cnst->wide_string.value = wres;
3932 * Parse an integer constant.
3934 static expression_t *parse_int_const(void)
3936 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3937 cnst->base.source_position = HERE;
3938 cnst->base.type = token.datatype;
3939 cnst->conste.v.int_value = token.v.intvalue;
3947 * Parse a character constant.
3949 static expression_t *parse_character_constant(void)
3951 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3953 cnst->base.source_position = HERE;
3954 cnst->base.type = token.datatype;
3955 cnst->conste.v.character = token.v.string;
3957 if (cnst->conste.v.character.size != 1) {
3958 if (warning.multichar && (c_mode & _GNUC)) {
3960 warningf(HERE, "multi-character character constant");
3962 errorf(HERE, "more than 1 characters in character constant");
3971 * Parse a wide character constant.
3973 static expression_t *parse_wide_character_constant(void)
3975 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3977 cnst->base.source_position = HERE;
3978 cnst->base.type = token.datatype;
3979 cnst->conste.v.wide_character = token.v.wide_string;
3981 if (cnst->conste.v.wide_character.size != 1) {
3982 if (warning.multichar && (c_mode & _GNUC)) {
3984 warningf(HERE, "multi-character character constant");
3986 errorf(HERE, "more than 1 characters in character constant");
3995 * Parse a float constant.
3997 static expression_t *parse_float_const(void)
3999 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4000 cnst->base.type = token.datatype;
4001 cnst->conste.v.float_value = token.v.floatvalue;
4008 static declaration_t *create_implicit_function(symbol_t *symbol,
4009 const source_position_t source_position)
4011 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4012 ntype->function.return_type = type_int;
4013 ntype->function.unspecified_parameters = true;
4015 type_t *type = typehash_insert(ntype);
4020 declaration_t *const declaration = allocate_declaration_zero();
4021 declaration->storage_class = STORAGE_CLASS_EXTERN;
4022 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4023 declaration->type = type;
4024 declaration->symbol = symbol;
4025 declaration->source_position = source_position;
4026 declaration->parent_scope = global_scope;
4028 scope_t *old_scope = scope;
4029 set_scope(global_scope);
4031 environment_push(declaration);
4032 /* prepends the declaration to the global declarations list */
4033 declaration->next = scope->declarations;
4034 scope->declarations = declaration;
4036 assert(scope == global_scope);
4037 set_scope(old_scope);
4043 * Creates a return_type (func)(argument_type) function type if not
4046 * @param return_type the return type
4047 * @param argument_type the argument type
4049 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4051 function_parameter_t *parameter
4052 = obstack_alloc(type_obst, sizeof(parameter[0]));
4053 memset(parameter, 0, sizeof(parameter[0]));
4054 parameter->type = argument_type;
4056 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4057 type->function.return_type = return_type;
4058 type->function.parameters = parameter;
4060 type_t *result = typehash_insert(type);
4061 if(result != type) {
4069 * Creates a function type for some function like builtins.
4071 * @param symbol the symbol describing the builtin
4073 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4075 switch(symbol->ID) {
4076 case T___builtin_alloca:
4077 return make_function_1_type(type_void_ptr, type_size_t);
4078 case T___builtin_nan:
4079 return make_function_1_type(type_double, type_char_ptr);
4080 case T___builtin_nanf:
4081 return make_function_1_type(type_float, type_char_ptr);
4082 case T___builtin_nand:
4083 return make_function_1_type(type_long_double, type_char_ptr);
4084 case T___builtin_va_end:
4085 return make_function_1_type(type_void, type_valist);
4087 panic("not implemented builtin symbol found");
4092 * Performs automatic type cast as described in § 6.3.2.1.
4094 * @param orig_type the original type
4096 static type_t *automatic_type_conversion(type_t *orig_type)
4098 type_t *type = skip_typeref(orig_type);
4099 if(is_type_array(type)) {
4100 array_type_t *array_type = &type->array;
4101 type_t *element_type = array_type->element_type;
4102 unsigned qualifiers = array_type->type.qualifiers;
4104 return make_pointer_type(element_type, qualifiers);
4107 if(is_type_function(type)) {
4108 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4115 * reverts the automatic casts of array to pointer types and function
4116 * to function-pointer types as defined § 6.3.2.1
4118 type_t *revert_automatic_type_conversion(const expression_t *expression)
4120 switch (expression->kind) {
4121 case EXPR_REFERENCE: return expression->reference.declaration->type;
4122 case EXPR_SELECT: return expression->select.compound_entry->type;
4124 case EXPR_UNARY_DEREFERENCE: {
4125 const expression_t *const value = expression->unary.value;
4126 type_t *const type = skip_typeref(value->base.type);
4127 assert(is_type_pointer(type));
4128 return type->pointer.points_to;
4131 case EXPR_BUILTIN_SYMBOL:
4132 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4134 case EXPR_ARRAY_ACCESS: {
4135 const expression_t *array_ref = expression->array_access.array_ref;
4136 type_t *type_left = skip_typeref(array_ref->base.type);
4137 if (!is_type_valid(type_left))
4139 assert(is_type_pointer(type_left));
4140 return type_left->pointer.points_to;
4143 case EXPR_STRING_LITERAL: {
4144 size_t size = expression->string.value.size;
4145 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4148 case EXPR_WIDE_STRING_LITERAL: {
4149 size_t size = expression->wide_string.value.size;
4150 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4153 case EXPR_COMPOUND_LITERAL:
4154 return expression->compound_literal.type;
4159 return expression->base.type;
4162 static expression_t *parse_reference(void)
4164 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4166 reference_expression_t *ref = &expression->reference;
4167 ref->symbol = token.v.symbol;
4169 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4171 source_position_t source_position = token.source_position;
4174 if(declaration == NULL) {
4175 if (! strict_mode && token.type == '(') {
4176 /* an implicitly defined function */
4177 if (warning.implicit_function_declaration) {
4178 warningf(HERE, "implicit declaration of function '%Y'",
4182 declaration = create_implicit_function(ref->symbol,
4185 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4186 return create_invalid_expression();
4190 type_t *type = declaration->type;
4192 /* we always do the auto-type conversions; the & and sizeof parser contains
4193 * code to revert this! */
4194 type = automatic_type_conversion(type);
4196 ref->declaration = declaration;
4197 ref->base.type = type;
4199 /* this declaration is used */
4200 declaration->used = true;
4205 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4209 /* TODO check if explicit cast is allowed and issue warnings/errors */
4212 static expression_t *parse_compound_literal(type_t *type)
4214 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4216 parse_initializer_env_t env;
4218 env.declaration = NULL;
4219 env.must_be_constant = false;
4220 initializer_t *initializer = parse_initializer(&env);
4223 expression->compound_literal.initializer = initializer;
4224 expression->compound_literal.type = type;
4225 expression->base.type = automatic_type_conversion(type);
4231 * Parse a cast expression.
4233 static expression_t *parse_cast(void)
4235 source_position_t source_position = token.source_position;
4237 type_t *type = parse_typename();
4239 /* matching add_anchor_token() is at call site */
4240 rem_anchor_token(')');
4243 if(token.type == '{') {
4244 return parse_compound_literal(type);
4247 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4248 cast->base.source_position = source_position;
4250 expression_t *value = parse_sub_expression(20);
4252 check_cast_allowed(value, type);
4254 cast->base.type = type;
4255 cast->unary.value = value;
4259 return create_invalid_expression();
4263 * Parse a statement expression.
4265 static expression_t *parse_statement_expression(void)
4267 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4269 statement_t *statement = parse_compound_statement();
4270 expression->statement.statement = statement;
4271 expression->base.source_position = statement->base.source_position;
4273 /* find last statement and use its type */
4274 type_t *type = type_void;
4275 const statement_t *stmt = statement->compound.statements;
4277 while (stmt->base.next != NULL)
4278 stmt = stmt->base.next;
4280 if (stmt->kind == STATEMENT_EXPRESSION) {
4281 type = stmt->expression.expression->base.type;
4284 warningf(expression->base.source_position, "empty statement expression ({})");
4286 expression->base.type = type;
4292 return create_invalid_expression();
4296 * Parse a braced expression.
4298 static expression_t *parse_brace_expression(void)
4301 add_anchor_token(')');
4303 switch(token.type) {
4305 /* gcc extension: a statement expression */
4306 return parse_statement_expression();
4310 return parse_cast();
4312 if(is_typedef_symbol(token.v.symbol)) {
4313 return parse_cast();
4317 expression_t *result = parse_expression();
4318 rem_anchor_token(')');
4323 return create_invalid_expression();
4326 static expression_t *parse_function_keyword(void)
4331 if (current_function == NULL) {
4332 errorf(HERE, "'__func__' used outside of a function");
4335 expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4336 expression->base.type = type_char_ptr;
4341 static expression_t *parse_pretty_function_keyword(void)
4343 eat(T___PRETTY_FUNCTION__);
4346 if (current_function == NULL) {
4347 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4350 expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4351 expression->base.type = type_char_ptr;
4356 static designator_t *parse_designator(void)
4358 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4359 result->source_position = HERE;
4361 if(token.type != T_IDENTIFIER) {
4362 parse_error_expected("while parsing member designator",
4366 result->symbol = token.v.symbol;
4369 designator_t *last_designator = result;
4371 if(token.type == '.') {
4373 if(token.type != T_IDENTIFIER) {
4374 parse_error_expected("while parsing member designator",
4378 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4379 designator->source_position = HERE;
4380 designator->symbol = token.v.symbol;
4383 last_designator->next = designator;
4384 last_designator = designator;
4387 if(token.type == '[') {
4389 add_anchor_token(']');
4390 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4391 designator->source_position = HERE;
4392 designator->array_index = parse_expression();
4393 rem_anchor_token(']');
4395 if(designator->array_index == NULL) {
4399 last_designator->next = designator;
4400 last_designator = designator;
4412 * Parse the __builtin_offsetof() expression.
4414 static expression_t *parse_offsetof(void)
4416 eat(T___builtin_offsetof);
4418 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4419 expression->base.type = type_size_t;
4422 add_anchor_token(',');
4423 type_t *type = parse_typename();
4424 rem_anchor_token(',');
4426 add_anchor_token(')');
4427 designator_t *designator = parse_designator();
4428 rem_anchor_token(')');
4431 expression->offsetofe.type = type;
4432 expression->offsetofe.designator = designator;
4435 memset(&path, 0, sizeof(path));
4436 path.top_type = type;
4437 path.path = NEW_ARR_F(type_path_entry_t, 0);
4439 descend_into_subtype(&path);
4441 if(!walk_designator(&path, designator, true)) {
4442 return create_invalid_expression();
4445 DEL_ARR_F(path.path);
4449 return create_invalid_expression();
4453 * Parses a _builtin_va_start() expression.
4455 static expression_t *parse_va_start(void)
4457 eat(T___builtin_va_start);
4459 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4462 add_anchor_token(',');
4463 expression->va_starte.ap = parse_assignment_expression();
4464 rem_anchor_token(',');
4466 expression_t *const expr = parse_assignment_expression();
4467 if (expr->kind == EXPR_REFERENCE) {
4468 declaration_t *const decl = expr->reference.declaration;
4470 return create_invalid_expression();
4471 if (decl->parent_scope == ¤t_function->scope &&
4472 decl->next == NULL) {
4473 expression->va_starte.parameter = decl;
4478 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4480 return create_invalid_expression();
4484 * Parses a _builtin_va_arg() expression.
4486 static expression_t *parse_va_arg(void)
4488 eat(T___builtin_va_arg);
4490 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4493 expression->va_arge.ap = parse_assignment_expression();
4495 expression->base.type = parse_typename();
4500 return create_invalid_expression();
4503 static expression_t *parse_builtin_symbol(void)
4505 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4507 symbol_t *symbol = token.v.symbol;
4509 expression->builtin_symbol.symbol = symbol;
4512 type_t *type = get_builtin_symbol_type(symbol);
4513 type = automatic_type_conversion(type);
4515 expression->base.type = type;
4520 * Parses a __builtin_constant() expression.
4522 static expression_t *parse_builtin_constant(void)
4524 eat(T___builtin_constant_p);
4526 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4529 add_anchor_token(')');
4530 expression->builtin_constant.value = parse_assignment_expression();
4531 rem_anchor_token(')');
4533 expression->base.type = type_int;
4537 return create_invalid_expression();
4541 * Parses a __builtin_prefetch() expression.
4543 static expression_t *parse_builtin_prefetch(void)
4545 eat(T___builtin_prefetch);
4547 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4550 add_anchor_token(')');
4551 expression->builtin_prefetch.adr = parse_assignment_expression();
4552 if (token.type == ',') {
4554 expression->builtin_prefetch.rw = parse_assignment_expression();
4556 if (token.type == ',') {
4558 expression->builtin_prefetch.locality = parse_assignment_expression();
4560 rem_anchor_token(')');
4562 expression->base.type = type_void;
4566 return create_invalid_expression();
4570 * Parses a __builtin_is_*() compare expression.
4572 static expression_t *parse_compare_builtin(void)
4574 expression_t *expression;
4576 switch(token.type) {
4577 case T___builtin_isgreater:
4578 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4580 case T___builtin_isgreaterequal:
4581 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4583 case T___builtin_isless:
4584 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4586 case T___builtin_islessequal:
4587 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4589 case T___builtin_islessgreater:
4590 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4592 case T___builtin_isunordered:
4593 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4596 panic("invalid compare builtin found");
4599 expression->base.source_position = HERE;
4603 expression->binary.left = parse_assignment_expression();
4605 expression->binary.right = parse_assignment_expression();
4608 type_t *const orig_type_left = expression->binary.left->base.type;
4609 type_t *const orig_type_right = expression->binary.right->base.type;
4611 type_t *const type_left = skip_typeref(orig_type_left);
4612 type_t *const type_right = skip_typeref(orig_type_right);
4613 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4614 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4615 type_error_incompatible("invalid operands in comparison",
4616 expression->base.source_position, orig_type_left, orig_type_right);
4619 semantic_comparison(&expression->binary);
4624 return create_invalid_expression();
4628 * Parses a __builtin_expect() expression.
4630 static expression_t *parse_builtin_expect(void)
4632 eat(T___builtin_expect);
4634 expression_t *expression
4635 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4638 expression->binary.left = parse_assignment_expression();
4640 expression->binary.right = parse_constant_expression();
4643 expression->base.type = expression->binary.left->base.type;
4647 return create_invalid_expression();
4651 * Parses a MS assume() expression.
4653 static expression_t *parse_assume(void) {
4656 expression_t *expression
4657 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4660 add_anchor_token(')');
4661 expression->unary.value = parse_assignment_expression();
4662 rem_anchor_token(')');
4665 expression->base.type = type_void;
4668 return create_invalid_expression();
4672 * Parses a primary expression.
4674 static expression_t *parse_primary_expression(void)
4676 switch (token.type) {
4677 case T_INTEGER: return parse_int_const();
4678 case T_CHARACTER_CONSTANT: return parse_character_constant();
4679 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4680 case T_FLOATINGPOINT: return parse_float_const();
4681 case T_STRING_LITERAL:
4682 case T_WIDE_STRING_LITERAL: return parse_string_const();
4683 case T_IDENTIFIER: return parse_reference();
4684 case T___FUNCTION__:
4685 case T___func__: return parse_function_keyword();
4686 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4687 case T___builtin_offsetof: return parse_offsetof();
4688 case T___builtin_va_start: return parse_va_start();
4689 case T___builtin_va_arg: return parse_va_arg();
4690 case T___builtin_expect: return parse_builtin_expect();
4691 case T___builtin_alloca:
4692 case T___builtin_nan:
4693 case T___builtin_nand:
4694 case T___builtin_nanf:
4695 case T___builtin_va_end: return parse_builtin_symbol();
4696 case T___builtin_isgreater:
4697 case T___builtin_isgreaterequal:
4698 case T___builtin_isless:
4699 case T___builtin_islessequal:
4700 case T___builtin_islessgreater:
4701 case T___builtin_isunordered: return parse_compare_builtin();
4702 case T___builtin_constant_p: return parse_builtin_constant();
4703 case T___builtin_prefetch: return parse_builtin_prefetch();
4704 case T_assume: return parse_assume();
4706 case '(': return parse_brace_expression();
4709 errorf(HERE, "unexpected token %K, expected an expression", &token);
4710 return create_invalid_expression();
4714 * Check if the expression has the character type and issue a warning then.
4716 static void check_for_char_index_type(const expression_t *expression) {
4717 type_t *const type = expression->base.type;
4718 const type_t *const base_type = skip_typeref(type);
4720 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4721 warning.char_subscripts) {
4722 warningf(expression->base.source_position,
4723 "array subscript has type '%T'", type);
4727 static expression_t *parse_array_expression(unsigned precedence,
4733 add_anchor_token(']');
4735 expression_t *inside = parse_expression();
4737 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4739 array_access_expression_t *array_access = &expression->array_access;
4741 type_t *const orig_type_left = left->base.type;
4742 type_t *const orig_type_inside = inside->base.type;
4744 type_t *const type_left = skip_typeref(orig_type_left);
4745 type_t *const type_inside = skip_typeref(orig_type_inside);
4747 type_t *return_type;
4748 if (is_type_pointer(type_left)) {
4749 return_type = type_left->pointer.points_to;
4750 array_access->array_ref = left;
4751 array_access->index = inside;
4752 check_for_char_index_type(inside);
4753 } else if (is_type_pointer(type_inside)) {
4754 return_type = type_inside->pointer.points_to;
4755 array_access->array_ref = inside;
4756 array_access->index = left;
4757 array_access->flipped = true;
4758 check_for_char_index_type(left);
4760 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4762 "array access on object with non-pointer types '%T', '%T'",
4763 orig_type_left, orig_type_inside);
4765 return_type = type_error_type;
4766 array_access->array_ref = create_invalid_expression();
4769 rem_anchor_token(']');
4770 if(token.type != ']') {
4771 parse_error_expected("Problem while parsing array access", ']', 0);
4776 return_type = automatic_type_conversion(return_type);
4777 expression->base.type = return_type;
4782 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4784 expression_t *tp_expression = allocate_expression_zero(kind);
4785 tp_expression->base.type = type_size_t;
4787 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4789 add_anchor_token(')');
4790 tp_expression->typeprop.type = parse_typename();
4791 rem_anchor_token(')');
4794 expression_t *expression = parse_sub_expression(precedence);
4795 expression->base.type = revert_automatic_type_conversion(expression);
4797 tp_expression->typeprop.type = expression->base.type;
4798 tp_expression->typeprop.tp_expression = expression;
4801 return tp_expression;
4803 return create_invalid_expression();
4806 static expression_t *parse_sizeof(unsigned precedence)
4809 return parse_typeprop(EXPR_SIZEOF, precedence);
4812 static expression_t *parse_alignof(unsigned precedence)
4815 return parse_typeprop(EXPR_SIZEOF, precedence);
4818 static expression_t *parse_select_expression(unsigned precedence,
4819 expression_t *compound)
4822 assert(token.type == '.' || token.type == T_MINUSGREATER);
4824 bool is_pointer = (token.type == T_MINUSGREATER);
4827 expression_t *select = allocate_expression_zero(EXPR_SELECT);
4828 select->select.compound = compound;
4830 if(token.type != T_IDENTIFIER) {
4831 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4834 symbol_t *symbol = token.v.symbol;
4835 select->select.symbol = symbol;
4838 type_t *const orig_type = compound->base.type;
4839 type_t *const type = skip_typeref(orig_type);
4841 type_t *type_left = type;
4843 if (!is_type_pointer(type)) {
4844 if (is_type_valid(type)) {
4845 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4847 return create_invalid_expression();
4849 type_left = type->pointer.points_to;
4851 type_left = skip_typeref(type_left);
4853 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4854 type_left->kind != TYPE_COMPOUND_UNION) {
4855 if (is_type_valid(type_left)) {
4856 errorf(HERE, "request for member '%Y' in something not a struct or "
4857 "union, but '%T'", symbol, type_left);
4859 return create_invalid_expression();
4862 declaration_t *const declaration = type_left->compound.declaration;
4864 if(!declaration->init.is_defined) {
4865 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4867 return create_invalid_expression();
4870 declaration_t *iter = find_compound_entry(declaration, symbol);
4872 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4873 return create_invalid_expression();
4876 /* we always do the auto-type conversions; the & and sizeof parser contains
4877 * code to revert this! */
4878 type_t *expression_type = automatic_type_conversion(iter->type);
4880 select->select.compound_entry = iter;
4881 select->base.type = expression_type;
4883 if(expression_type->kind == TYPE_BITFIELD) {
4884 expression_t *extract
4885 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4886 extract->unary.value = select;
4887 extract->base.type = expression_type->bitfield.base;
4896 * Parse a call expression, ie. expression '( ... )'.
4898 * @param expression the function address
4900 static expression_t *parse_call_expression(unsigned precedence,
4901 expression_t *expression)
4904 expression_t *result = allocate_expression_zero(EXPR_CALL);
4906 call_expression_t *call = &result->call;
4907 call->function = expression;
4909 type_t *const orig_type = expression->base.type;
4910 type_t *const type = skip_typeref(orig_type);
4912 function_type_t *function_type = NULL;
4913 if (is_type_pointer(type)) {
4914 type_t *const to_type = skip_typeref(type->pointer.points_to);
4916 if (is_type_function(to_type)) {
4917 function_type = &to_type->function;
4918 call->base.type = function_type->return_type;
4922 if (function_type == NULL && is_type_valid(type)) {
4923 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4926 /* parse arguments */
4928 add_anchor_token(')');
4929 add_anchor_token(',');
4931 if(token.type != ')') {
4932 call_argument_t *last_argument = NULL;
4935 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4937 argument->expression = parse_assignment_expression();
4938 if(last_argument == NULL) {
4939 call->arguments = argument;
4941 last_argument->next = argument;
4943 last_argument = argument;
4945 if(token.type != ',')
4950 rem_anchor_token(',');
4951 rem_anchor_token(')');
4954 if(function_type != NULL) {
4955 function_parameter_t *parameter = function_type->parameters;
4956 call_argument_t *argument = call->arguments;
4957 for( ; parameter != NULL && argument != NULL;
4958 parameter = parameter->next, argument = argument->next) {
4959 type_t *expected_type = parameter->type;
4960 /* TODO report scope in error messages */
4961 expression_t *const arg_expr = argument->expression;
4962 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4963 if (res_type == NULL) {
4964 /* TODO improve error message */
4965 errorf(arg_expr->base.source_position,
4966 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4967 arg_expr, arg_expr->base.type, expected_type);
4969 argument->expression = create_implicit_cast(argument->expression, expected_type);
4972 /* too few parameters */
4973 if(parameter != NULL) {
4974 errorf(HERE, "too few arguments to function '%E'", expression);
4975 } else if(argument != NULL) {
4976 /* too many parameters */
4977 if(!function_type->variadic
4978 && !function_type->unspecified_parameters) {
4979 errorf(HERE, "too many arguments to function '%E'", expression);
4981 /* do default promotion */
4982 for( ; argument != NULL; argument = argument->next) {
4983 type_t *type = argument->expression->base.type;
4985 type = skip_typeref(type);
4986 if(is_type_integer(type)) {
4987 type = promote_integer(type);
4988 } else if(type == type_float) {
4992 argument->expression
4993 = create_implicit_cast(argument->expression, type);
4996 check_format(&result->call);
4999 check_format(&result->call);
5005 return create_invalid_expression();
5008 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5010 static bool same_compound_type(const type_t *type1, const type_t *type2)
5013 is_type_compound(type1) &&
5014 type1->kind == type2->kind &&
5015 type1->compound.declaration == type2->compound.declaration;
5019 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5021 * @param expression the conditional expression
5023 static expression_t *parse_conditional_expression(unsigned precedence,
5024 expression_t *expression)
5027 add_anchor_token(':');
5029 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5031 conditional_expression_t *conditional = &result->conditional;
5032 conditional->condition = expression;
5035 type_t *const condition_type_orig = expression->base.type;
5036 type_t *const condition_type = skip_typeref(condition_type_orig);
5037 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5038 type_error("expected a scalar type in conditional condition",
5039 expression->base.source_position, condition_type_orig);
5042 expression_t *true_expression = parse_expression();
5043 rem_anchor_token(':');
5045 expression_t *false_expression = parse_sub_expression(precedence);
5047 type_t *const orig_true_type = true_expression->base.type;
5048 type_t *const orig_false_type = false_expression->base.type;
5049 type_t *const true_type = skip_typeref(orig_true_type);
5050 type_t *const false_type = skip_typeref(orig_false_type);
5053 type_t *result_type;
5054 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
5055 result_type = semantic_arithmetic(true_type, false_type);
5057 true_expression = create_implicit_cast(true_expression, result_type);
5058 false_expression = create_implicit_cast(false_expression, result_type);
5060 conditional->true_expression = true_expression;
5061 conditional->false_expression = false_expression;
5062 conditional->base.type = result_type;
5063 } else if (same_compound_type(true_type, false_type) || (
5064 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
5065 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
5067 /* just take 1 of the 2 types */
5068 result_type = true_type;
5069 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
5070 && pointers_compatible(true_type, false_type)) {
5072 result_type = true_type;
5073 } else if (is_type_pointer(true_type)
5074 && is_null_pointer_constant(false_expression)) {
5075 result_type = true_type;
5076 } else if (is_type_pointer(false_type)
5077 && is_null_pointer_constant(true_expression)) {
5078 result_type = false_type;
5080 /* TODO: one pointer to void*, other some pointer */
5082 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5083 type_error_incompatible("while parsing conditional",
5084 expression->base.source_position, true_type,
5087 result_type = type_error_type;
5090 conditional->true_expression
5091 = create_implicit_cast(true_expression, result_type);
5092 conditional->false_expression
5093 = create_implicit_cast(false_expression, result_type);
5094 conditional->base.type = result_type;
5097 return create_invalid_expression();
5101 * Parse an extension expression.
5103 static expression_t *parse_extension(unsigned precedence)
5105 eat(T___extension__);
5107 /* TODO enable extensions */
5108 expression_t *expression = parse_sub_expression(precedence);
5109 /* TODO disable extensions */
5114 * Parse a __builtin_classify_type() expression.
5116 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5118 eat(T___builtin_classify_type);
5120 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5121 result->base.type = type_int;
5124 add_anchor_token(')');
5125 expression_t *expression = parse_sub_expression(precedence);
5126 rem_anchor_token(')');
5128 result->classify_type.type_expression = expression;
5132 return create_invalid_expression();
5135 static void semantic_incdec(unary_expression_t *expression)
5137 type_t *const orig_type = expression->value->base.type;
5138 type_t *const type = skip_typeref(orig_type);
5139 /* TODO !is_type_real && !is_type_pointer */
5140 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5141 if (is_type_valid(type)) {
5142 /* TODO: improve error message */
5143 errorf(HERE, "operation needs an arithmetic or pointer type");
5148 expression->base.type = orig_type;
5151 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5153 type_t *const orig_type = expression->value->base.type;
5154 type_t *const type = skip_typeref(orig_type);
5155 if(!is_type_arithmetic(type)) {
5156 if (is_type_valid(type)) {
5157 /* TODO: improve error message */
5158 errorf(HERE, "operation needs an arithmetic type");
5163 expression->base.type = orig_type;
5166 static void semantic_unexpr_scalar(unary_expression_t *expression)
5168 type_t *const orig_type = expression->value->base.type;
5169 type_t *const type = skip_typeref(orig_type);
5170 if (!is_type_scalar(type)) {
5171 if (is_type_valid(type)) {
5172 errorf(HERE, "operand of ! must be of scalar type");
5177 expression->base.type = orig_type;
5180 static void semantic_unexpr_integer(unary_expression_t *expression)
5182 type_t *const orig_type = expression->value->base.type;
5183 type_t *const type = skip_typeref(orig_type);
5184 if (!is_type_integer(type)) {
5185 if (is_type_valid(type)) {
5186 errorf(HERE, "operand of ~ must be of integer type");
5191 expression->base.type = orig_type;
5194 static void semantic_dereference(unary_expression_t *expression)
5196 type_t *const orig_type = expression->value->base.type;
5197 type_t *const type = skip_typeref(orig_type);
5198 if(!is_type_pointer(type)) {
5199 if (is_type_valid(type)) {
5200 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5205 type_t *result_type = type->pointer.points_to;
5206 result_type = automatic_type_conversion(result_type);
5207 expression->base.type = result_type;
5211 * Check the semantic of the address taken expression.
5213 static void semantic_take_addr(unary_expression_t *expression)
5215 expression_t *value = expression->value;
5216 value->base.type = revert_automatic_type_conversion(value);
5218 type_t *orig_type = value->base.type;
5219 if(!is_type_valid(orig_type))
5222 if(value->kind == EXPR_REFERENCE) {
5223 declaration_t *const declaration = value->reference.declaration;
5224 if(declaration != NULL) {
5225 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5226 errorf(expression->base.source_position,
5227 "address of register variable '%Y' requested",
5228 declaration->symbol);
5230 declaration->address_taken = 1;
5234 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5237 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5238 static expression_t *parse_##unexpression_type(unsigned precedence) \
5242 expression_t *unary_expression \
5243 = allocate_expression_zero(unexpression_type); \
5244 unary_expression->base.source_position = HERE; \
5245 unary_expression->unary.value = parse_sub_expression(precedence); \
5247 sfunc(&unary_expression->unary); \
5249 return unary_expression; \
5252 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5253 semantic_unexpr_arithmetic)
5254 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5255 semantic_unexpr_arithmetic)
5256 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5257 semantic_unexpr_scalar)
5258 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5259 semantic_dereference)
5260 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5262 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5263 semantic_unexpr_integer)
5264 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5266 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5269 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5271 static expression_t *parse_##unexpression_type(unsigned precedence, \
5272 expression_t *left) \
5274 (void) precedence; \
5277 expression_t *unary_expression \
5278 = allocate_expression_zero(unexpression_type); \
5279 unary_expression->unary.value = left; \
5281 sfunc(&unary_expression->unary); \
5283 return unary_expression; \
5286 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5287 EXPR_UNARY_POSTFIX_INCREMENT,
5289 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5290 EXPR_UNARY_POSTFIX_DECREMENT,
5293 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5295 /* TODO: handle complex + imaginary types */
5297 /* § 6.3.1.8 Usual arithmetic conversions */
5298 if(type_left == type_long_double || type_right == type_long_double) {
5299 return type_long_double;
5300 } else if(type_left == type_double || type_right == type_double) {
5302 } else if(type_left == type_float || type_right == type_float) {
5306 type_right = promote_integer(type_right);
5307 type_left = promote_integer(type_left);
5309 if(type_left == type_right)
5312 bool signed_left = is_type_signed(type_left);
5313 bool signed_right = is_type_signed(type_right);
5314 int rank_left = get_rank(type_left);
5315 int rank_right = get_rank(type_right);
5316 if(rank_left < rank_right) {
5317 if(signed_left == signed_right || !signed_right) {
5323 if(signed_left == signed_right || !signed_left) {
5332 * Check the semantic restrictions for a binary expression.
5334 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5336 expression_t *const left = expression->left;
5337 expression_t *const right = expression->right;
5338 type_t *const orig_type_left = left->base.type;
5339 type_t *const orig_type_right = right->base.type;
5340 type_t *const type_left = skip_typeref(orig_type_left);
5341 type_t *const type_right = skip_typeref(orig_type_right);
5343 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5344 /* TODO: improve error message */
5345 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5346 errorf(HERE, "operation needs arithmetic types");
5351 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5352 expression->left = create_implicit_cast(left, arithmetic_type);
5353 expression->right = create_implicit_cast(right, arithmetic_type);
5354 expression->base.type = arithmetic_type;
5357 static void semantic_shift_op(binary_expression_t *expression)
5359 expression_t *const left = expression->left;
5360 expression_t *const right = expression->right;
5361 type_t *const orig_type_left = left->base.type;
5362 type_t *const orig_type_right = right->base.type;
5363 type_t * type_left = skip_typeref(orig_type_left);
5364 type_t * type_right = skip_typeref(orig_type_right);
5366 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5367 /* TODO: improve error message */
5368 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5369 errorf(HERE, "operation needs integer types");
5374 type_left = promote_integer(type_left);
5375 type_right = promote_integer(type_right);
5377 expression->left = create_implicit_cast(left, type_left);
5378 expression->right = create_implicit_cast(right, type_right);
5379 expression->base.type = type_left;
5382 static void semantic_add(binary_expression_t *expression)
5384 expression_t *const left = expression->left;
5385 expression_t *const right = expression->right;
5386 type_t *const orig_type_left = left->base.type;
5387 type_t *const orig_type_right = right->base.type;
5388 type_t *const type_left = skip_typeref(orig_type_left);
5389 type_t *const type_right = skip_typeref(orig_type_right);
5392 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5393 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5394 expression->left = create_implicit_cast(left, arithmetic_type);
5395 expression->right = create_implicit_cast(right, arithmetic_type);
5396 expression->base.type = arithmetic_type;
5398 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5399 expression->base.type = type_left;
5400 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5401 expression->base.type = type_right;
5402 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5403 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5407 static void semantic_sub(binary_expression_t *expression)
5409 expression_t *const left = expression->left;
5410 expression_t *const right = expression->right;
5411 type_t *const orig_type_left = left->base.type;
5412 type_t *const orig_type_right = right->base.type;
5413 type_t *const type_left = skip_typeref(orig_type_left);
5414 type_t *const type_right = skip_typeref(orig_type_right);
5417 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5418 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5419 expression->left = create_implicit_cast(left, arithmetic_type);
5420 expression->right = create_implicit_cast(right, arithmetic_type);
5421 expression->base.type = arithmetic_type;
5423 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5424 expression->base.type = type_left;
5425 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5426 if(!pointers_compatible(type_left, type_right)) {
5428 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5429 orig_type_left, orig_type_right);
5431 expression->base.type = type_ptrdiff_t;
5433 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5434 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5435 orig_type_left, orig_type_right);
5440 * Check the semantics of comparison expressions.
5442 * @param expression The expression to check.
5444 static void semantic_comparison(binary_expression_t *expression)
5446 expression_t *left = expression->left;
5447 expression_t *right = expression->right;
5448 type_t *orig_type_left = left->base.type;
5449 type_t *orig_type_right = right->base.type;
5451 type_t *type_left = skip_typeref(orig_type_left);
5452 type_t *type_right = skip_typeref(orig_type_right);
5454 /* TODO non-arithmetic types */
5455 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5456 if (warning.sign_compare &&
5457 (expression->base.kind != EXPR_BINARY_EQUAL &&
5458 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5459 (is_type_signed(type_left) != is_type_signed(type_right))) {
5460 warningf(expression->base.source_position,
5461 "comparison between signed and unsigned");
5463 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5464 expression->left = create_implicit_cast(left, arithmetic_type);
5465 expression->right = create_implicit_cast(right, arithmetic_type);
5466 expression->base.type = arithmetic_type;
5467 if (warning.float_equal &&
5468 (expression->base.kind == EXPR_BINARY_EQUAL ||
5469 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5470 is_type_float(arithmetic_type)) {
5471 warningf(expression->base.source_position,
5472 "comparing floating point with == or != is unsafe");
5474 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5475 /* TODO check compatibility */
5476 } else if (is_type_pointer(type_left)) {
5477 expression->right = create_implicit_cast(right, type_left);
5478 } else if (is_type_pointer(type_right)) {
5479 expression->left = create_implicit_cast(left, type_right);
5480 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5481 type_error_incompatible("invalid operands in comparison",
5482 expression->base.source_position,
5483 type_left, type_right);
5485 expression->base.type = type_int;
5488 static void semantic_arithmetic_assign(binary_expression_t *expression)
5490 expression_t *left = expression->left;
5491 expression_t *right = expression->right;
5492 type_t *orig_type_left = left->base.type;
5493 type_t *orig_type_right = right->base.type;
5495 type_t *type_left = skip_typeref(orig_type_left);
5496 type_t *type_right = skip_typeref(orig_type_right);
5498 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5499 /* TODO: improve error message */
5500 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5501 errorf(HERE, "operation needs arithmetic types");
5506 /* combined instructions are tricky. We can't create an implicit cast on
5507 * the left side, because we need the uncasted form for the store.
5508 * The ast2firm pass has to know that left_type must be right_type
5509 * for the arithmetic operation and create a cast by itself */
5510 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5511 expression->right = create_implicit_cast(right, arithmetic_type);
5512 expression->base.type = type_left;
5515 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5517 expression_t *const left = expression->left;
5518 expression_t *const right = expression->right;
5519 type_t *const orig_type_left = left->base.type;
5520 type_t *const orig_type_right = right->base.type;
5521 type_t *const type_left = skip_typeref(orig_type_left);
5522 type_t *const type_right = skip_typeref(orig_type_right);
5524 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5525 /* combined instructions are tricky. We can't create an implicit cast on
5526 * the left side, because we need the uncasted form for the store.
5527 * The ast2firm pass has to know that left_type must be right_type
5528 * for the arithmetic operation and create a cast by itself */
5529 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5530 expression->right = create_implicit_cast(right, arithmetic_type);
5531 expression->base.type = type_left;
5532 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5533 expression->base.type = type_left;
5534 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5535 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5540 * Check the semantic restrictions of a logical expression.
5542 static void semantic_logical_op(binary_expression_t *expression)
5544 expression_t *const left = expression->left;
5545 expression_t *const right = expression->right;
5546 type_t *const orig_type_left = left->base.type;
5547 type_t *const orig_type_right = right->base.type;
5548 type_t *const type_left = skip_typeref(orig_type_left);
5549 type_t *const type_right = skip_typeref(orig_type_right);
5551 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5552 /* TODO: improve error message */
5553 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5554 errorf(HERE, "operation needs scalar types");
5559 expression->base.type = type_int;
5563 * Checks if a compound type has constant fields.
5565 static bool has_const_fields(const compound_type_t *type)
5567 const scope_t *scope = &type->declaration->scope;
5568 const declaration_t *declaration = scope->declarations;
5570 for (; declaration != NULL; declaration = declaration->next) {
5571 if (declaration->namespc != NAMESPACE_NORMAL)
5574 const type_t *decl_type = skip_typeref(declaration->type);
5575 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5583 * Check the semantic restrictions of a binary assign expression.
5585 static void semantic_binexpr_assign(binary_expression_t *expression)
5587 expression_t *left = expression->left;
5588 type_t *orig_type_left = left->base.type;
5590 type_t *type_left = revert_automatic_type_conversion(left);
5591 type_left = skip_typeref(orig_type_left);
5593 /* must be a modifiable lvalue */
5594 if (is_type_array(type_left)) {
5595 errorf(HERE, "cannot assign to arrays ('%E')", left);
5598 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5599 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5603 if(is_type_incomplete(type_left)) {
5605 "left-hand side of assignment '%E' has incomplete type '%T'",
5606 left, orig_type_left);
5609 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5610 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5611 left, orig_type_left);
5615 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5617 if (res_type == NULL) {
5618 errorf(expression->base.source_position,
5619 "cannot assign to '%T' from '%T'",
5620 orig_type_left, expression->right->base.type);
5622 expression->right = create_implicit_cast(expression->right, res_type);
5625 expression->base.type = orig_type_left;
5629 * Determine if the outermost operation (or parts thereof) of the given
5630 * expression has no effect in order to generate a warning about this fact.
5631 * Therefore in some cases this only examines some of the operands of the
5632 * expression (see comments in the function and examples below).
5634 * f() + 23; // warning, because + has no effect
5635 * x || f(); // no warning, because x controls execution of f()
5636 * x ? y : f(); // warning, because y has no effect
5637 * (void)x; // no warning to be able to suppress the warning
5638 * This function can NOT be used for an "expression has definitely no effect"-
5640 static bool expression_has_effect(const expression_t *const expr)
5642 switch (expr->kind) {
5643 case EXPR_UNKNOWN: break;
5644 case EXPR_INVALID: return true; /* do NOT warn */
5645 case EXPR_REFERENCE: return false;
5646 case EXPR_CONST: return false;
5647 case EXPR_CHARACTER_CONSTANT: return false;
5648 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5649 case EXPR_STRING_LITERAL: return false;
5650 case EXPR_WIDE_STRING_LITERAL: return false;
5653 const call_expression_t *const call = &expr->call;
5654 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5657 switch (call->function->builtin_symbol.symbol->ID) {
5658 case T___builtin_va_end: return true;
5659 default: return false;
5663 /* Generate the warning if either the left or right hand side of a
5664 * conditional expression has no effect */
5665 case EXPR_CONDITIONAL: {
5666 const conditional_expression_t *const cond = &expr->conditional;
5668 expression_has_effect(cond->true_expression) &&
5669 expression_has_effect(cond->false_expression);
5672 case EXPR_SELECT: return false;
5673 case EXPR_ARRAY_ACCESS: return false;
5674 case EXPR_SIZEOF: return false;
5675 case EXPR_CLASSIFY_TYPE: return false;
5676 case EXPR_ALIGNOF: return false;
5678 case EXPR_FUNCTION: return false;
5679 case EXPR_PRETTY_FUNCTION: return false;
5680 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5681 case EXPR_BUILTIN_CONSTANT_P: return false;
5682 case EXPR_BUILTIN_PREFETCH: return true;
5683 case EXPR_OFFSETOF: return false;
5684 case EXPR_VA_START: return true;
5685 case EXPR_VA_ARG: return true;
5686 case EXPR_STATEMENT: return true; // TODO
5687 case EXPR_COMPOUND_LITERAL: return false;
5689 case EXPR_UNARY_NEGATE: return false;
5690 case EXPR_UNARY_PLUS: return false;
5691 case EXPR_UNARY_BITWISE_NEGATE: return false;
5692 case EXPR_UNARY_NOT: return false;
5693 case EXPR_UNARY_DEREFERENCE: return false;
5694 case EXPR_UNARY_TAKE_ADDRESS: return false;
5695 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5696 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5697 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5698 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5700 /* Treat void casts as if they have an effect in order to being able to
5701 * suppress the warning */
5702 case EXPR_UNARY_CAST: {
5703 type_t *const type = skip_typeref(expr->base.type);
5704 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5707 case EXPR_UNARY_CAST_IMPLICIT: return true;
5708 case EXPR_UNARY_ASSUME: return true;
5709 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5711 case EXPR_BINARY_ADD: return false;
5712 case EXPR_BINARY_SUB: return false;
5713 case EXPR_BINARY_MUL: return false;
5714 case EXPR_BINARY_DIV: return false;
5715 case EXPR_BINARY_MOD: return false;
5716 case EXPR_BINARY_EQUAL: return false;
5717 case EXPR_BINARY_NOTEQUAL: return false;
5718 case EXPR_BINARY_LESS: return false;
5719 case EXPR_BINARY_LESSEQUAL: return false;
5720 case EXPR_BINARY_GREATER: return false;
5721 case EXPR_BINARY_GREATEREQUAL: return false;
5722 case EXPR_BINARY_BITWISE_AND: return false;
5723 case EXPR_BINARY_BITWISE_OR: return false;
5724 case EXPR_BINARY_BITWISE_XOR: return false;
5725 case EXPR_BINARY_SHIFTLEFT: return false;
5726 case EXPR_BINARY_SHIFTRIGHT: return false;
5727 case EXPR_BINARY_ASSIGN: return true;
5728 case EXPR_BINARY_MUL_ASSIGN: return true;
5729 case EXPR_BINARY_DIV_ASSIGN: return true;
5730 case EXPR_BINARY_MOD_ASSIGN: return true;
5731 case EXPR_BINARY_ADD_ASSIGN: return true;
5732 case EXPR_BINARY_SUB_ASSIGN: return true;
5733 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5734 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5735 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5736 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5737 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5739 /* Only examine the right hand side of && and ||, because the left hand
5740 * side already has the effect of controlling the execution of the right
5742 case EXPR_BINARY_LOGICAL_AND:
5743 case EXPR_BINARY_LOGICAL_OR:
5744 /* Only examine the right hand side of a comma expression, because the left
5745 * hand side has a separate warning */
5746 case EXPR_BINARY_COMMA:
5747 return expression_has_effect(expr->binary.right);
5749 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5750 case EXPR_BINARY_ISGREATER: return false;
5751 case EXPR_BINARY_ISGREATEREQUAL: return false;
5752 case EXPR_BINARY_ISLESS: return false;
5753 case EXPR_BINARY_ISLESSEQUAL: return false;
5754 case EXPR_BINARY_ISLESSGREATER: return false;
5755 case EXPR_BINARY_ISUNORDERED: return false;
5758 panic("unexpected expression");
5761 static void semantic_comma(binary_expression_t *expression)
5763 if (warning.unused_value) {
5764 const expression_t *const left = expression->left;
5765 if (!expression_has_effect(left)) {
5766 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5769 expression->base.type = expression->right->base.type;
5772 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5773 static expression_t *parse_##binexpression_type(unsigned precedence, \
5774 expression_t *left) \
5777 source_position_t pos = HERE; \
5779 expression_t *right = parse_sub_expression(precedence + lr); \
5781 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5782 binexpr->base.source_position = pos; \
5783 binexpr->binary.left = left; \
5784 binexpr->binary.right = right; \
5785 sfunc(&binexpr->binary); \
5790 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5791 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5792 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5793 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5794 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5795 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5796 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5797 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5798 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5800 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5801 semantic_comparison, 1)
5802 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5803 semantic_comparison, 1)
5804 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5805 semantic_comparison, 1)
5806 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5807 semantic_comparison, 1)
5809 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5810 semantic_binexpr_arithmetic, 1)
5811 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5812 semantic_binexpr_arithmetic, 1)
5813 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5814 semantic_binexpr_arithmetic, 1)
5815 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5816 semantic_logical_op, 1)
5817 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5818 semantic_logical_op, 1)
5819 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5820 semantic_shift_op, 1)
5821 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5822 semantic_shift_op, 1)
5823 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5824 semantic_arithmetic_addsubb_assign, 0)
5825 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5826 semantic_arithmetic_addsubb_assign, 0)
5827 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5828 semantic_arithmetic_assign, 0)
5829 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5830 semantic_arithmetic_assign, 0)
5831 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5832 semantic_arithmetic_assign, 0)
5833 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5834 semantic_arithmetic_assign, 0)
5835 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5836 semantic_arithmetic_assign, 0)
5837 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5838 semantic_arithmetic_assign, 0)
5839 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5840 semantic_arithmetic_assign, 0)
5841 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5842 semantic_arithmetic_assign, 0)
5844 static expression_t *parse_sub_expression(unsigned precedence)
5846 if(token.type < 0) {
5847 return expected_expression_error();
5850 expression_parser_function_t *parser
5851 = &expression_parsers[token.type];
5852 source_position_t source_position = token.source_position;
5855 if(parser->parser != NULL) {
5856 left = parser->parser(parser->precedence);
5858 left = parse_primary_expression();
5860 assert(left != NULL);
5861 left->base.source_position = source_position;
5864 if(token.type < 0) {
5865 return expected_expression_error();
5868 parser = &expression_parsers[token.type];
5869 if(parser->infix_parser == NULL)
5871 if(parser->infix_precedence < precedence)
5874 left = parser->infix_parser(parser->infix_precedence, left);
5876 assert(left != NULL);
5877 assert(left->kind != EXPR_UNKNOWN);
5878 left->base.source_position = source_position;
5885 * Parse an expression.
5887 static expression_t *parse_expression(void)
5889 return parse_sub_expression(1);
5893 * Register a parser for a prefix-like operator with given precedence.
5895 * @param parser the parser function
5896 * @param token_type the token type of the prefix token
5897 * @param precedence the precedence of the operator
5899 static void register_expression_parser(parse_expression_function parser,
5900 int token_type, unsigned precedence)
5902 expression_parser_function_t *entry = &expression_parsers[token_type];
5904 if(entry->parser != NULL) {
5905 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5906 panic("trying to register multiple expression parsers for a token");
5908 entry->parser = parser;
5909 entry->precedence = precedence;
5913 * Register a parser for an infix operator with given precedence.
5915 * @param parser the parser function
5916 * @param token_type the token type of the infix operator
5917 * @param precedence the precedence of the operator
5919 static void register_infix_parser(parse_expression_infix_function parser,
5920 int token_type, unsigned precedence)
5922 expression_parser_function_t *entry = &expression_parsers[token_type];
5924 if(entry->infix_parser != NULL) {
5925 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5926 panic("trying to register multiple infix expression parsers for a "
5929 entry->infix_parser = parser;
5930 entry->infix_precedence = precedence;
5934 * Initialize the expression parsers.
5936 static void init_expression_parsers(void)
5938 memset(&expression_parsers, 0, sizeof(expression_parsers));
5940 register_infix_parser(parse_array_expression, '[', 30);
5941 register_infix_parser(parse_call_expression, '(', 30);
5942 register_infix_parser(parse_select_expression, '.', 30);
5943 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
5944 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5946 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5949 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
5950 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
5951 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
5952 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
5953 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
5954 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
5955 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
5956 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
5957 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
5958 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
5959 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
5960 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
5961 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5962 T_EXCLAMATIONMARKEQUAL, 13);
5963 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
5964 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
5965 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
5966 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
5967 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
5968 register_infix_parser(parse_conditional_expression, '?', 7);
5969 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
5970 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
5971 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
5972 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
5973 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
5974 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
5975 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5976 T_LESSLESSEQUAL, 2);
5977 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5978 T_GREATERGREATEREQUAL, 2);
5979 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5981 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5983 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5986 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
5988 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
5989 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
5990 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
5991 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
5992 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
5993 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
5994 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5996 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5998 register_expression_parser(parse_sizeof, T_sizeof, 25);
5999 register_expression_parser(parse_alignof, T___alignof__, 25);
6000 register_expression_parser(parse_extension, T___extension__, 25);
6001 register_expression_parser(parse_builtin_classify_type,
6002 T___builtin_classify_type, 25);
6006 * Parse a asm statement constraints specification.
6008 static asm_constraint_t *parse_asm_constraints(void)
6010 asm_constraint_t *result = NULL;
6011 asm_constraint_t *last = NULL;
6013 while(token.type == T_STRING_LITERAL || token.type == '[') {
6014 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6015 memset(constraint, 0, sizeof(constraint[0]));
6017 if(token.type == '[') {
6019 if(token.type != T_IDENTIFIER) {
6020 parse_error_expected("while parsing asm constraint",
6024 constraint->symbol = token.v.symbol;
6029 constraint->constraints = parse_string_literals();
6031 constraint->expression = parse_expression();
6035 last->next = constraint;
6037 result = constraint;
6041 if(token.type != ',')
6052 * Parse a asm statement clobber specification.
6054 static asm_clobber_t *parse_asm_clobbers(void)
6056 asm_clobber_t *result = NULL;
6057 asm_clobber_t *last = NULL;
6059 while(token.type == T_STRING_LITERAL) {
6060 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6061 clobber->clobber = parse_string_literals();
6064 last->next = clobber;
6070 if(token.type != ',')
6079 * Parse an asm statement.
6081 static statement_t *parse_asm_statement(void)
6085 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6086 statement->base.source_position = token.source_position;
6088 asm_statement_t *asm_statement = &statement->asms;
6090 if(token.type == T_volatile) {
6092 asm_statement->is_volatile = true;
6096 add_anchor_token(')');
6097 add_anchor_token(':');
6098 asm_statement->asm_text = parse_string_literals();
6100 if(token.type != ':') {
6101 rem_anchor_token(':');
6106 asm_statement->inputs = parse_asm_constraints();
6107 if(token.type != ':') {
6108 rem_anchor_token(':');
6113 asm_statement->outputs = parse_asm_constraints();
6114 if(token.type != ':') {
6115 rem_anchor_token(':');
6118 rem_anchor_token(':');
6121 asm_statement->clobbers = parse_asm_clobbers();
6124 rem_anchor_token(')');
6129 return create_invalid_statement();
6133 * Parse a case statement.
6135 static statement_t *parse_case_statement(void)
6139 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6141 statement->base.source_position = token.source_position;
6142 statement->case_label.expression = parse_expression();
6144 if (c_mode & _GNUC) {
6145 if (token.type == T_DOTDOTDOT) {
6147 statement->case_label.end_range = parse_expression();
6153 if (! is_constant_expression(statement->case_label.expression)) {
6154 errorf(statement->base.source_position,
6155 "case label does not reduce to an integer constant");
6157 /* TODO: check if the case label is already known */
6158 if (current_switch != NULL) {
6159 /* link all cases into the switch statement */
6160 if (current_switch->last_case == NULL) {
6161 current_switch->first_case =
6162 current_switch->last_case = &statement->case_label;
6164 current_switch->last_case->next = &statement->case_label;
6167 errorf(statement->base.source_position,
6168 "case label not within a switch statement");
6171 statement->case_label.statement = parse_statement();
6175 return create_invalid_statement();
6179 * Finds an existing default label of a switch statement.
6181 static case_label_statement_t *
6182 find_default_label(const switch_statement_t *statement)
6184 case_label_statement_t *label = statement->first_case;
6185 for ( ; label != NULL; label = label->next) {
6186 if (label->expression == NULL)
6193 * Parse a default statement.
6195 static statement_t *parse_default_statement(void)
6199 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6201 statement->base.source_position = token.source_position;
6204 if (current_switch != NULL) {
6205 const case_label_statement_t *def_label = find_default_label(current_switch);
6206 if (def_label != NULL) {
6207 errorf(HERE, "multiple default labels in one switch");
6208 errorf(def_label->base.source_position,
6209 "this is the first default label");
6211 /* link all cases into the switch statement */
6212 if (current_switch->last_case == NULL) {
6213 current_switch->first_case =
6214 current_switch->last_case = &statement->case_label;
6216 current_switch->last_case->next = &statement->case_label;
6220 errorf(statement->base.source_position,
6221 "'default' label not within a switch statement");
6223 statement->case_label.statement = parse_statement();
6227 return create_invalid_statement();
6231 * Return the declaration for a given label symbol or create a new one.
6233 static declaration_t *get_label(symbol_t *symbol)
6235 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6236 assert(current_function != NULL);
6237 /* if we found a label in the same function, then we already created the
6239 if(candidate != NULL
6240 && candidate->parent_scope == ¤t_function->scope) {
6244 /* otherwise we need to create a new one */
6245 declaration_t *const declaration = allocate_declaration_zero();
6246 declaration->namespc = NAMESPACE_LABEL;
6247 declaration->symbol = symbol;
6249 label_push(declaration);
6255 * Parse a label statement.
6257 static statement_t *parse_label_statement(void)
6259 assert(token.type == T_IDENTIFIER);
6260 symbol_t *symbol = token.v.symbol;
6263 declaration_t *label = get_label(symbol);
6265 /* if source position is already set then the label is defined twice,
6266 * otherwise it was just mentioned in a goto so far */
6267 if(label->source_position.input_name != NULL) {
6268 errorf(HERE, "duplicate label '%Y'", symbol);
6269 errorf(label->source_position, "previous definition of '%Y' was here",
6272 label->source_position = token.source_position;
6275 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6277 statement->base.source_position = token.source_position;
6278 statement->label.label = label;
6282 if(token.type == '}') {
6283 /* TODO only warn? */
6285 warningf(HERE, "label at end of compound statement");
6286 statement->label.statement = create_empty_statement();
6288 errorf(HERE, "label at end of compound statement");
6289 statement->label.statement = create_invalid_statement();
6293 if (token.type == ';') {
6294 /* eat an empty statement here, to avoid the warning about an empty
6295 * after a label. label:; is commonly used to have a label before
6297 statement->label.statement = create_empty_statement();
6300 statement->label.statement = parse_statement();
6304 /* remember the labels's in a list for later checking */
6305 if (label_last == NULL) {
6306 label_first = &statement->label;
6308 label_last->next = &statement->label;
6310 label_last = &statement->label;
6316 * Parse an if statement.
6318 static statement_t *parse_if(void)
6322 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6323 statement->base.source_position = token.source_position;
6326 add_anchor_token(')');
6327 statement->ifs.condition = parse_expression();
6328 rem_anchor_token(')');
6331 add_anchor_token(T_else);
6332 statement->ifs.true_statement = parse_statement();
6333 rem_anchor_token(T_else);
6335 if(token.type == T_else) {
6337 statement->ifs.false_statement = parse_statement();
6342 return create_invalid_statement();
6346 * Parse a switch statement.
6348 static statement_t *parse_switch(void)
6352 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6353 statement->base.source_position = token.source_position;
6356 expression_t *const expr = parse_expression();
6357 type_t * type = skip_typeref(expr->base.type);
6358 if (is_type_integer(type)) {
6359 type = promote_integer(type);
6360 } else if (is_type_valid(type)) {
6361 errorf(expr->base.source_position,
6362 "switch quantity is not an integer, but '%T'", type);
6363 type = type_error_type;
6365 statement->switchs.expression = create_implicit_cast(expr, type);
6368 switch_statement_t *rem = current_switch;
6369 current_switch = &statement->switchs;
6370 statement->switchs.body = parse_statement();
6371 current_switch = rem;
6373 if (warning.switch_default
6374 && find_default_label(&statement->switchs) == NULL) {
6375 warningf(statement->base.source_position, "switch has no default case");
6380 return create_invalid_statement();
6383 static statement_t *parse_loop_body(statement_t *const loop)
6385 statement_t *const rem = current_loop;
6386 current_loop = loop;
6388 statement_t *const body = parse_statement();
6395 * Parse a while statement.
6397 static statement_t *parse_while(void)
6401 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6402 statement->base.source_position = token.source_position;
6405 add_anchor_token(')');
6406 statement->whiles.condition = parse_expression();
6407 rem_anchor_token(')');
6410 statement->whiles.body = parse_loop_body(statement);
6414 return create_invalid_statement();
6418 * Parse a do statement.
6420 static statement_t *parse_do(void)
6424 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6426 statement->base.source_position = token.source_position;
6428 add_anchor_token(T_while);
6429 statement->do_while.body = parse_loop_body(statement);
6430 rem_anchor_token(T_while);
6434 add_anchor_token(')');
6435 statement->do_while.condition = parse_expression();
6436 rem_anchor_token(')');
6442 return create_invalid_statement();
6446 * Parse a for statement.
6448 static statement_t *parse_for(void)
6452 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6453 statement->base.source_position = token.source_position;
6455 int top = environment_top();
6456 scope_t *last_scope = scope;
6457 set_scope(&statement->fors.scope);
6460 add_anchor_token(')');
6462 if(token.type != ';') {
6463 if(is_declaration_specifier(&token, false)) {
6464 parse_declaration(record_declaration);
6466 expression_t *const init = parse_expression();
6467 statement->fors.initialisation = init;
6468 if (warning.unused_value && !expression_has_effect(init)) {
6469 warningf(init->base.source_position,
6470 "initialisation of 'for'-statement has no effect");
6478 if(token.type != ';') {
6479 statement->fors.condition = parse_expression();
6482 if(token.type != ')') {
6483 expression_t *const step = parse_expression();
6484 statement->fors.step = step;
6485 if (warning.unused_value && !expression_has_effect(step)) {
6486 warningf(step->base.source_position,
6487 "step of 'for'-statement has no effect");
6490 rem_anchor_token(')');
6492 statement->fors.body = parse_loop_body(statement);
6494 assert(scope == &statement->fors.scope);
6495 set_scope(last_scope);
6496 environment_pop_to(top);
6501 rem_anchor_token(')');
6502 assert(scope == &statement->fors.scope);
6503 set_scope(last_scope);
6504 environment_pop_to(top);
6506 return create_invalid_statement();
6510 * Parse a goto statement.
6512 static statement_t *parse_goto(void)
6516 if(token.type != T_IDENTIFIER) {
6517 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6521 symbol_t *symbol = token.v.symbol;
6524 declaration_t *label = get_label(symbol);
6526 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6527 statement->base.source_position = token.source_position;
6529 statement->gotos.label = label;
6531 /* remember the goto's in a list for later checking */
6532 if (goto_last == NULL) {
6533 goto_first = &statement->gotos;
6535 goto_last->next = &statement->gotos;
6537 goto_last = &statement->gotos;
6543 return create_invalid_statement();
6547 * Parse a continue statement.
6549 static statement_t *parse_continue(void)
6551 statement_t *statement;
6552 if (current_loop == NULL) {
6553 errorf(HERE, "continue statement not within loop");
6556 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6558 statement->base.source_position = token.source_position;
6566 return create_invalid_statement();
6570 * Parse a break statement.
6572 static statement_t *parse_break(void)
6574 statement_t *statement;
6575 if (current_switch == NULL && current_loop == NULL) {
6576 errorf(HERE, "break statement not within loop or switch");
6579 statement = allocate_statement_zero(STATEMENT_BREAK);
6581 statement->base.source_position = token.source_position;
6589 return create_invalid_statement();
6593 * Check if a given declaration represents a local variable.
6595 static bool is_local_var_declaration(const declaration_t *declaration) {
6596 switch ((storage_class_tag_t) declaration->storage_class) {
6597 case STORAGE_CLASS_AUTO:
6598 case STORAGE_CLASS_REGISTER: {
6599 const type_t *type = skip_typeref(declaration->type);
6600 if(is_type_function(type)) {
6612 * Check if a given declaration represents a variable.
6614 static bool is_var_declaration(const declaration_t *declaration) {
6615 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6618 const type_t *type = skip_typeref(declaration->type);
6619 return !is_type_function(type);
6623 * Check if a given expression represents a local variable.
6625 static bool is_local_variable(const expression_t *expression)
6627 if (expression->base.kind != EXPR_REFERENCE) {
6630 const declaration_t *declaration = expression->reference.declaration;
6631 return is_local_var_declaration(declaration);
6635 * Check if a given expression represents a local variable and
6636 * return its declaration then, else return NULL.
6638 declaration_t *expr_is_variable(const expression_t *expression)
6640 if (expression->base.kind != EXPR_REFERENCE) {
6643 declaration_t *declaration = expression->reference.declaration;
6644 if (is_var_declaration(declaration))
6650 * Parse a return statement.
6652 static statement_t *parse_return(void)
6656 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6657 statement->base.source_position = token.source_position;
6659 expression_t *return_value = NULL;
6660 if(token.type != ';') {
6661 return_value = parse_expression();
6665 const type_t *const func_type = current_function->type;
6666 assert(is_type_function(func_type));
6667 type_t *const return_type = skip_typeref(func_type->function.return_type);
6669 if(return_value != NULL) {
6670 type_t *return_value_type = skip_typeref(return_value->base.type);
6672 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6673 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6674 warningf(statement->base.source_position,
6675 "'return' with a value, in function returning void");
6676 return_value = NULL;
6678 type_t *const res_type = semantic_assign(return_type,
6679 return_value, "'return'");
6680 if (res_type == NULL) {
6681 errorf(statement->base.source_position,
6682 "cannot return something of type '%T' in function returning '%T'",
6683 return_value->base.type, return_type);
6685 return_value = create_implicit_cast(return_value, res_type);
6688 /* check for returning address of a local var */
6689 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6690 const expression_t *expression = return_value->unary.value;
6691 if (is_local_variable(expression)) {
6692 warningf(statement->base.source_position,
6693 "function returns address of local variable");
6697 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6698 warningf(statement->base.source_position,
6699 "'return' without value, in function returning non-void");
6702 statement->returns.value = return_value;
6706 return create_invalid_statement();
6710 * Parse a declaration statement.
6712 static statement_t *parse_declaration_statement(void)
6714 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6716 statement->base.source_position = token.source_position;
6718 declaration_t *before = last_declaration;
6719 parse_declaration(record_declaration);
6721 if(before == NULL) {
6722 statement->declaration.declarations_begin = scope->declarations;
6724 statement->declaration.declarations_begin = before->next;
6726 statement->declaration.declarations_end = last_declaration;
6732 * Parse an expression statement, ie. expr ';'.
6734 static statement_t *parse_expression_statement(void)
6736 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6738 statement->base.source_position = token.source_position;
6739 expression_t *const expr = parse_expression();
6740 statement->expression.expression = expr;
6742 if (warning.unused_value && !expression_has_effect(expr)) {
6743 warningf(expr->base.source_position, "statement has no effect");
6750 return create_invalid_statement();
6754 * Parse a statement.
6756 static statement_t *parse_statement(void)
6758 statement_t *statement = NULL;
6760 /* declaration or statement */
6761 add_anchor_token(';');
6762 switch(token.type) {
6764 statement = parse_asm_statement();
6768 statement = parse_case_statement();
6772 statement = parse_default_statement();
6776 statement = parse_compound_statement();
6780 statement = parse_if();
6784 statement = parse_switch();
6788 statement = parse_while();
6792 statement = parse_do();
6796 statement = parse_for();
6800 statement = parse_goto();
6804 statement = parse_continue();
6808 statement = parse_break();
6812 statement = parse_return();
6816 if(warning.empty_statement) {
6817 warningf(HERE, "statement is empty");
6819 statement = create_empty_statement();
6824 if(look_ahead(1)->type == ':') {
6825 statement = parse_label_statement();
6829 if(is_typedef_symbol(token.v.symbol)) {
6830 statement = parse_declaration_statement();
6834 statement = parse_expression_statement();
6837 case T___extension__:
6838 /* this can be a prefix to a declaration or an expression statement */
6839 /* we simply eat it now and parse the rest with tail recursion */
6842 } while(token.type == T___extension__);
6843 statement = parse_statement();
6847 statement = parse_declaration_statement();
6851 statement = parse_expression_statement();
6854 rem_anchor_token(';');
6856 assert(statement != NULL
6857 && statement->base.source_position.input_name != NULL);
6863 * Parse a compound statement.
6865 static statement_t *parse_compound_statement(void)
6867 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6869 statement->base.source_position = token.source_position;
6872 add_anchor_token('}');
6874 int top = environment_top();
6875 scope_t *last_scope = scope;
6876 set_scope(&statement->compound.scope);
6878 statement_t *last_statement = NULL;
6880 while(token.type != '}' && token.type != T_EOF) {
6881 statement_t *sub_statement = parse_statement();
6882 if(is_invalid_statement(sub_statement)) {
6883 /* an error occurred. if we are at an anchor, return */
6889 if(last_statement != NULL) {
6890 last_statement->base.next = sub_statement;
6892 statement->compound.statements = sub_statement;
6895 while(sub_statement->base.next != NULL)
6896 sub_statement = sub_statement->base.next;
6898 last_statement = sub_statement;
6901 if(token.type == '}') {
6904 errorf(statement->base.source_position,
6905 "end of file while looking for closing '}'");
6909 rem_anchor_token('}');
6910 assert(scope == &statement->compound.scope);
6911 set_scope(last_scope);
6912 environment_pop_to(top);
6918 * Initialize builtin types.
6920 static void initialize_builtin_types(void)
6922 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
6923 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
6924 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
6925 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
6926 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
6927 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6928 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
6929 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
6931 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
6932 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6933 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
6934 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
6938 * Check for unused global static functions and variables
6940 static void check_unused_globals(void)
6942 if (!warning.unused_function && !warning.unused_variable)
6945 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6946 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6949 type_t *const type = decl->type;
6951 if (is_type_function(skip_typeref(type))) {
6952 if (!warning.unused_function || decl->is_inline)
6955 s = (decl->init.statement != NULL ? "defined" : "declared");
6957 if (!warning.unused_variable)
6963 warningf(decl->source_position, "'%#T' %s but not used",
6964 type, decl->symbol, s);
6969 * Parse a translation unit.
6971 static translation_unit_t *parse_translation_unit(void)
6973 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6975 assert(global_scope == NULL);
6976 global_scope = &unit->scope;
6978 assert(scope == NULL);
6979 set_scope(&unit->scope);
6981 initialize_builtin_types();
6983 while(token.type != T_EOF) {
6984 if (token.type == ';') {
6985 /* TODO error in strict mode */
6986 warningf(HERE, "stray ';' outside of function");
6989 parse_external_declaration();
6993 assert(scope == &unit->scope);
6995 last_declaration = NULL;
6997 assert(global_scope == &unit->scope);
6998 check_unused_globals();
6999 global_scope = NULL;
7007 * @return the translation unit or NULL if errors occurred.
7009 translation_unit_t *parse(void)
7011 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7012 label_stack = NEW_ARR_F(stack_entry_t, 0);
7013 diagnostic_count = 0;
7017 type_set_output(stderr);
7018 ast_set_output(stderr);
7020 lookahead_bufpos = 0;
7021 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7024 translation_unit_t *unit = parse_translation_unit();
7026 DEL_ARR_F(environment_stack);
7027 DEL_ARR_F(label_stack);
7033 * Initialize the parser.
7035 void init_parser(void)
7038 /* add predefined symbols for extended-decl-modifier */
7039 sym_align = symbol_table_insert("align");
7040 sym_allocate = symbol_table_insert("allocate");
7041 sym_dllimport = symbol_table_insert("dllimport");
7042 sym_dllexport = symbol_table_insert("dllexport");
7043 sym_naked = symbol_table_insert("naked");
7044 sym_noinline = symbol_table_insert("noinline");
7045 sym_noreturn = symbol_table_insert("noreturn");
7046 sym_nothrow = symbol_table_insert("nothrow");
7047 sym_novtable = symbol_table_insert("novtable");
7048 sym_property = symbol_table_insert("property");
7049 sym_get = symbol_table_insert("get");
7050 sym_put = symbol_table_insert("put");
7051 sym_selectany = symbol_table_insert("selectany");
7052 sym_thread = symbol_table_insert("thread");
7053 sym_uuid = symbol_table_insert("uuid");
7054 sym_deprecated = symbol_table_insert("deprecated");
7056 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7058 init_expression_parsers();
7059 obstack_init(&temp_obst);
7061 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7062 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7066 * Terminate the parser.
7068 void exit_parser(void)
7070 obstack_free(&temp_obst, NULL);