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 gnu_attribute_t gnu_attribute_t;
52 struct gnu_attribute_t {
53 gnu_attribute_kind_t kind;
54 gnu_attribute_t *next;
63 typedef struct declaration_specifiers_t declaration_specifiers_t;
64 struct declaration_specifiers_t {
65 source_position_t source_position;
66 unsigned char declared_storage_class;
67 unsigned char alignment; /**< Alignment, 0 if not set. */
68 unsigned int is_inline : 1;
69 unsigned int deprecated : 1;
70 decl_modifiers_t decl_modifiers; /**< MS __declspec extended modifier mask */
71 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
72 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
73 symbol_t *get_property_sym; /**< the name of the get property if set. */
74 symbol_t *put_property_sym; /**< the name of the put property if set. */
79 * An environment for parsing initializers (and compound literals).
81 typedef struct parse_initializer_env_t {
82 type_t *type; /**< the type of the initializer. In case of an
83 array type with unspecified size this gets
84 adjusted to the actual size. */
85 declaration_t *declaration; /**< the declaration that is initialized if any */
86 bool must_be_constant;
87 } parse_initializer_env_t;
89 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
92 static token_t lookahead_buffer[MAX_LOOKAHEAD];
93 static int lookahead_bufpos;
94 static stack_entry_t *environment_stack = NULL;
95 static stack_entry_t *label_stack = NULL;
96 static scope_t *global_scope = NULL;
97 static scope_t *scope = NULL;
98 static declaration_t *last_declaration = NULL;
99 static declaration_t *current_function = NULL;
100 static switch_statement_t *current_switch = NULL;
101 static statement_t *current_loop = NULL;
102 static goto_statement_t *goto_first = NULL;
103 static goto_statement_t *goto_last = NULL;
104 static label_statement_t *label_first = NULL;
105 static label_statement_t *label_last = NULL;
106 static struct obstack temp_obst;
108 /* symbols for Microsoft extended-decl-modifier */
109 static const symbol_t *sym_align = NULL;
110 static const symbol_t *sym_allocate = NULL;
111 static const symbol_t *sym_dllimport = NULL;
112 static const symbol_t *sym_dllexport = NULL;
113 static const symbol_t *sym_naked = NULL;
114 static const symbol_t *sym_noinline = NULL;
115 static const symbol_t *sym_noreturn = NULL;
116 static const symbol_t *sym_nothrow = NULL;
117 static const symbol_t *sym_novtable = NULL;
118 static const symbol_t *sym_property = NULL;
119 static const symbol_t *sym_get = NULL;
120 static const symbol_t *sym_put = NULL;
121 static const symbol_t *sym_selectany = NULL;
122 static const symbol_t *sym_thread = NULL;
123 static const symbol_t *sym_uuid = NULL;
124 static const symbol_t *sym_deprecated = NULL;
125 static const symbol_t *sym_restrict = NULL;
126 static const symbol_t *sym_noalias = NULL;
128 /** The token anchor set */
129 static unsigned char token_anchor_set[T_LAST_TOKEN];
131 /** The current source position. */
132 #define HERE token.source_position
134 static type_t *type_valist;
136 static statement_t *parse_compound_statement(void);
137 static statement_t *parse_statement(void);
139 static expression_t *parse_sub_expression(unsigned precedence);
140 static expression_t *parse_expression(void);
141 static type_t *parse_typename(void);
143 static void parse_compound_type_entries(declaration_t *compound_declaration);
144 static declaration_t *parse_declarator(
145 const declaration_specifiers_t *specifiers, bool may_be_abstract);
146 static declaration_t *record_declaration(declaration_t *declaration);
148 static void semantic_comparison(binary_expression_t *expression);
150 #define STORAGE_CLASSES \
157 #define TYPE_QUALIFIERS \
164 #ifdef PROVIDE_COMPLEX
165 #define COMPLEX_SPECIFIERS \
167 #define IMAGINARY_SPECIFIERS \
170 #define COMPLEX_SPECIFIERS
171 #define IMAGINARY_SPECIFIERS
174 #define TYPE_SPECIFIERS \
189 case T___builtin_va_list: \
194 #define DECLARATION_START \
199 #define TYPENAME_START \
204 * Allocate an AST node with given size and
205 * initialize all fields with zero.
207 static void *allocate_ast_zero(size_t size)
209 void *res = allocate_ast(size);
210 memset(res, 0, size);
214 static declaration_t *allocate_declaration_zero(void)
216 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
217 declaration->type = type_error_type;
218 declaration->alignment = 0;
223 * Returns the size of a statement node.
225 * @param kind the statement kind
227 static size_t get_statement_struct_size(statement_kind_t kind)
229 static const size_t sizes[] = {
230 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
231 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
232 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
233 [STATEMENT_RETURN] = sizeof(return_statement_t),
234 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
235 [STATEMENT_IF] = sizeof(if_statement_t),
236 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
237 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
238 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
239 [STATEMENT_BREAK] = sizeof(statement_base_t),
240 [STATEMENT_GOTO] = sizeof(goto_statement_t),
241 [STATEMENT_LABEL] = sizeof(label_statement_t),
242 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
243 [STATEMENT_WHILE] = sizeof(while_statement_t),
244 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
245 [STATEMENT_FOR] = sizeof(for_statement_t),
246 [STATEMENT_ASM] = sizeof(asm_statement_t)
248 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
249 assert(sizes[kind] != 0);
254 * Returns the size of an expression node.
256 * @param kind the expression kind
258 static size_t get_expression_struct_size(expression_kind_t kind)
260 static const size_t sizes[] = {
261 [EXPR_INVALID] = sizeof(expression_base_t),
262 [EXPR_REFERENCE] = sizeof(reference_expression_t),
263 [EXPR_CONST] = sizeof(const_expression_t),
264 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
265 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
266 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
267 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
268 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
269 [EXPR_CALL] = sizeof(call_expression_t),
270 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
271 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
272 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
273 [EXPR_SELECT] = sizeof(select_expression_t),
274 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
275 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
276 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
277 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
278 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
279 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
280 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
281 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
282 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
283 [EXPR_VA_START] = sizeof(va_start_expression_t),
284 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
285 [EXPR_STATEMENT] = sizeof(statement_expression_t),
287 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
288 return sizes[EXPR_UNARY_FIRST];
290 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
291 return sizes[EXPR_BINARY_FIRST];
293 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
294 assert(sizes[kind] != 0);
299 * Allocate a statement node of given kind and initialize all
302 static statement_t *allocate_statement_zero(statement_kind_t kind)
304 size_t size = get_statement_struct_size(kind);
305 statement_t *res = allocate_ast_zero(size);
307 res->base.kind = kind;
312 * Allocate an expression node of given kind and initialize all
315 static expression_t *allocate_expression_zero(expression_kind_t kind)
317 size_t size = get_expression_struct_size(kind);
318 expression_t *res = allocate_ast_zero(size);
320 res->base.kind = kind;
321 res->base.type = type_error_type;
326 * Creates a new invalid expression.
328 static expression_t *create_invalid_expression(void)
330 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
331 expression->base.source_position = token.source_position;
336 * Creates a new invalid statement.
338 static statement_t *create_invalid_statement(void)
340 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
341 statement->base.source_position = token.source_position;
346 * Allocate a new empty statement.
348 static statement_t *create_empty_statement(void)
350 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
351 statement->base.source_position = token.source_position;
356 * Returns the size of a type node.
358 * @param kind the type kind
360 static size_t get_type_struct_size(type_kind_t kind)
362 static const size_t sizes[] = {
363 [TYPE_ATOMIC] = sizeof(atomic_type_t),
364 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
365 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
366 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
367 [TYPE_ENUM] = sizeof(enum_type_t),
368 [TYPE_FUNCTION] = sizeof(function_type_t),
369 [TYPE_POINTER] = sizeof(pointer_type_t),
370 [TYPE_ARRAY] = sizeof(array_type_t),
371 [TYPE_BUILTIN] = sizeof(builtin_type_t),
372 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
373 [TYPE_TYPEOF] = sizeof(typeof_type_t),
375 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
376 assert(kind <= TYPE_TYPEOF);
377 assert(sizes[kind] != 0);
382 * Allocate a type node of given kind and initialize all
385 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
387 size_t size = get_type_struct_size(kind);
388 type_t *res = obstack_alloc(type_obst, size);
389 memset(res, 0, size);
391 res->base.kind = kind;
392 res->base.source_position = source_position;
397 * Returns the size of an initializer node.
399 * @param kind the initializer kind
401 static size_t get_initializer_size(initializer_kind_t kind)
403 static const size_t sizes[] = {
404 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
405 [INITIALIZER_STRING] = sizeof(initializer_string_t),
406 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
407 [INITIALIZER_LIST] = sizeof(initializer_list_t),
408 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
410 assert(kind < sizeof(sizes) / sizeof(*sizes));
411 assert(sizes[kind] != 0);
416 * Allocate an initializer node of given kind and initialize all
419 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
421 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
428 * Free a type from the type obstack.
430 static void free_type(void *type)
432 obstack_free(type_obst, type);
436 * Returns the index of the top element of the environment stack.
438 static size_t environment_top(void)
440 return ARR_LEN(environment_stack);
444 * Returns the index of the top element of the label stack.
446 static size_t label_top(void)
448 return ARR_LEN(label_stack);
452 * Return the next token.
454 static inline void next_token(void)
456 token = lookahead_buffer[lookahead_bufpos];
457 lookahead_buffer[lookahead_bufpos] = lexer_token;
460 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
463 print_token(stderr, &token);
464 fprintf(stderr, "\n");
469 * Return the next token with a given lookahead.
471 static inline const token_t *look_ahead(int num)
473 assert(num > 0 && num <= MAX_LOOKAHEAD);
474 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
475 return &lookahead_buffer[pos];
479 * Adds a token to the token anchor set (a multi-set).
481 static void add_anchor_token(int token_type) {
482 assert(0 <= token_type && token_type < T_LAST_TOKEN);
483 ++token_anchor_set[token_type];
487 * Remove a token from the token anchor set (a multi-set).
489 static void rem_anchor_token(int token_type) {
490 assert(0 <= token_type && token_type < T_LAST_TOKEN);
491 --token_anchor_set[token_type];
494 static bool at_anchor(void) {
497 return token_anchor_set[token.type];
501 * Eat tokens until a matching token is found.
503 static void eat_until_matching_token(int type) {
504 unsigned parenthesis_count = 0;
505 unsigned brace_count = 0;
506 unsigned bracket_count = 0;
507 int end_token = type;
516 while(token.type != end_token ||
517 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
521 case '(': ++parenthesis_count; break;
522 case '{': ++brace_count; break;
523 case '[': ++bracket_count; break;
525 if(parenthesis_count > 0)
533 if(bracket_count > 0)
544 * Eat input tokens until an anchor is found.
546 static void eat_until_anchor(void) {
547 if(token.type == T_EOF)
549 while(token_anchor_set[token.type] == 0) {
550 if(token.type == '(' || token.type == '{' || token.type == '[')
551 eat_until_matching_token(token.type);
552 if(token.type == T_EOF)
558 static void eat_block(void) {
559 eat_until_matching_token('{');
560 if(token.type == '}')
565 * eat all token until a ';' is reached
566 * or a stop token is found.
568 static void eat_statement(void) {
569 eat_until_matching_token(';');
570 if(token.type == ';')
574 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
577 * Report a parse error because an expected token was not found.
579 static void parse_error_expected(const char *message, ...)
581 if(message != NULL) {
582 errorf(HERE, "%s", message);
585 va_start(ap, message);
586 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
591 * Report a type error.
593 static void type_error(const char *msg, const source_position_t source_position,
596 errorf(source_position, "%s, but found type '%T'", msg, type);
600 * Report an incompatible type.
602 static void type_error_incompatible(const char *msg,
603 const source_position_t source_position, type_t *type1, type_t *type2)
605 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
609 * Expect the the current token is the expected token.
610 * If not, generate an error, eat the current statement,
611 * and goto the end_error label.
613 #define expect(expected) \
615 if(UNLIKELY(token.type != (expected))) { \
616 parse_error_expected(NULL, (expected), 0); \
617 add_anchor_token(expected); \
618 eat_until_anchor(); \
619 rem_anchor_token(expected); \
625 static void set_scope(scope_t *new_scope)
628 scope->last_declaration = last_declaration;
632 last_declaration = new_scope->last_declaration;
636 * Search a symbol in a given namespace and returns its declaration or
637 * NULL if this symbol was not found.
639 static declaration_t *get_declaration(const symbol_t *const symbol,
640 const namespace_t namespc)
642 declaration_t *declaration = symbol->declaration;
643 for( ; declaration != NULL; declaration = declaration->symbol_next) {
644 if(declaration->namespc == namespc)
652 * pushs an environment_entry on the environment stack and links the
653 * corresponding symbol to the new entry
655 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
657 symbol_t *symbol = declaration->symbol;
658 namespace_t namespc = (namespace_t) declaration->namespc;
660 /* replace/add declaration into declaration list of the symbol */
661 declaration_t *iter = symbol->declaration;
663 symbol->declaration = declaration;
665 declaration_t *iter_last = NULL;
666 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
667 /* replace an entry? */
668 if(iter->namespc == namespc) {
669 if(iter_last == NULL) {
670 symbol->declaration = declaration;
672 iter_last->symbol_next = declaration;
674 declaration->symbol_next = iter->symbol_next;
679 assert(iter_last->symbol_next == NULL);
680 iter_last->symbol_next = declaration;
684 /* remember old declaration */
686 entry.symbol = symbol;
687 entry.old_declaration = iter;
688 entry.namespc = (unsigned short) namespc;
689 ARR_APP1(stack_entry_t, *stack_ptr, entry);
692 static void environment_push(declaration_t *declaration)
694 assert(declaration->source_position.input_name != NULL);
695 assert(declaration->parent_scope != NULL);
696 stack_push(&environment_stack, declaration);
699 static void label_push(declaration_t *declaration)
701 declaration->parent_scope = ¤t_function->scope;
702 stack_push(&label_stack, declaration);
706 * pops symbols from the environment stack until @p new_top is the top element
708 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
710 stack_entry_t *stack = *stack_ptr;
711 size_t top = ARR_LEN(stack);
714 assert(new_top <= top);
718 for(i = top; i > new_top; --i) {
719 stack_entry_t *entry = &stack[i - 1];
721 declaration_t *old_declaration = entry->old_declaration;
722 symbol_t *symbol = entry->symbol;
723 namespace_t namespc = (namespace_t)entry->namespc;
725 /* replace/remove declaration */
726 declaration_t *declaration = symbol->declaration;
727 assert(declaration != NULL);
728 if(declaration->namespc == namespc) {
729 if(old_declaration == NULL) {
730 symbol->declaration = declaration->symbol_next;
732 symbol->declaration = old_declaration;
735 declaration_t *iter_last = declaration;
736 declaration_t *iter = declaration->symbol_next;
737 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
738 /* replace an entry? */
739 if(iter->namespc == namespc) {
740 assert(iter_last != NULL);
741 iter_last->symbol_next = old_declaration;
742 if(old_declaration != NULL) {
743 old_declaration->symbol_next = iter->symbol_next;
748 assert(iter != NULL);
752 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
755 static void environment_pop_to(size_t new_top)
757 stack_pop_to(&environment_stack, new_top);
760 static void label_pop_to(size_t new_top)
762 stack_pop_to(&label_stack, new_top);
766 static int get_rank(const type_t *type)
768 assert(!is_typeref(type));
769 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
770 * and esp. footnote 108). However we can't fold constants (yet), so we
771 * can't decide whether unsigned int is possible, while int always works.
772 * (unsigned int would be preferable when possible... for stuff like
773 * struct { enum { ... } bla : 4; } ) */
774 if(type->kind == TYPE_ENUM)
775 return ATOMIC_TYPE_INT;
777 assert(type->kind == TYPE_ATOMIC);
778 return type->atomic.akind;
781 static type_t *promote_integer(type_t *type)
783 if(type->kind == TYPE_BITFIELD)
784 type = type->bitfield.base;
786 if(get_rank(type) < ATOMIC_TYPE_INT)
793 * Create a cast expression.
795 * @param expression the expression to cast
796 * @param dest_type the destination type
798 static expression_t *create_cast_expression(expression_t *expression,
801 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
803 cast->unary.value = expression;
804 cast->base.type = dest_type;
810 * Check if a given expression represents the 0 pointer constant.
812 static bool is_null_pointer_constant(const expression_t *expression)
814 /* skip void* cast */
815 if(expression->kind == EXPR_UNARY_CAST
816 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
817 expression = expression->unary.value;
820 /* TODO: not correct yet, should be any constant integer expression
821 * which evaluates to 0 */
822 if (expression->kind != EXPR_CONST)
825 type_t *const type = skip_typeref(expression->base.type);
826 if (!is_type_integer(type))
829 return expression->conste.v.int_value == 0;
833 * Create an implicit cast expression.
835 * @param expression the expression to cast
836 * @param dest_type the destination type
838 static expression_t *create_implicit_cast(expression_t *expression,
841 type_t *const source_type = expression->base.type;
843 if (source_type == dest_type)
846 return create_cast_expression(expression, dest_type);
849 /** Implements the rules from § 6.5.16.1 */
850 static type_t *semantic_assign(type_t *orig_type_left,
851 const expression_t *const right,
853 source_position_t source_position)
855 type_t *const orig_type_right = right->base.type;
856 type_t *const type_left = skip_typeref(orig_type_left);
857 type_t *const type_right = skip_typeref(orig_type_right);
859 if(is_type_pointer(type_left)) {
860 if(is_null_pointer_constant(right)) {
861 return orig_type_left;
862 } else if(is_type_pointer(type_right)) {
863 type_t *points_to_left
864 = skip_typeref(type_left->pointer.points_to);
865 type_t *points_to_right
866 = skip_typeref(type_right->pointer.points_to);
868 /* the left type has all qualifiers from the right type */
869 unsigned missing_qualifiers
870 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
871 if(missing_qualifiers != 0) {
872 errorf(source_position,
873 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
874 return orig_type_left;
877 points_to_left = get_unqualified_type(points_to_left);
878 points_to_right = get_unqualified_type(points_to_right);
880 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
881 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
882 return orig_type_left;
885 if (!types_compatible(points_to_left, points_to_right)) {
886 warningf(source_position,
887 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
888 orig_type_left, context, right, orig_type_right);
891 return orig_type_left;
892 } else if(is_type_integer(type_right)) {
893 warningf(source_position,
894 "%s makes pointer '%T' from integer '%T' without a cast",
895 context, orig_type_left, orig_type_right);
896 return orig_type_left;
898 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
899 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
900 && is_type_pointer(type_right))) {
901 return orig_type_left;
902 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
903 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
904 type_t *const unqual_type_left = get_unqualified_type(type_left);
905 type_t *const unqual_type_right = get_unqualified_type(type_right);
906 if (types_compatible(unqual_type_left, unqual_type_right)) {
907 return orig_type_left;
909 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
910 warningf(source_position,
911 "%s makes integer '%T' from pointer '%T' without a cast",
912 context, orig_type_left, orig_type_right);
913 return orig_type_left;
916 if (!is_type_valid(type_left))
919 if (!is_type_valid(type_right))
920 return orig_type_right;
925 static expression_t *parse_constant_expression(void)
927 /* start parsing at precedence 7 (conditional expression) */
928 expression_t *result = parse_sub_expression(7);
930 if(!is_constant_expression(result)) {
931 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
937 static expression_t *parse_assignment_expression(void)
939 /* start parsing at precedence 2 (assignment expression) */
940 return parse_sub_expression(2);
943 static type_t *make_global_typedef(const char *name, type_t *type)
945 symbol_t *const symbol = symbol_table_insert(name);
947 declaration_t *const declaration = allocate_declaration_zero();
948 declaration->namespc = NAMESPACE_NORMAL;
949 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
950 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
951 declaration->type = type;
952 declaration->symbol = symbol;
953 declaration->source_position = builtin_source_position;
955 record_declaration(declaration);
957 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
958 typedef_type->typedeft.declaration = declaration;
963 static string_t parse_string_literals(void)
965 assert(token.type == T_STRING_LITERAL);
966 string_t result = token.v.string;
970 while (token.type == T_STRING_LITERAL) {
971 result = concat_strings(&result, &token.v.string);
978 static const char *gnu_attribute_names[GNU_AK_LAST] = {
979 [GNU_AK_CONST] = "const",
980 [GNU_AK_VOLATILE] = "volatile",
981 [GNU_AK_CDECL] = "cdecl",
982 [GNU_AK_STDCALL] = "stdcall",
983 [GNU_AK_FASTCALL] = "fastcall",
984 [GNU_AK_DEPRECATED] = "deprecated",
985 [GNU_AK_NOINLINE] = "noinline",
986 [GNU_AK_NORETURN] = "noreturn",
987 [GNU_AK_NAKED] = "naked",
988 [GNU_AK_PURE] = "pure",
989 [GNU_AK_ALWAYS_INLINE] = "always_inline",
990 [GNU_AK_MALLOC] = "malloc",
991 [GNU_AK_WEAK] = "weak",
992 [GNU_AK_CONSTRUCTOR] = "constructor",
993 [GNU_AK_DESTRUCTOR] = "destructor",
994 [GNU_AK_NOTHROW] = "nothrow",
995 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
996 [GNU_AK_COMMON] = "coommon",
997 [GNU_AK_NOCOMMON] = "nocommon",
998 [GNU_AK_PACKED] = "packed",
999 [GNU_AK_SHARED] = "shared",
1000 [GNU_AK_NOTSHARED] = "notshared",
1001 [GNU_AK_USED] = "used",
1002 [GNU_AK_UNUSED] = "unused",
1003 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1004 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1005 [GNU_AK_LONGCALL] = "longcall",
1006 [GNU_AK_SHORTCALL] = "shortcall",
1007 [GNU_AK_LONG_CALL] = "long_call",
1008 [GNU_AK_SHORT_CALL] = "short_call",
1009 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1010 [GNU_AK_INTERRUPT] = "interrupt",
1011 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1012 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1013 [GNU_AK_NESTING] = "nesting",
1014 [GNU_AK_NEAR] = "near",
1015 [GNU_AK_FAR] = "far",
1016 [GNU_AK_SIGNAL] = "signal",
1017 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1018 [GNU_AK_TINY_DATA] = "tiny_data",
1019 [GNU_AK_SAVEALL] = "saveall",
1020 [GNU_AK_FLATTEN] = "flatten",
1021 [GNU_AK_SSEREGPARM] = "sseregparm",
1022 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1023 [GNU_AK_RETURN_TWICE] = "return_twice",
1024 [GNU_AK_MAY_ALIAS] = "may_alias",
1025 [GNU_AK_MS_STRUCT] = "ms_struct",
1026 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1027 [GNU_AK_ALIGNED] = "aligned",
1028 [GNU_AK_ALIAS] = "alias",
1029 [GNU_AK_SECTION] = "section",
1030 [GNU_AK_FORMAT] = "format",
1031 [GNU_AK_FORMAT_ARG] = "format_arg",
1032 [GNU_AK_WEAKREF] = "weakref",
1033 [GNU_AK_NONNULL] = "nonnull",
1034 [GNU_AK_TLS_MODEL] = "tls_model",
1035 [GNU_AK_VISIBILITY] = "visibility",
1036 [GNU_AK_REGPARM] = "regparm",
1037 [GNU_AK_MODEL] = "model",
1038 [GNU_AK_TRAP_EXIT] = "trap_exit",
1039 [GNU_AK_SP_SWITCH] = "sp_switch",
1040 [GNU_AK_SENTINEL] = "sentinel"
1044 * compare two string, ignoring double underscores on the second.
1046 static int strcmp_underscore(const char *s1, const char *s2) {
1047 if(s2[0] == '_' && s2[1] == '_') {
1049 size_t l1 = strlen(s1);
1050 if(l1 + 2 != strlen(s2)) {
1054 return strncmp(s1, s2, l1);
1056 return strcmp(s1, s2);
1060 * Allocate a new gnu temporal attribute.
1062 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1063 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1064 attribute->kind = kind;
1065 attribute->next = NULL;
1066 attribute->invalid = false;
1067 attribute->have_arguments = false;
1071 * parse one constant expression argument.
1073 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1074 expression_t *expression;
1075 add_anchor_token(')');
1076 expression = parse_constant_expression();
1077 rem_anchor_token(')');
1082 attribute->invalid = true;
1086 * parse a list of constant expressions arguments.
1088 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1089 expression_t *expression;
1090 add_anchor_token(')');
1091 add_anchor_token(',');
1093 expression = parse_constant_expression();
1094 if(token.type != ',')
1098 rem_anchor_token(',');
1099 rem_anchor_token(')');
1104 attribute->invalid = true;
1108 * parse one string literal argument.
1110 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute, string_t *string) {
1111 add_anchor_token('(');
1112 if(token.type != T_STRING_LITERAL) {
1113 parse_error_expected("while parsing attribute directive", T_STRING_LITERAL);
1116 *string = parse_string_literals();
1117 rem_anchor_token('(');
1121 attribute->invalid = true;
1125 * parse one tls model.
1127 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1128 static const char *tls_models[] = {
1134 string_t string = { NULL, 0 };
1135 parse_gnu_attribute_string_arg(attribute, &string);
1136 if(string.begin != NULL) {
1137 for(size_t i = 0; i < 4; ++i) {
1138 if(strcmp(tls_models[i], string.begin) == 0) {
1139 attribute->u.value = i;
1144 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1145 attribute->invalid = true;
1149 * parse one tls model.
1151 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1152 static const char *visibilities[] = {
1158 string_t string = { NULL, 0 };
1159 parse_gnu_attribute_string_arg(attribute, &string);
1160 if(string.begin != NULL) {
1161 for(size_t i = 0; i < 4; ++i) {
1162 if(strcmp(visibilities[i], string.begin) == 0) {
1163 attribute->u.value = i;
1168 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1169 attribute->invalid = true;
1173 * parse one (code) model.
1175 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1176 static const char *visibilities[] = {
1181 string_t string = { NULL, 0 };
1182 parse_gnu_attribute_string_arg(attribute, &string);
1183 if(string.begin != NULL) {
1184 for(int i = 0; i < 3; ++i) {
1185 if(strcmp(visibilities[i], string.begin) == 0) {
1186 attribute->u.value = i;
1191 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1192 attribute->invalid = true;
1196 * parse one interrupt argument.
1198 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1199 static const char *interrupts[] = {
1206 string_t string = { NULL, 0 };
1207 parse_gnu_attribute_string_arg(attribute, &string);
1208 if(string.begin != NULL) {
1209 for(size_t i = 0; i < 5; ++i) {
1210 if(strcmp(interrupts[i], string.begin) == 0) {
1211 attribute->u.value = i;
1216 errorf(HERE, "'%s' is an interrupt", string.begin);
1217 attribute->invalid = true;
1221 * parse ( identifier, const expression, const expression )
1223 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1224 static const char *format_names[] = {
1232 if(token.type != T_IDENTIFIER) {
1233 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER);
1236 const char *name = token.v.symbol->string;
1237 for(i = 0; i < 4; ++i) {
1238 if(strcmp_underscore(format_names[i], name) == 0)
1242 if(warning.attribute)
1243 warningf(HERE, "'%s' is an unrecognized format function type", name);
1248 add_anchor_token(')');
1249 add_anchor_token(',');
1250 parse_constant_expression();
1251 rem_anchor_token(',');
1252 rem_anchor_token('(');
1255 add_anchor_token(')');
1256 parse_constant_expression();
1257 rem_anchor_token('(');
1261 attribute->u.value = true;
1265 * Parse one GNU attribute.
1267 * Note that attribute names can be specified WITH or WITHOUT
1268 * double underscores, ie const or __const__.
1270 * The following attributes are parsed without arguments
1295 * no_instrument_function
1296 * warn_unused_result
1313 * externally_visible
1319 * The following attributes are parsed with arguments
1320 * aligned( const expression )
1321 * alias( string literal )
1322 * section( string literal )
1323 * format( identifier, const expression, const expression )
1324 * format_arg( const expression )
1325 * tls_model( string literal )
1326 * visibility( string literal )
1327 * regparm( const expression )
1328 * model( string leteral )
1329 * trap_exit( const expression )
1330 * sp_switch( string literal )
1332 * The following attributes might have arguments
1333 * weak_ref( string literal )
1334 * non_null( const expression // ',' )
1335 * interrupt( string literal )
1336 * sentinel( constant expression )
1338 static void parse_gnu_attribute(gnu_attribute_t **attributes)
1340 gnu_attribute_t *head = *attributes;
1341 gnu_attribute_t *last = *attributes;
1342 gnu_attribute_t *attribute;
1344 eat(T___attribute__);
1348 if(token.type != ')') {
1349 /* find the end of the list */
1351 while(last->next != NULL)
1355 /* non-empty attribute list */
1358 if(token.type == T_const) {
1360 } else if(token.type == T_volatile) {
1362 } else if(token.type == T_cdecl) {
1363 /* __attribute__((cdecl)), WITH ms mode */
1365 } else if(token.type != T_IDENTIFIER) {
1366 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1369 const symbol_t *sym = token.v.symbol;
1374 for(i = 0; i < GNU_AK_LAST; ++i) {
1375 if(strcmp_underscore(gnu_attribute_names[i], name) == 0)
1378 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1381 if(kind == GNU_AK_LAST) {
1382 if(warning.attribute)
1383 warningf(HERE, "'%s' attribute directive ignored", name);
1385 /* skip possible arguments */
1386 if(token.type == '(') {
1387 eat_until_matching_token(')');
1390 /* check for arguments */
1391 attribute = allocate_gnu_attribute(kind);
1392 if(token.type == '(') {
1394 if(token.type == ')') {
1395 /* empty args are allowed */
1398 attribute->have_arguments = true;
1403 case GNU_AK_VOLATILE:
1405 case GNU_AK_STDCALL:
1406 case GNU_AK_FASTCALL:
1407 case GNU_AK_DEPRECATED:
1408 case GNU_AK_NOINLINE:
1409 case GNU_AK_NORETURN:
1412 case GNU_AK_ALWAYS_INLINE:
1415 case GNU_AK_CONSTRUCTOR:
1416 case GNU_AK_DESTRUCTOR:
1417 case GNU_AK_NOTHROW:
1418 case GNU_AK_TRANSPARENT_UNION:
1420 case GNU_AK_NOCOMMON:
1423 case GNU_AK_NOTSHARED:
1426 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1427 case GNU_AK_WARN_UNUSED_RESULT:
1428 case GNU_AK_LONGCALL:
1429 case GNU_AK_SHORTCALL:
1430 case GNU_AK_LONG_CALL:
1431 case GNU_AK_SHORT_CALL:
1432 case GNU_AK_FUNCTION_VECTOR:
1433 case GNU_AK_INTERRUPT_HANDLER:
1434 case GNU_AK_NMI_HANDLER:
1435 case GNU_AK_NESTING:
1439 case GNU_AK_EIGTHBIT_DATA:
1440 case GNU_AK_TINY_DATA:
1441 case GNU_AK_SAVEALL:
1442 case GNU_AK_FLATTEN:
1443 case GNU_AK_SSEREGPARM:
1444 case GNU_AK_EXTERNALLY_VISIBLE:
1445 case GNU_AK_RETURN_TWICE:
1446 case GNU_AK_MAY_ALIAS:
1447 case GNU_AK_MS_STRUCT:
1448 case GNU_AK_GCC_STRUCT:
1449 if(attribute->have_arguments) {
1450 /* should have no arguments */
1451 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1452 eat_until_matching_token('(');
1453 /* we have already consumed '(', so we stop before ')', eat it */
1455 attribute->invalid = true;
1459 case GNU_AK_ALIGNED:
1460 case GNU_AK_FORMAT_ARG:
1461 case GNU_AK_REGPARM:
1462 case GNU_AK_TRAP_EXIT:
1463 if(!attribute->have_arguments) {
1464 /* should have arguments */
1465 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1466 attribute->invalid = true;
1468 parse_gnu_attribute_const_arg(attribute);
1471 case GNU_AK_SECTION:
1472 case GNU_AK_SP_SWITCH:
1473 if(!attribute->have_arguments) {
1474 /* should have arguments */
1475 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1476 attribute->invalid = true;
1478 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1481 if(!attribute->have_arguments) {
1482 /* should have arguments */
1483 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1484 attribute->invalid = true;
1486 parse_gnu_attribute_format_args(attribute);
1488 case GNU_AK_WEAKREF:
1489 /* may have one string argument */
1490 if(attribute->have_arguments)
1491 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1493 case GNU_AK_NONNULL:
1494 if(attribute->have_arguments)
1495 parse_gnu_attribute_const_arg_list(attribute);
1497 case GNU_AK_TLS_MODEL:
1498 if(!attribute->have_arguments) {
1499 /* should have arguments */
1500 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1502 parse_gnu_attribute_tls_model_arg(attribute);
1504 case GNU_AK_VISIBILITY:
1505 if(!attribute->have_arguments) {
1506 /* should have arguments */
1507 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1509 parse_gnu_attribute_visibility_arg(attribute);
1512 if(!attribute->have_arguments) {
1513 /* should have arguments */
1514 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1516 parse_gnu_attribute_model_arg(attribute);
1517 case GNU_AK_INTERRUPT:
1518 /* may have one string argument */
1519 if(attribute->have_arguments)
1520 parse_gnu_attribute_interrupt_arg(attribute);
1522 case GNU_AK_SENTINEL:
1523 /* may have one string argument */
1524 if(attribute->have_arguments)
1525 parse_gnu_attribute_const_arg(attribute);
1528 /* already handled */
1532 if(attribute != NULL) {
1534 last->next = attribute;
1537 head = last = attribute;
1541 if(token.type != ',')
1553 * Parse GNU attributes.
1555 static void parse_attributes(gnu_attribute_t **attributes)
1558 switch(token.type) {
1559 case T___attribute__: {
1560 parse_gnu_attribute(attributes);
1566 if(token.type != T_STRING_LITERAL) {
1567 parse_error_expected("while parsing assembler attribute",
1569 eat_until_matching_token('(');
1572 parse_string_literals();
1577 goto attributes_finished;
1581 attributes_finished:
1586 static designator_t *parse_designation(void)
1588 designator_t *result = NULL;
1589 designator_t *last = NULL;
1592 designator_t *designator;
1593 switch(token.type) {
1595 designator = allocate_ast_zero(sizeof(designator[0]));
1596 designator->source_position = token.source_position;
1598 add_anchor_token(']');
1599 designator->array_index = parse_constant_expression();
1600 rem_anchor_token(']');
1604 designator = allocate_ast_zero(sizeof(designator[0]));
1605 designator->source_position = token.source_position;
1607 if(token.type != T_IDENTIFIER) {
1608 parse_error_expected("while parsing designator",
1612 designator->symbol = token.v.symbol;
1620 assert(designator != NULL);
1622 last->next = designator;
1624 result = designator;
1632 static initializer_t *initializer_from_string(array_type_t *type,
1633 const string_t *const string)
1635 /* TODO: check len vs. size of array type */
1638 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1639 initializer->string.string = *string;
1644 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1645 wide_string_t *const string)
1647 /* TODO: check len vs. size of array type */
1650 initializer_t *const initializer =
1651 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1652 initializer->wide_string.string = *string;
1658 * Build an initializer from a given expression.
1660 static initializer_t *initializer_from_expression(type_t *orig_type,
1661 expression_t *expression)
1663 /* TODO check that expression is a constant expression */
1665 /* § 6.7.8.14/15 char array may be initialized by string literals */
1666 type_t *type = skip_typeref(orig_type);
1667 type_t *expr_type_orig = expression->base.type;
1668 type_t *expr_type = skip_typeref(expr_type_orig);
1669 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1670 array_type_t *const array_type = &type->array;
1671 type_t *const element_type = skip_typeref(array_type->element_type);
1673 if (element_type->kind == TYPE_ATOMIC) {
1674 atomic_type_kind_t akind = element_type->atomic.akind;
1675 switch (expression->kind) {
1676 case EXPR_STRING_LITERAL:
1677 if (akind == ATOMIC_TYPE_CHAR
1678 || akind == ATOMIC_TYPE_SCHAR
1679 || akind == ATOMIC_TYPE_UCHAR) {
1680 return initializer_from_string(array_type,
1681 &expression->string.value);
1684 case EXPR_WIDE_STRING_LITERAL: {
1685 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1686 if (get_unqualified_type(element_type) == bare_wchar_type) {
1687 return initializer_from_wide_string(array_type,
1688 &expression->wide_string.value);
1698 type_t *const res_type = semantic_assign(type, expression, "initializer",
1699 expression->base.source_position);
1700 if (res_type == NULL)
1703 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1704 result->value.value = create_implicit_cast(expression, res_type);
1710 * Checks if a given expression can be used as an constant initializer.
1712 static bool is_initializer_constant(const expression_t *expression)
1714 return is_constant_expression(expression)
1715 || is_address_constant(expression);
1719 * Parses an scalar initializer.
1721 * § 6.7.8.11; eat {} without warning
1723 static initializer_t *parse_scalar_initializer(type_t *type,
1724 bool must_be_constant)
1726 /* there might be extra {} hierarchies */
1728 while(token.type == '{') {
1731 warningf(HERE, "extra curly braces around scalar initializer");
1736 expression_t *expression = parse_assignment_expression();
1737 if(must_be_constant && !is_initializer_constant(expression)) {
1738 errorf(expression->base.source_position,
1739 "Initialisation expression '%E' is not constant\n",
1743 initializer_t *initializer = initializer_from_expression(type, expression);
1745 if(initializer == NULL) {
1746 errorf(expression->base.source_position,
1747 "expression '%E' (type '%T') doesn't match expected type '%T'",
1748 expression, expression->base.type, type);
1753 bool additional_warning_displayed = false;
1755 if(token.type == ',') {
1758 if(token.type != '}') {
1759 if(!additional_warning_displayed) {
1760 warningf(HERE, "additional elements in scalar initializer");
1761 additional_warning_displayed = true;
1772 * An entry in the type path.
1774 typedef struct type_path_entry_t type_path_entry_t;
1775 struct type_path_entry_t {
1776 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1778 size_t index; /**< For array types: the current index. */
1779 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1784 * A type path expression a position inside compound or array types.
1786 typedef struct type_path_t type_path_t;
1787 struct type_path_t {
1788 type_path_entry_t *path; /**< An flexible array containing the current path. */
1789 type_t *top_type; /**< type of the element the path points */
1790 size_t max_index; /**< largest index in outermost array */
1794 * Prints a type path for debugging.
1796 static __attribute__((unused)) void debug_print_type_path(
1797 const type_path_t *path)
1799 size_t len = ARR_LEN(path->path);
1801 for(size_t i = 0; i < len; ++i) {
1802 const type_path_entry_t *entry = & path->path[i];
1804 type_t *type = skip_typeref(entry->type);
1805 if(is_type_compound(type)) {
1806 /* in gcc mode structs can have no members */
1807 if(entry->v.compound_entry == NULL) {
1811 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1812 } else if(is_type_array(type)) {
1813 fprintf(stderr, "[%zd]", entry->v.index);
1815 fprintf(stderr, "-INVALID-");
1818 if(path->top_type != NULL) {
1819 fprintf(stderr, " (");
1820 print_type(path->top_type);
1821 fprintf(stderr, ")");
1826 * Return the top type path entry, ie. in a path
1827 * (type).a.b returns the b.
1829 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1831 size_t len = ARR_LEN(path->path);
1833 return &path->path[len-1];
1837 * Enlarge the type path by an (empty) element.
1839 static type_path_entry_t *append_to_type_path(type_path_t *path)
1841 size_t len = ARR_LEN(path->path);
1842 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1844 type_path_entry_t *result = & path->path[len];
1845 memset(result, 0, sizeof(result[0]));
1850 * Descending into a sub-type. Enter the scope of the current
1853 static void descend_into_subtype(type_path_t *path)
1855 type_t *orig_top_type = path->top_type;
1856 type_t *top_type = skip_typeref(orig_top_type);
1858 assert(is_type_compound(top_type) || is_type_array(top_type));
1860 type_path_entry_t *top = append_to_type_path(path);
1861 top->type = top_type;
1863 if(is_type_compound(top_type)) {
1864 declaration_t *declaration = top_type->compound.declaration;
1865 declaration_t *entry = declaration->scope.declarations;
1866 top->v.compound_entry = entry;
1869 path->top_type = entry->type;
1871 path->top_type = NULL;
1874 assert(is_type_array(top_type));
1877 path->top_type = top_type->array.element_type;
1882 * Pop an entry from the given type path, ie. returning from
1883 * (type).a.b to (type).a
1885 static void ascend_from_subtype(type_path_t *path)
1887 type_path_entry_t *top = get_type_path_top(path);
1889 path->top_type = top->type;
1891 size_t len = ARR_LEN(path->path);
1892 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1896 * Pop entries from the given type path until the given
1897 * path level is reached.
1899 static void ascend_to(type_path_t *path, size_t top_path_level)
1901 size_t len = ARR_LEN(path->path);
1903 while(len > top_path_level) {
1904 ascend_from_subtype(path);
1905 len = ARR_LEN(path->path);
1909 static bool walk_designator(type_path_t *path, const designator_t *designator,
1910 bool used_in_offsetof)
1912 for( ; designator != NULL; designator = designator->next) {
1913 type_path_entry_t *top = get_type_path_top(path);
1914 type_t *orig_type = top->type;
1916 type_t *type = skip_typeref(orig_type);
1918 if(designator->symbol != NULL) {
1919 symbol_t *symbol = designator->symbol;
1920 if(!is_type_compound(type)) {
1921 if(is_type_valid(type)) {
1922 errorf(designator->source_position,
1923 "'.%Y' designator used for non-compound type '%T'",
1929 declaration_t *declaration = type->compound.declaration;
1930 declaration_t *iter = declaration->scope.declarations;
1931 for( ; iter != NULL; iter = iter->next) {
1932 if(iter->symbol == symbol) {
1937 errorf(designator->source_position,
1938 "'%T' has no member named '%Y'", orig_type, symbol);
1941 if(used_in_offsetof) {
1942 type_t *real_type = skip_typeref(iter->type);
1943 if(real_type->kind == TYPE_BITFIELD) {
1944 errorf(designator->source_position,
1945 "offsetof designator '%Y' may not specify bitfield",
1951 top->type = orig_type;
1952 top->v.compound_entry = iter;
1953 orig_type = iter->type;
1955 expression_t *array_index = designator->array_index;
1956 assert(designator->array_index != NULL);
1958 if(!is_type_array(type)) {
1959 if(is_type_valid(type)) {
1960 errorf(designator->source_position,
1961 "[%E] designator used for non-array type '%T'",
1962 array_index, orig_type);
1966 if(!is_type_valid(array_index->base.type)) {
1970 long index = fold_constant(array_index);
1971 if(!used_in_offsetof) {
1973 errorf(designator->source_position,
1974 "array index [%E] must be positive", array_index);
1977 if(type->array.size_constant == true) {
1978 long array_size = type->array.size;
1979 if(index >= array_size) {
1980 errorf(designator->source_position,
1981 "designator [%E] (%d) exceeds array size %d",
1982 array_index, index, array_size);
1988 top->type = orig_type;
1989 top->v.index = (size_t) index;
1990 orig_type = type->array.element_type;
1992 path->top_type = orig_type;
1994 if(designator->next != NULL) {
1995 descend_into_subtype(path);
2004 static void advance_current_object(type_path_t *path, size_t top_path_level)
2006 type_path_entry_t *top = get_type_path_top(path);
2008 type_t *type = skip_typeref(top->type);
2009 if(is_type_union(type)) {
2010 /* in unions only the first element is initialized */
2011 top->v.compound_entry = NULL;
2012 } else if(is_type_struct(type)) {
2013 declaration_t *entry = top->v.compound_entry;
2015 entry = entry->next;
2016 top->v.compound_entry = entry;
2018 path->top_type = entry->type;
2022 assert(is_type_array(type));
2026 if(!type->array.size_constant || top->v.index < type->array.size) {
2031 /* we're past the last member of the current sub-aggregate, try if we
2032 * can ascend in the type hierarchy and continue with another subobject */
2033 size_t len = ARR_LEN(path->path);
2035 if(len > top_path_level) {
2036 ascend_from_subtype(path);
2037 advance_current_object(path, top_path_level);
2039 path->top_type = NULL;
2044 * skip until token is found.
2046 static void skip_until(int type) {
2047 while(token.type != type) {
2048 if(token.type == T_EOF)
2055 * skip any {...} blocks until a closing braket is reached.
2057 static void skip_initializers(void)
2059 if(token.type == '{')
2062 while(token.type != '}') {
2063 if(token.type == T_EOF)
2065 if(token.type == '{') {
2073 static initializer_t *create_empty_initializer(void)
2075 static initializer_t empty_initializer
2076 = { .list = { { INITIALIZER_LIST }, 0 } };
2077 return &empty_initializer;
2081 * Parse a part of an initialiser for a struct or union,
2083 static initializer_t *parse_sub_initializer(type_path_t *path,
2084 type_t *outer_type, size_t top_path_level,
2085 parse_initializer_env_t *env)
2087 if(token.type == '}') {
2088 /* empty initializer */
2089 return create_empty_initializer();
2092 type_t *orig_type = path->top_type;
2093 type_t *type = NULL;
2095 if (orig_type == NULL) {
2096 /* We are initializing an empty compound. */
2098 type = skip_typeref(orig_type);
2100 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2101 * initializers in this case. */
2102 if(!is_type_valid(type)) {
2103 skip_initializers();
2104 return create_empty_initializer();
2108 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2111 designator_t *designator = NULL;
2112 if(token.type == '.' || token.type == '[') {
2113 designator = parse_designation();
2115 /* reset path to toplevel, evaluate designator from there */
2116 ascend_to(path, top_path_level);
2117 if(!walk_designator(path, designator, false)) {
2118 /* can't continue after designation error */
2122 initializer_t *designator_initializer
2123 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2124 designator_initializer->designator.designator = designator;
2125 ARR_APP1(initializer_t*, initializers, designator_initializer);
2130 if(token.type == '{') {
2131 if(type != NULL && is_type_scalar(type)) {
2132 sub = parse_scalar_initializer(type, env->must_be_constant);
2136 if (env->declaration != NULL)
2137 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2138 env->declaration->symbol);
2140 errorf(HERE, "extra brace group at end of initializer");
2142 descend_into_subtype(path);
2144 add_anchor_token('}');
2145 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2147 rem_anchor_token('}');
2150 ascend_from_subtype(path);
2154 goto error_parse_next;
2158 /* must be an expression */
2159 expression_t *expression = parse_assignment_expression();
2161 if(env->must_be_constant && !is_initializer_constant(expression)) {
2162 errorf(expression->base.source_position,
2163 "Initialisation expression '%E' is not constant\n",
2168 /* we are already outside, ... */
2172 /* handle { "string" } special case */
2173 if((expression->kind == EXPR_STRING_LITERAL
2174 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2175 && outer_type != NULL) {
2176 sub = initializer_from_expression(outer_type, expression);
2178 if(token.type == ',') {
2181 if(token.type != '}') {
2182 warningf(HERE, "excessive elements in initializer for type '%T'",
2185 /* TODO: eat , ... */
2190 /* descend into subtypes until expression matches type */
2192 orig_type = path->top_type;
2193 type = skip_typeref(orig_type);
2195 sub = initializer_from_expression(orig_type, expression);
2199 if(!is_type_valid(type)) {
2202 if(is_type_scalar(type)) {
2203 errorf(expression->base.source_position,
2204 "expression '%E' doesn't match expected type '%T'",
2205 expression, orig_type);
2209 descend_into_subtype(path);
2213 /* update largest index of top array */
2214 const type_path_entry_t *first = &path->path[0];
2215 type_t *first_type = first->type;
2216 first_type = skip_typeref(first_type);
2217 if(is_type_array(first_type)) {
2218 size_t index = first->v.index;
2219 if(index > path->max_index)
2220 path->max_index = index;
2224 /* append to initializers list */
2225 ARR_APP1(initializer_t*, initializers, sub);
2228 if(env->declaration != NULL)
2229 warningf(HERE, "excess elements in struct initializer for '%Y'",
2230 env->declaration->symbol);
2232 warningf(HERE, "excess elements in struct initializer");
2236 if(token.type == '}') {
2240 if(token.type == '}') {
2245 /* advance to the next declaration if we are not at the end */
2246 advance_current_object(path, top_path_level);
2247 orig_type = path->top_type;
2248 if(orig_type != NULL)
2249 type = skip_typeref(orig_type);
2255 size_t len = ARR_LEN(initializers);
2256 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2257 initializer_t *result = allocate_ast_zero(size);
2258 result->kind = INITIALIZER_LIST;
2259 result->list.len = len;
2260 memcpy(&result->list.initializers, initializers,
2261 len * sizeof(initializers[0]));
2263 DEL_ARR_F(initializers);
2264 ascend_to(path, top_path_level);
2269 skip_initializers();
2270 DEL_ARR_F(initializers);
2271 ascend_to(path, top_path_level);
2276 * Parses an initializer. Parsers either a compound literal
2277 * (env->declaration == NULL) or an initializer of a declaration.
2279 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2281 type_t *type = skip_typeref(env->type);
2282 initializer_t *result = NULL;
2285 if(is_type_scalar(type)) {
2286 result = parse_scalar_initializer(type, env->must_be_constant);
2287 } else if(token.type == '{') {
2291 memset(&path, 0, sizeof(path));
2292 path.top_type = env->type;
2293 path.path = NEW_ARR_F(type_path_entry_t, 0);
2295 descend_into_subtype(&path);
2297 add_anchor_token('}');
2298 result = parse_sub_initializer(&path, env->type, 1, env);
2299 rem_anchor_token('}');
2301 max_index = path.max_index;
2302 DEL_ARR_F(path.path);
2306 /* parse_scalar_initializer() also works in this case: we simply
2307 * have an expression without {} around it */
2308 result = parse_scalar_initializer(type, env->must_be_constant);
2311 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2312 * the array type size */
2313 if(is_type_array(type) && type->array.size_expression == NULL
2314 && result != NULL) {
2316 switch (result->kind) {
2317 case INITIALIZER_LIST:
2318 size = max_index + 1;
2321 case INITIALIZER_STRING:
2322 size = result->string.string.size;
2325 case INITIALIZER_WIDE_STRING:
2326 size = result->wide_string.string.size;
2330 internal_errorf(HERE, "invalid initializer type");
2333 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2334 cnst->base.type = type_size_t;
2335 cnst->conste.v.int_value = size;
2337 type_t *new_type = duplicate_type(type);
2339 new_type->array.size_expression = cnst;
2340 new_type->array.size_constant = true;
2341 new_type->array.size = size;
2342 env->type = new_type;
2350 static declaration_t *append_declaration(declaration_t *declaration);
2352 static declaration_t *parse_compound_type_specifier(bool is_struct)
2354 gnu_attribute_t *attributes = NULL;
2361 symbol_t *symbol = NULL;
2362 declaration_t *declaration = NULL;
2364 if (token.type == T___attribute__) {
2365 parse_attributes(&attributes);
2368 if(token.type == T_IDENTIFIER) {
2369 symbol = token.v.symbol;
2373 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2375 declaration = get_declaration(symbol, NAMESPACE_UNION);
2377 } else if(token.type != '{') {
2379 parse_error_expected("while parsing struct type specifier",
2380 T_IDENTIFIER, '{', 0);
2382 parse_error_expected("while parsing union type specifier",
2383 T_IDENTIFIER, '{', 0);
2389 if(declaration == NULL) {
2390 declaration = allocate_declaration_zero();
2391 declaration->namespc =
2392 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2393 declaration->source_position = token.source_position;
2394 declaration->symbol = symbol;
2395 declaration->parent_scope = scope;
2396 if (symbol != NULL) {
2397 environment_push(declaration);
2399 append_declaration(declaration);
2402 if(token.type == '{') {
2403 if(declaration->init.is_defined) {
2404 assert(symbol != NULL);
2405 errorf(HERE, "multiple definitions of '%s %Y'",
2406 is_struct ? "struct" : "union", symbol);
2407 declaration->scope.declarations = NULL;
2409 declaration->init.is_defined = true;
2411 parse_compound_type_entries(declaration);
2412 parse_attributes(&attributes);
2418 static void parse_enum_entries(type_t *const enum_type)
2422 if(token.type == '}') {
2424 errorf(HERE, "empty enum not allowed");
2428 add_anchor_token('}');
2430 if(token.type != T_IDENTIFIER) {
2431 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2433 rem_anchor_token('}');
2437 declaration_t *const entry = allocate_declaration_zero();
2438 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2439 entry->type = enum_type;
2440 entry->symbol = token.v.symbol;
2441 entry->source_position = token.source_position;
2444 if(token.type == '=') {
2446 expression_t *value = parse_constant_expression();
2448 value = create_implicit_cast(value, enum_type);
2449 entry->init.enum_value = value;
2454 record_declaration(entry);
2456 if(token.type != ',')
2459 } while(token.type != '}');
2460 rem_anchor_token('}');
2468 static type_t *parse_enum_specifier(void)
2470 gnu_attribute_t *attributes = NULL;
2471 declaration_t *declaration;
2475 if(token.type == T_IDENTIFIER) {
2476 symbol = token.v.symbol;
2479 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2480 } else if(token.type != '{') {
2481 parse_error_expected("while parsing enum type specifier",
2482 T_IDENTIFIER, '{', 0);
2489 if(declaration == NULL) {
2490 declaration = allocate_declaration_zero();
2491 declaration->namespc = NAMESPACE_ENUM;
2492 declaration->source_position = token.source_position;
2493 declaration->symbol = symbol;
2494 declaration->parent_scope = scope;
2497 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2498 type->enumt.declaration = declaration;
2500 if(token.type == '{') {
2501 if(declaration->init.is_defined) {
2502 errorf(HERE, "multiple definitions of enum %Y", symbol);
2504 if (symbol != NULL) {
2505 environment_push(declaration);
2507 append_declaration(declaration);
2508 declaration->init.is_defined = 1;
2510 parse_enum_entries(type);
2511 parse_attributes(&attributes);
2518 * if a symbol is a typedef to another type, return true
2520 static bool is_typedef_symbol(symbol_t *symbol)
2522 const declaration_t *const declaration =
2523 get_declaration(symbol, NAMESPACE_NORMAL);
2525 declaration != NULL &&
2526 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2529 static type_t *parse_typeof(void)
2536 add_anchor_token(')');
2538 expression_t *expression = NULL;
2541 switch(token.type) {
2542 case T___extension__:
2543 /* this can be a prefix to a typename or an expression */
2544 /* we simply eat it now. */
2547 } while(token.type == T___extension__);
2551 if(is_typedef_symbol(token.v.symbol)) {
2552 type = parse_typename();
2554 expression = parse_expression();
2555 type = expression->base.type;
2560 type = parse_typename();
2564 expression = parse_expression();
2565 type = expression->base.type;
2569 rem_anchor_token(')');
2572 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2573 typeof_type->typeoft.expression = expression;
2574 typeof_type->typeoft.typeof_type = type;
2582 SPECIFIER_SIGNED = 1 << 0,
2583 SPECIFIER_UNSIGNED = 1 << 1,
2584 SPECIFIER_LONG = 1 << 2,
2585 SPECIFIER_INT = 1 << 3,
2586 SPECIFIER_DOUBLE = 1 << 4,
2587 SPECIFIER_CHAR = 1 << 5,
2588 SPECIFIER_SHORT = 1 << 6,
2589 SPECIFIER_LONG_LONG = 1 << 7,
2590 SPECIFIER_FLOAT = 1 << 8,
2591 SPECIFIER_BOOL = 1 << 9,
2592 SPECIFIER_VOID = 1 << 10,
2593 SPECIFIER_INT8 = 1 << 11,
2594 SPECIFIER_INT16 = 1 << 12,
2595 SPECIFIER_INT32 = 1 << 13,
2596 SPECIFIER_INT64 = 1 << 14,
2597 SPECIFIER_INT128 = 1 << 15,
2598 #ifdef PROVIDE_COMPLEX
2599 SPECIFIER_COMPLEX = 1 << 16,
2600 SPECIFIER_IMAGINARY = 1 << 17,
2604 static type_t *create_builtin_type(symbol_t *const symbol,
2605 type_t *const real_type)
2607 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2608 type->builtin.symbol = symbol;
2609 type->builtin.real_type = real_type;
2611 type_t *result = typehash_insert(type);
2612 if (type != result) {
2619 static type_t *get_typedef_type(symbol_t *symbol)
2621 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2622 if(declaration == NULL
2623 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2626 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2627 type->typedeft.declaration = declaration;
2633 * check for the allowed MS alignment values.
2635 static bool check_elignment_value(long long intvalue) {
2636 if(intvalue < 1 || intvalue > 8192) {
2637 errorf(HERE, "illegal alignment value");
2640 unsigned v = (unsigned)intvalue;
2641 for(unsigned i = 1; i <= 8192; i += i) {
2645 errorf(HERE, "alignment must be power of two");
2649 #define DET_MOD(name, tag) do { \
2650 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2651 *modifiers |= tag; \
2654 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2656 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2659 if(token.type == T_restrict) {
2661 DET_MOD(restrict, DM_RESTRICT);
2663 } else if(token.type != T_IDENTIFIER)
2665 symbol_t *symbol = token.v.symbol;
2666 if(symbol == sym_align) {
2669 if(token.type != T_INTEGER)
2671 if(check_elignment_value(token.v.intvalue)) {
2672 if(specifiers->alignment != 0)
2673 warningf(HERE, "align used more than once");
2674 specifiers->alignment = (unsigned char)token.v.intvalue;
2678 } else if(symbol == sym_allocate) {
2681 if(token.type != T_IDENTIFIER)
2683 (void)token.v.symbol;
2685 } else if(symbol == sym_dllimport) {
2687 DET_MOD(dllimport, DM_DLLIMPORT);
2688 } else if(symbol == sym_dllexport) {
2690 DET_MOD(dllexport, DM_DLLEXPORT);
2691 } else if(symbol == sym_thread) {
2693 DET_MOD(thread, DM_THREAD);
2694 } else if(symbol == sym_naked) {
2696 DET_MOD(naked, DM_NAKED);
2697 } else if(symbol == sym_noinline) {
2699 DET_MOD(noinline, DM_NOINLINE);
2700 } else if(symbol == sym_noreturn) {
2702 DET_MOD(noreturn, DM_NORETURN);
2703 } else if(symbol == sym_nothrow) {
2705 DET_MOD(nothrow, DM_NOTHROW);
2706 } else if(symbol == sym_novtable) {
2708 DET_MOD(novtable, DM_NOVTABLE);
2709 } else if(symbol == sym_property) {
2713 bool is_get = false;
2714 if(token.type != T_IDENTIFIER)
2716 if(token.v.symbol == sym_get) {
2718 } else if(token.v.symbol == sym_put) {
2720 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2725 if(token.type != T_IDENTIFIER)
2728 if(specifiers->get_property_sym != NULL) {
2729 errorf(HERE, "get property name already specified");
2731 specifiers->get_property_sym = token.v.symbol;
2734 if(specifiers->put_property_sym != NULL) {
2735 errorf(HERE, "put property name already specified");
2737 specifiers->put_property_sym = token.v.symbol;
2741 if(token.type == ',') {
2748 } else if(symbol == sym_selectany) {
2750 DET_MOD(selectany, DM_SELECTANY);
2751 } else if(symbol == sym_uuid) {
2754 if(token.type != T_STRING_LITERAL)
2758 } else if(symbol == sym_deprecated) {
2760 if(specifiers->deprecated != 0)
2761 warningf(HERE, "deprecated used more than once");
2762 specifiers->deprecated = 1;
2763 if(token.type == '(') {
2765 if(token.type == T_STRING_LITERAL) {
2766 specifiers->deprecated_string = token.v.string.begin;
2769 errorf(HERE, "string literal expected");
2773 } else if(symbol == sym_noalias) {
2775 DET_MOD(noalias, DM_NOALIAS);
2777 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2779 if(token.type == '(')
2783 if (token.type == ',')
2790 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2792 type_t *type = NULL;
2793 unsigned type_qualifiers = 0;
2794 unsigned type_specifiers = 0;
2797 specifiers->source_position = token.source_position;
2800 switch(token.type) {
2803 #define MATCH_STORAGE_CLASS(token, class) \
2805 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2806 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2808 specifiers->declared_storage_class = class; \
2812 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2813 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2814 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2815 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2816 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2821 add_anchor_token(')');
2822 parse_microsoft_extended_decl_modifier(specifiers);
2823 rem_anchor_token(')');
2828 switch (specifiers->declared_storage_class) {
2829 case STORAGE_CLASS_NONE:
2830 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2833 case STORAGE_CLASS_EXTERN:
2834 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2837 case STORAGE_CLASS_STATIC:
2838 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2842 errorf(HERE, "multiple storage classes in declaration specifiers");
2848 /* type qualifiers */
2849 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2851 type_qualifiers |= qualifier; \
2855 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2856 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2857 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2858 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2859 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2860 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2861 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2862 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2864 case T___extension__:
2869 /* type specifiers */
2870 #define MATCH_SPECIFIER(token, specifier, name) \
2873 if(type_specifiers & specifier) { \
2874 errorf(HERE, "multiple " name " type specifiers given"); \
2876 type_specifiers |= specifier; \
2880 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2881 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2882 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2883 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2884 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2885 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2886 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2887 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2888 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2889 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2890 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2891 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2892 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2893 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2894 #ifdef PROVIDE_COMPLEX
2895 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2896 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2898 case T__forceinline:
2899 /* only in microsoft mode */
2900 specifiers->decl_modifiers |= DM_FORCEINLINE;
2904 specifiers->is_inline = true;
2909 if(type_specifiers & SPECIFIER_LONG_LONG) {
2910 errorf(HERE, "multiple type specifiers given");
2911 } else if(type_specifiers & SPECIFIER_LONG) {
2912 type_specifiers |= SPECIFIER_LONG_LONG;
2914 type_specifiers |= SPECIFIER_LONG;
2919 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2921 type->compound.declaration = parse_compound_type_specifier(true);
2925 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2927 type->compound.declaration = parse_compound_type_specifier(false);
2931 type = parse_enum_specifier();
2934 type = parse_typeof();
2936 case T___builtin_va_list:
2937 type = duplicate_type(type_valist);
2941 case T___attribute__:
2942 parse_attributes(&specifiers->gnu_attributes);
2945 case T_IDENTIFIER: {
2946 /* only parse identifier if we haven't found a type yet */
2947 if(type != NULL || type_specifiers != 0)
2948 goto finish_specifiers;
2950 type_t *typedef_type = get_typedef_type(token.v.symbol);
2952 if(typedef_type == NULL)
2953 goto finish_specifiers;
2956 type = typedef_type;
2960 /* function specifier */
2962 goto finish_specifiers;
2969 atomic_type_kind_t atomic_type;
2971 /* match valid basic types */
2972 switch(type_specifiers) {
2973 case SPECIFIER_VOID:
2974 atomic_type = ATOMIC_TYPE_VOID;
2976 case SPECIFIER_CHAR:
2977 atomic_type = ATOMIC_TYPE_CHAR;
2979 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2980 atomic_type = ATOMIC_TYPE_SCHAR;
2982 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2983 atomic_type = ATOMIC_TYPE_UCHAR;
2985 case SPECIFIER_SHORT:
2986 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2987 case SPECIFIER_SHORT | SPECIFIER_INT:
2988 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2989 atomic_type = ATOMIC_TYPE_SHORT;
2991 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2992 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2993 atomic_type = ATOMIC_TYPE_USHORT;
2996 case SPECIFIER_SIGNED:
2997 case SPECIFIER_SIGNED | SPECIFIER_INT:
2998 atomic_type = ATOMIC_TYPE_INT;
3000 case SPECIFIER_UNSIGNED:
3001 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3002 atomic_type = ATOMIC_TYPE_UINT;
3004 case SPECIFIER_LONG:
3005 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3006 case SPECIFIER_LONG | SPECIFIER_INT:
3007 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3008 atomic_type = ATOMIC_TYPE_LONG;
3010 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3011 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3012 atomic_type = ATOMIC_TYPE_ULONG;
3014 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3015 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3016 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3017 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3019 atomic_type = ATOMIC_TYPE_LONGLONG;
3021 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3022 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3024 atomic_type = ATOMIC_TYPE_ULONGLONG;
3027 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3028 atomic_type = unsigned_int8_type_kind;
3031 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3032 atomic_type = unsigned_int16_type_kind;
3035 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3036 atomic_type = unsigned_int32_type_kind;
3039 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3040 atomic_type = unsigned_int64_type_kind;
3043 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3044 atomic_type = unsigned_int128_type_kind;
3047 case SPECIFIER_INT8:
3048 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3049 atomic_type = int8_type_kind;
3052 case SPECIFIER_INT16:
3053 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3054 atomic_type = int16_type_kind;
3057 case SPECIFIER_INT32:
3058 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3059 atomic_type = int32_type_kind;
3062 case SPECIFIER_INT64:
3063 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3064 atomic_type = int64_type_kind;
3067 case SPECIFIER_INT128:
3068 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3069 atomic_type = int128_type_kind;
3072 case SPECIFIER_FLOAT:
3073 atomic_type = ATOMIC_TYPE_FLOAT;
3075 case SPECIFIER_DOUBLE:
3076 atomic_type = ATOMIC_TYPE_DOUBLE;
3078 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3079 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3081 case SPECIFIER_BOOL:
3082 atomic_type = ATOMIC_TYPE_BOOL;
3084 #ifdef PROVIDE_COMPLEX
3085 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3086 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
3088 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3089 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
3091 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3092 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
3094 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3095 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
3097 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3098 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
3100 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3101 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
3105 /* invalid specifier combination, give an error message */
3106 if(type_specifiers == 0) {
3107 if (! strict_mode) {
3108 if (warning.implicit_int) {
3109 warningf(HERE, "no type specifiers in declaration, using 'int'");
3111 atomic_type = ATOMIC_TYPE_INT;
3114 errorf(HERE, "no type specifiers given in declaration");
3116 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3117 (type_specifiers & SPECIFIER_UNSIGNED)) {
3118 errorf(HERE, "signed and unsigned specifiers gives");
3119 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3120 errorf(HERE, "only integer types can be signed or unsigned");
3122 errorf(HERE, "multiple datatypes in declaration");
3124 atomic_type = ATOMIC_TYPE_INVALID;
3127 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
3128 type->atomic.akind = atomic_type;
3131 if(type_specifiers != 0) {
3132 errorf(HERE, "multiple datatypes in declaration");
3136 type->base.qualifiers = type_qualifiers;
3137 /* FIXME: check type qualifiers here */
3139 type_t *result = typehash_insert(type);
3140 if(newtype && result != type) {
3144 specifiers->type = result;
3149 static type_qualifiers_t parse_type_qualifiers(void)
3151 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3154 switch(token.type) {
3155 /* type qualifiers */
3156 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3157 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3158 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3159 /* microsoft extended type modifiers */
3160 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3161 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3162 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3163 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3164 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3167 return type_qualifiers;
3172 static declaration_t *parse_identifier_list(void)
3174 declaration_t *declarations = NULL;
3175 declaration_t *last_declaration = NULL;
3177 declaration_t *const declaration = allocate_declaration_zero();
3178 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3179 declaration->source_position = token.source_position;
3180 declaration->symbol = token.v.symbol;
3183 if(last_declaration != NULL) {
3184 last_declaration->next = declaration;
3186 declarations = declaration;
3188 last_declaration = declaration;
3190 if(token.type != ',')
3193 } while(token.type == T_IDENTIFIER);
3195 return declarations;
3198 static void semantic_parameter(declaration_t *declaration)
3200 /* TODO: improve error messages */
3202 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3203 errorf(HERE, "typedef not allowed in parameter list");
3204 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3205 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3206 errorf(HERE, "parameter may only have none or register storage class");
3209 type_t *const orig_type = declaration->type;
3210 type_t * type = skip_typeref(orig_type);
3212 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3213 * into a pointer. § 6.7.5.3 (7) */
3214 if (is_type_array(type)) {
3215 type_t *const element_type = type->array.element_type;
3217 type = make_pointer_type(element_type, type->base.qualifiers);
3219 declaration->type = type;
3222 if(is_type_incomplete(type)) {
3223 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3224 orig_type, declaration->symbol);
3228 static declaration_t *parse_parameter(void)
3230 declaration_specifiers_t specifiers;
3231 memset(&specifiers, 0, sizeof(specifiers));
3233 parse_declaration_specifiers(&specifiers);
3235 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3237 semantic_parameter(declaration);
3242 static declaration_t *parse_parameters(function_type_t *type)
3244 if(token.type == T_IDENTIFIER) {
3245 symbol_t *symbol = token.v.symbol;
3246 if(!is_typedef_symbol(symbol)) {
3247 type->kr_style_parameters = true;
3248 return parse_identifier_list();
3252 if(token.type == ')') {
3253 type->unspecified_parameters = 1;
3256 if(token.type == T_void && look_ahead(1)->type == ')') {
3261 declaration_t *declarations = NULL;
3262 declaration_t *declaration;
3263 declaration_t *last_declaration = NULL;
3264 function_parameter_t *parameter;
3265 function_parameter_t *last_parameter = NULL;
3268 switch(token.type) {
3272 return declarations;
3275 case T___extension__:
3277 declaration = parse_parameter();
3279 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3280 memset(parameter, 0, sizeof(parameter[0]));
3281 parameter->type = declaration->type;
3283 if(last_parameter != NULL) {
3284 last_declaration->next = declaration;
3285 last_parameter->next = parameter;
3287 type->parameters = parameter;
3288 declarations = declaration;
3290 last_parameter = parameter;
3291 last_declaration = declaration;
3295 return declarations;
3297 if(token.type != ',')
3298 return declarations;
3308 } construct_type_kind_t;
3310 typedef struct construct_type_t construct_type_t;
3311 struct construct_type_t {
3312 construct_type_kind_t kind;
3313 construct_type_t *next;
3316 typedef struct parsed_pointer_t parsed_pointer_t;
3317 struct parsed_pointer_t {
3318 construct_type_t construct_type;
3319 type_qualifiers_t type_qualifiers;
3322 typedef struct construct_function_type_t construct_function_type_t;
3323 struct construct_function_type_t {
3324 construct_type_t construct_type;
3325 type_t *function_type;
3328 typedef struct parsed_array_t parsed_array_t;
3329 struct parsed_array_t {
3330 construct_type_t construct_type;
3331 type_qualifiers_t type_qualifiers;
3337 typedef struct construct_base_type_t construct_base_type_t;
3338 struct construct_base_type_t {
3339 construct_type_t construct_type;
3343 static construct_type_t *parse_pointer_declarator(void)
3347 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3348 memset(pointer, 0, sizeof(pointer[0]));
3349 pointer->construct_type.kind = CONSTRUCT_POINTER;
3350 pointer->type_qualifiers = parse_type_qualifiers();
3352 return (construct_type_t*) pointer;
3355 static construct_type_t *parse_array_declarator(void)
3358 add_anchor_token(']');
3360 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3361 memset(array, 0, sizeof(array[0]));
3362 array->construct_type.kind = CONSTRUCT_ARRAY;
3364 if(token.type == T_static) {
3365 array->is_static = true;
3369 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3370 if(type_qualifiers != 0) {
3371 if(token.type == T_static) {
3372 array->is_static = true;
3376 array->type_qualifiers = type_qualifiers;
3378 if(token.type == '*' && look_ahead(1)->type == ']') {
3379 array->is_variable = true;
3381 } else if(token.type != ']') {
3382 array->size = parse_assignment_expression();
3385 rem_anchor_token(']');
3388 return (construct_type_t*) array;
3393 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3396 add_anchor_token(')');
3399 if(declaration != NULL) {
3400 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
3402 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
3405 declaration_t *parameters = parse_parameters(&type->function);
3406 if(declaration != NULL) {
3407 declaration->scope.declarations = parameters;
3410 construct_function_type_t *construct_function_type =
3411 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3412 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3413 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3414 construct_function_type->function_type = type;
3416 rem_anchor_token(')');
3420 return (construct_type_t*) construct_function_type;
3423 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3424 bool may_be_abstract)
3426 /* construct a single linked list of construct_type_t's which describe
3427 * how to construct the final declarator type */
3428 construct_type_t *first = NULL;
3429 construct_type_t *last = NULL;
3430 gnu_attribute_t *attributes = NULL;
3433 while(token.type == '*') {
3434 construct_type_t *type = parse_pointer_declarator();
3445 /* TODO: find out if this is correct */
3446 parse_attributes(&attributes);
3448 construct_type_t *inner_types = NULL;
3450 switch(token.type) {
3452 if(declaration == NULL) {
3453 errorf(HERE, "no identifier expected in typename");
3455 declaration->symbol = token.v.symbol;
3456 declaration->source_position = token.source_position;
3462 add_anchor_token(')');
3463 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3464 rem_anchor_token(')');
3470 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3471 /* avoid a loop in the outermost scope, because eat_statement doesn't
3473 if(token.type == '}' && current_function == NULL) {
3481 construct_type_t *p = last;
3484 construct_type_t *type;
3485 switch(token.type) {
3487 type = parse_function_declarator(declaration);
3490 type = parse_array_declarator();
3493 goto declarator_finished;
3496 /* insert in the middle of the list (behind p) */
3498 type->next = p->next;
3509 declarator_finished:
3510 parse_attributes(&attributes);
3512 /* append inner_types at the end of the list, we don't to set last anymore
3513 * as it's not needed anymore */
3515 assert(first == NULL);
3516 first = inner_types;
3518 last->next = inner_types;
3526 static type_t *construct_declarator_type(construct_type_t *construct_list,
3529 construct_type_t *iter = construct_list;
3530 for( ; iter != NULL; iter = iter->next) {
3531 switch(iter->kind) {
3532 case CONSTRUCT_INVALID:
3533 internal_errorf(HERE, "invalid type construction found");
3534 case CONSTRUCT_FUNCTION: {
3535 construct_function_type_t *construct_function_type
3536 = (construct_function_type_t*) iter;
3538 type_t *function_type = construct_function_type->function_type;
3540 function_type->function.return_type = type;
3542 type_t *skipped_return_type = skip_typeref(type);
3543 if (is_type_function(skipped_return_type)) {
3544 errorf(HERE, "function returning function is not allowed");
3545 type = type_error_type;
3546 } else if (is_type_array(skipped_return_type)) {
3547 errorf(HERE, "function returning array is not allowed");
3548 type = type_error_type;
3550 type = function_type;
3555 case CONSTRUCT_POINTER: {
3556 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3557 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3558 pointer_type->pointer.points_to = type;
3559 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3561 type = pointer_type;
3565 case CONSTRUCT_ARRAY: {
3566 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3567 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3569 expression_t *size_expression = parsed_array->size;
3570 if(size_expression != NULL) {
3572 = create_implicit_cast(size_expression, type_size_t);
3575 array_type->base.qualifiers = parsed_array->type_qualifiers;
3576 array_type->array.element_type = type;
3577 array_type->array.is_static = parsed_array->is_static;
3578 array_type->array.is_variable = parsed_array->is_variable;
3579 array_type->array.size_expression = size_expression;
3581 if(size_expression != NULL) {
3582 if(is_constant_expression(size_expression)) {
3583 array_type->array.size_constant = true;
3584 array_type->array.size
3585 = fold_constant(size_expression);
3587 array_type->array.is_vla = true;
3591 type_t *skipped_type = skip_typeref(type);
3592 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3593 errorf(HERE, "array of void is not allowed");
3594 type = type_error_type;
3602 type_t *hashed_type = typehash_insert(type);
3603 if(hashed_type != type) {
3604 /* the function type was constructed earlier freeing it here will
3605 * destroy other types... */
3606 if(iter->kind != CONSTRUCT_FUNCTION) {
3616 static declaration_t *parse_declarator(
3617 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3619 declaration_t *const declaration = allocate_declaration_zero();
3620 declaration->declared_storage_class = specifiers->declared_storage_class;
3621 declaration->modifiers = specifiers->decl_modifiers;
3622 declaration->deprecated = specifiers->deprecated;
3623 declaration->deprecated_string = specifiers->deprecated_string;
3624 declaration->get_property_sym = specifiers->get_property_sym;
3625 declaration->put_property_sym = specifiers->put_property_sym;
3626 declaration->is_inline = specifiers->is_inline;
3628 declaration->storage_class = specifiers->declared_storage_class;
3629 if(declaration->storage_class == STORAGE_CLASS_NONE
3630 && scope != global_scope) {
3631 declaration->storage_class = STORAGE_CLASS_AUTO;
3634 if(specifiers->alignment != 0) {
3635 /* TODO: add checks here */
3636 declaration->alignment = specifiers->alignment;
3639 construct_type_t *construct_type
3640 = parse_inner_declarator(declaration, may_be_abstract);
3641 type_t *const type = specifiers->type;
3642 declaration->type = construct_declarator_type(construct_type, type);
3644 if(construct_type != NULL) {
3645 obstack_free(&temp_obst, construct_type);
3651 static type_t *parse_abstract_declarator(type_t *base_type)
3653 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3655 type_t *result = construct_declarator_type(construct_type, base_type);
3656 if(construct_type != NULL) {
3657 obstack_free(&temp_obst, construct_type);
3663 static declaration_t *append_declaration(declaration_t* const declaration)
3665 if (last_declaration != NULL) {
3666 last_declaration->next = declaration;
3668 scope->declarations = declaration;
3670 last_declaration = declaration;
3675 * Check if the declaration of main is suspicious. main should be a
3676 * function with external linkage, returning int, taking either zero
3677 * arguments, two, or three arguments of appropriate types, ie.
3679 * int main([ int argc, char **argv [, char **env ] ]).
3681 * @param decl the declaration to check
3682 * @param type the function type of the declaration
3684 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3686 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3687 warningf(decl->source_position, "'main' is normally a non-static function");
3689 if (skip_typeref(func_type->return_type) != type_int) {
3690 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3692 const function_parameter_t *parm = func_type->parameters;
3694 type_t *const first_type = parm->type;
3695 if (!types_compatible(skip_typeref(first_type), type_int)) {
3696 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3700 type_t *const second_type = parm->type;
3701 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3702 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3706 type_t *const third_type = parm->type;
3707 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3708 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3712 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3716 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3722 * Check if a symbol is the equal to "main".
3724 static bool is_sym_main(const symbol_t *const sym)
3726 return strcmp(sym->string, "main") == 0;
3729 static declaration_t *internal_record_declaration(
3730 declaration_t *const declaration,
3731 const bool is_function_definition)
3733 const symbol_t *const symbol = declaration->symbol;
3734 const namespace_t namespc = (namespace_t)declaration->namespc;
3736 type_t *const orig_type = declaration->type;
3737 type_t *const type = skip_typeref(orig_type);
3738 if (is_type_function(type) &&
3739 type->function.unspecified_parameters &&
3740 warning.strict_prototypes) {
3741 warningf(declaration->source_position,
3742 "function declaration '%#T' is not a prototype",
3743 orig_type, declaration->symbol);
3746 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3747 check_type_of_main(declaration, &type->function);
3750 assert(declaration->symbol != NULL);
3751 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3753 assert(declaration != previous_declaration);
3754 if (previous_declaration != NULL) {
3755 if (previous_declaration->parent_scope == scope) {
3756 /* can happen for K&R style declarations */
3757 if(previous_declaration->type == NULL) {
3758 previous_declaration->type = declaration->type;
3761 const type_t *prev_type = skip_typeref(previous_declaration->type);
3762 if (!types_compatible(type, prev_type)) {
3763 errorf(declaration->source_position,
3764 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3765 orig_type, symbol, previous_declaration->type, symbol,
3766 previous_declaration->source_position);
3768 unsigned old_storage_class = previous_declaration->storage_class;
3769 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3770 errorf(declaration->source_position, "redeclaration of enum entry '%Y' (declared %P)",
3771 symbol, previous_declaration->source_position);
3772 return previous_declaration;
3775 unsigned new_storage_class = declaration->storage_class;
3777 if(is_type_incomplete(prev_type)) {
3778 previous_declaration->type = type;
3782 /* pretend no storage class means extern for function
3783 * declarations (except if the previous declaration is neither
3784 * none nor extern) */
3785 if (is_type_function(type)) {
3786 switch (old_storage_class) {
3787 case STORAGE_CLASS_NONE:
3788 old_storage_class = STORAGE_CLASS_EXTERN;
3790 case STORAGE_CLASS_EXTERN:
3791 if (is_function_definition) {
3792 if (warning.missing_prototypes &&
3793 prev_type->function.unspecified_parameters &&
3794 !is_sym_main(symbol)) {
3795 warningf(declaration->source_position,
3796 "no previous prototype for '%#T'",
3799 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3800 new_storage_class = STORAGE_CLASS_EXTERN;
3808 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3809 new_storage_class == STORAGE_CLASS_EXTERN) {
3810 warn_redundant_declaration:
3811 if (warning.redundant_decls) {
3812 warningf(declaration->source_position,
3813 "redundant declaration for '%Y' (declared %P)",
3814 symbol, previous_declaration->source_position);
3816 } else if (current_function == NULL) {
3817 if (old_storage_class != STORAGE_CLASS_STATIC &&
3818 new_storage_class == STORAGE_CLASS_STATIC) {
3819 errorf(declaration->source_position,
3820 "static declaration of '%Y' follows non-static declaration (declared %P)",
3821 symbol, previous_declaration->source_position);
3823 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3824 goto warn_redundant_declaration;
3826 if (new_storage_class == STORAGE_CLASS_NONE) {
3827 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3828 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3832 if (old_storage_class == new_storage_class) {
3833 errorf(declaration->source_position,
3834 "redeclaration of '%Y' (declared %P)",
3835 symbol, previous_declaration->source_position);
3837 errorf(declaration->source_position,
3838 "redeclaration of '%Y' with different linkage (declared %P)",
3839 symbol, previous_declaration->source_position);
3843 return previous_declaration;
3845 } else if (is_function_definition) {
3846 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3847 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3848 warningf(declaration->source_position,
3849 "no previous prototype for '%#T'", orig_type, symbol);
3850 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3851 warningf(declaration->source_position,
3852 "no previous declaration for '%#T'", orig_type,
3856 } else if (warning.missing_declarations &&
3857 scope == global_scope &&
3858 !is_type_function(type) && (
3859 declaration->storage_class == STORAGE_CLASS_NONE ||
3860 declaration->storage_class == STORAGE_CLASS_THREAD
3862 warningf(declaration->source_position,
3863 "no previous declaration for '%#T'", orig_type, symbol);
3866 assert(declaration->parent_scope == NULL);
3867 assert(scope != NULL);
3869 declaration->parent_scope = scope;
3871 environment_push(declaration);
3872 return append_declaration(declaration);
3875 static declaration_t *record_declaration(declaration_t *declaration)
3877 return internal_record_declaration(declaration, false);
3880 static declaration_t *record_function_definition(declaration_t *declaration)
3882 return internal_record_declaration(declaration, true);
3885 static void parser_error_multiple_definition(declaration_t *declaration,
3886 const source_position_t source_position)
3888 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
3889 declaration->symbol, declaration->source_position);
3892 static bool is_declaration_specifier(const token_t *token,
3893 bool only_type_specifiers)
3895 switch(token->type) {
3899 return is_typedef_symbol(token->v.symbol);
3901 case T___extension__:
3904 return !only_type_specifiers;
3911 static void parse_init_declarator_rest(declaration_t *declaration)
3915 type_t *orig_type = declaration->type;
3916 type_t *type = skip_typeref(orig_type);
3918 if(declaration->init.initializer != NULL) {
3919 parser_error_multiple_definition(declaration, token.source_position);
3922 bool must_be_constant = false;
3923 if(declaration->storage_class == STORAGE_CLASS_STATIC
3924 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3925 || declaration->parent_scope == global_scope) {
3926 must_be_constant = true;
3929 parse_initializer_env_t env;
3930 env.type = orig_type;
3931 env.must_be_constant = must_be_constant;
3932 env.declaration = declaration;
3934 initializer_t *initializer = parse_initializer(&env);
3936 if(env.type != orig_type) {
3937 orig_type = env.type;
3938 type = skip_typeref(orig_type);
3939 declaration->type = env.type;
3942 if(is_type_function(type)) {
3943 errorf(declaration->source_position,
3944 "initializers not allowed for function types at declator '%Y' (type '%T')",
3945 declaration->symbol, orig_type);
3947 declaration->init.initializer = initializer;
3951 /* parse rest of a declaration without any declarator */
3952 static void parse_anonymous_declaration_rest(
3953 const declaration_specifiers_t *specifiers,
3954 parsed_declaration_func finished_declaration)
3958 declaration_t *const declaration = allocate_declaration_zero();
3959 declaration->type = specifiers->type;
3960 declaration->declared_storage_class = specifiers->declared_storage_class;
3961 declaration->source_position = specifiers->source_position;
3962 declaration->modifiers = specifiers->decl_modifiers;
3964 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3965 warningf(declaration->source_position, "useless storage class in empty declaration");
3967 declaration->storage_class = STORAGE_CLASS_NONE;
3969 type_t *type = declaration->type;
3970 switch (type->kind) {
3971 case TYPE_COMPOUND_STRUCT:
3972 case TYPE_COMPOUND_UNION: {
3973 if (type->compound.declaration->symbol == NULL) {
3974 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3983 warningf(declaration->source_position, "empty declaration");
3987 finished_declaration(declaration);
3990 static void parse_declaration_rest(declaration_t *ndeclaration,
3991 const declaration_specifiers_t *specifiers,
3992 parsed_declaration_func finished_declaration)
3994 add_anchor_token(';');
3995 add_anchor_token('=');
3996 add_anchor_token(',');
3998 declaration_t *declaration = finished_declaration(ndeclaration);
4000 type_t *orig_type = declaration->type;
4001 type_t *type = skip_typeref(orig_type);
4003 if (type->kind != TYPE_FUNCTION &&
4004 declaration->is_inline &&
4005 is_type_valid(type)) {
4006 warningf(declaration->source_position,
4007 "variable '%Y' declared 'inline'\n", declaration->symbol);
4010 if(token.type == '=') {
4011 parse_init_declarator_rest(declaration);
4014 if(token.type != ',')
4018 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4023 rem_anchor_token(';');
4024 rem_anchor_token('=');
4025 rem_anchor_token(',');
4028 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4030 symbol_t *symbol = declaration->symbol;
4031 if(symbol == NULL) {
4032 errorf(HERE, "anonymous declaration not valid as function parameter");
4035 namespace_t namespc = (namespace_t) declaration->namespc;
4036 if(namespc != NAMESPACE_NORMAL) {
4037 return record_declaration(declaration);
4040 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4041 if(previous_declaration == NULL ||
4042 previous_declaration->parent_scope != scope) {
4043 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4048 if(previous_declaration->type == NULL) {
4049 previous_declaration->type = declaration->type;
4050 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4051 previous_declaration->storage_class = declaration->storage_class;
4052 previous_declaration->parent_scope = scope;
4053 return previous_declaration;
4055 return record_declaration(declaration);
4059 static void parse_declaration(parsed_declaration_func finished_declaration)
4061 declaration_specifiers_t specifiers;
4062 memset(&specifiers, 0, sizeof(specifiers));
4063 parse_declaration_specifiers(&specifiers);
4065 if(token.type == ';') {
4066 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4068 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4069 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4073 static void parse_kr_declaration_list(declaration_t *declaration)
4075 type_t *type = skip_typeref(declaration->type);
4076 if(!is_type_function(type))
4079 if(!type->function.kr_style_parameters)
4082 /* push function parameters */
4083 int top = environment_top();
4084 scope_t *last_scope = scope;
4085 set_scope(&declaration->scope);
4087 declaration_t *parameter = declaration->scope.declarations;
4088 for( ; parameter != NULL; parameter = parameter->next) {
4089 assert(parameter->parent_scope == NULL);
4090 parameter->parent_scope = scope;
4091 environment_push(parameter);
4094 /* parse declaration list */
4095 while(is_declaration_specifier(&token, false)) {
4096 parse_declaration(finished_kr_declaration);
4099 /* pop function parameters */
4100 assert(scope == &declaration->scope);
4101 set_scope(last_scope);
4102 environment_pop_to(top);
4104 /* update function type */
4105 type_t *new_type = duplicate_type(type);
4106 new_type->function.kr_style_parameters = false;
4108 function_parameter_t *parameters = NULL;
4109 function_parameter_t *last_parameter = NULL;
4111 declaration_t *parameter_declaration = declaration->scope.declarations;
4112 for( ; parameter_declaration != NULL;
4113 parameter_declaration = parameter_declaration->next) {
4114 type_t *parameter_type = parameter_declaration->type;
4115 if(parameter_type == NULL) {
4117 errorf(HERE, "no type specified for function parameter '%Y'",
4118 parameter_declaration->symbol);
4120 if (warning.implicit_int) {
4121 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4122 parameter_declaration->symbol);
4124 parameter_type = type_int;
4125 parameter_declaration->type = parameter_type;
4129 semantic_parameter(parameter_declaration);
4130 parameter_type = parameter_declaration->type;
4132 function_parameter_t *function_parameter
4133 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4134 memset(function_parameter, 0, sizeof(function_parameter[0]));
4136 function_parameter->type = parameter_type;
4137 if(last_parameter != NULL) {
4138 last_parameter->next = function_parameter;
4140 parameters = function_parameter;
4142 last_parameter = function_parameter;
4144 new_type->function.parameters = parameters;
4146 type = typehash_insert(new_type);
4147 if(type != new_type) {
4148 obstack_free(type_obst, new_type);
4151 declaration->type = type;
4154 static bool first_err = true;
4157 * When called with first_err set, prints the name of the current function,
4160 static void print_in_function(void) {
4163 diagnosticf("%s: In function '%Y':\n",
4164 current_function->source_position.input_name,
4165 current_function->symbol);
4170 * Check if all labels are defined in the current function.
4171 * Check if all labels are used in the current function.
4173 static void check_labels(void)
4175 for (const goto_statement_t *goto_statement = goto_first;
4176 goto_statement != NULL;
4177 goto_statement = goto_statement->next) {
4178 declaration_t *label = goto_statement->label;
4181 if (label->source_position.input_name == NULL) {
4182 print_in_function();
4183 errorf(goto_statement->base.source_position,
4184 "label '%Y' used but not defined", label->symbol);
4187 goto_first = goto_last = NULL;
4189 if (warning.unused_label) {
4190 for (const label_statement_t *label_statement = label_first;
4191 label_statement != NULL;
4192 label_statement = label_statement->next) {
4193 const declaration_t *label = label_statement->label;
4195 if (! label->used) {
4196 print_in_function();
4197 warningf(label_statement->base.source_position,
4198 "label '%Y' defined but not used", label->symbol);
4202 label_first = label_last = NULL;
4206 * Check declarations of current_function for unused entities.
4208 static void check_declarations(void)
4210 if (warning.unused_parameter) {
4211 const scope_t *scope = ¤t_function->scope;
4213 const declaration_t *parameter = scope->declarations;
4214 for (; parameter != NULL; parameter = parameter->next) {
4215 if (! parameter->used) {
4216 print_in_function();
4217 warningf(parameter->source_position,
4218 "unused parameter '%Y'", parameter->symbol);
4222 if (warning.unused_variable) {
4226 static void parse_external_declaration(void)
4228 /* function-definitions and declarations both start with declaration
4230 declaration_specifiers_t specifiers;
4231 memset(&specifiers, 0, sizeof(specifiers));
4233 add_anchor_token(';');
4234 parse_declaration_specifiers(&specifiers);
4235 rem_anchor_token(';');
4237 /* must be a declaration */
4238 if(token.type == ';') {
4239 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4243 add_anchor_token(',');
4244 add_anchor_token('=');
4245 rem_anchor_token(';');
4247 /* declarator is common to both function-definitions and declarations */
4248 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4250 rem_anchor_token(',');
4251 rem_anchor_token('=');
4252 rem_anchor_token(';');
4254 /* must be a declaration */
4255 if(token.type == ',' || token.type == '=' || token.type == ';') {
4256 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4260 /* must be a function definition */
4261 parse_kr_declaration_list(ndeclaration);
4263 if(token.type != '{') {
4264 parse_error_expected("while parsing function definition", '{', 0);
4265 eat_until_matching_token(';');
4269 type_t *type = ndeclaration->type;
4271 /* note that we don't skip typerefs: the standard doesn't allow them here
4272 * (so we can't use is_type_function here) */
4273 if(type->kind != TYPE_FUNCTION) {
4274 if (is_type_valid(type)) {
4275 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4276 type, ndeclaration->symbol);
4282 /* § 6.7.5.3 (14) a function definition with () means no
4283 * parameters (and not unspecified parameters) */
4284 if(type->function.unspecified_parameters) {
4285 type_t *duplicate = duplicate_type(type);
4286 duplicate->function.unspecified_parameters = false;
4288 type = typehash_insert(duplicate);
4289 if(type != duplicate) {
4290 obstack_free(type_obst, duplicate);
4292 ndeclaration->type = type;
4295 declaration_t *const declaration = record_function_definition(ndeclaration);
4296 if(ndeclaration != declaration) {
4297 declaration->scope = ndeclaration->scope;
4299 type = skip_typeref(declaration->type);
4301 /* push function parameters and switch scope */
4302 int top = environment_top();
4303 scope_t *last_scope = scope;
4304 set_scope(&declaration->scope);
4306 declaration_t *parameter = declaration->scope.declarations;
4307 for( ; parameter != NULL; parameter = parameter->next) {
4308 if(parameter->parent_scope == &ndeclaration->scope) {
4309 parameter->parent_scope = scope;
4311 assert(parameter->parent_scope == NULL
4312 || parameter->parent_scope == scope);
4313 parameter->parent_scope = scope;
4314 environment_push(parameter);
4317 if(declaration->init.statement != NULL) {
4318 parser_error_multiple_definition(declaration, token.source_position);
4320 goto end_of_parse_external_declaration;
4322 /* parse function body */
4323 int label_stack_top = label_top();
4324 declaration_t *old_current_function = current_function;
4325 current_function = declaration;
4327 declaration->init.statement = parse_compound_statement();
4330 check_declarations();
4332 assert(current_function == declaration);
4333 current_function = old_current_function;
4334 label_pop_to(label_stack_top);
4337 end_of_parse_external_declaration:
4338 assert(scope == &declaration->scope);
4339 set_scope(last_scope);
4340 environment_pop_to(top);
4343 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4344 source_position_t source_position)
4346 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4347 type->bitfield.base = base;
4348 type->bitfield.size = size;
4353 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4356 declaration_t *iter = compound_declaration->scope.declarations;
4357 for( ; iter != NULL; iter = iter->next) {
4358 if(iter->namespc != NAMESPACE_NORMAL)
4361 if(iter->symbol == NULL) {
4362 type_t *type = skip_typeref(iter->type);
4363 if(is_type_compound(type)) {
4364 declaration_t *result
4365 = find_compound_entry(type->compound.declaration, symbol);
4372 if(iter->symbol == symbol) {
4380 static void parse_compound_declarators(declaration_t *struct_declaration,
4381 const declaration_specifiers_t *specifiers)
4383 declaration_t *last_declaration = struct_declaration->scope.declarations;
4384 if(last_declaration != NULL) {
4385 while(last_declaration->next != NULL) {
4386 last_declaration = last_declaration->next;
4391 declaration_t *declaration;
4393 if(token.type == ':') {
4394 source_position_t source_position = HERE;
4397 type_t *base_type = specifiers->type;
4398 expression_t *size = parse_constant_expression();
4400 if(!is_type_integer(skip_typeref(base_type))) {
4401 errorf(HERE, "bitfield base type '%T' is not an integer type",
4405 type_t *type = make_bitfield_type(base_type, size, source_position);
4407 declaration = allocate_declaration_zero();
4408 declaration->namespc = NAMESPACE_NORMAL;
4409 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4410 declaration->storage_class = STORAGE_CLASS_NONE;
4411 declaration->source_position = source_position;
4412 declaration->modifiers = specifiers->decl_modifiers;
4413 declaration->type = type;
4415 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4417 type_t *orig_type = declaration->type;
4418 type_t *type = skip_typeref(orig_type);
4420 if(token.type == ':') {
4421 source_position_t source_position = HERE;
4423 expression_t *size = parse_constant_expression();
4425 if(!is_type_integer(type)) {
4426 errorf(HERE, "bitfield base type '%T' is not an "
4427 "integer type", orig_type);
4430 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
4431 declaration->type = bitfield_type;
4433 /* TODO we ignore arrays for now... what is missing is a check
4434 * that they're at the end of the struct */
4435 if(is_type_incomplete(type) && !is_type_array(type)) {
4437 "compound member '%Y' has incomplete type '%T'",
4438 declaration->symbol, orig_type);
4439 } else if(is_type_function(type)) {
4440 errorf(HERE, "compound member '%Y' must not have function "
4441 "type '%T'", declaration->symbol, orig_type);
4446 /* make sure we don't define a symbol multiple times */
4447 symbol_t *symbol = declaration->symbol;
4448 if(symbol != NULL) {
4449 declaration_t *prev_decl
4450 = find_compound_entry(struct_declaration, symbol);
4452 if(prev_decl != NULL) {
4453 assert(prev_decl->symbol == symbol);
4454 errorf(declaration->source_position,
4455 "multiple declarations of symbol '%Y' (declared %P)",
4456 symbol, prev_decl->source_position);
4460 /* append declaration */
4461 if(last_declaration != NULL) {
4462 last_declaration->next = declaration;
4464 struct_declaration->scope.declarations = declaration;
4466 last_declaration = declaration;
4468 if(token.type != ',')
4478 static void parse_compound_type_entries(declaration_t *compound_declaration)
4481 add_anchor_token('}');
4483 while(token.type != '}' && token.type != T_EOF) {
4484 declaration_specifiers_t specifiers;
4485 memset(&specifiers, 0, sizeof(specifiers));
4486 parse_declaration_specifiers(&specifiers);
4488 parse_compound_declarators(compound_declaration, &specifiers);
4490 rem_anchor_token('}');
4492 if(token.type == T_EOF) {
4493 errorf(HERE, "EOF while parsing struct");
4498 static type_t *parse_typename(void)
4500 declaration_specifiers_t specifiers;
4501 memset(&specifiers, 0, sizeof(specifiers));
4502 parse_declaration_specifiers(&specifiers);
4503 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4504 /* TODO: improve error message, user does probably not know what a
4505 * storage class is...
4507 errorf(HERE, "typename may not have a storage class");
4510 type_t *result = parse_abstract_declarator(specifiers.type);
4518 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4519 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4520 expression_t *left);
4522 typedef struct expression_parser_function_t expression_parser_function_t;
4523 struct expression_parser_function_t {
4524 unsigned precedence;
4525 parse_expression_function parser;
4526 unsigned infix_precedence;
4527 parse_expression_infix_function infix_parser;
4530 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4533 * Prints an error message if an expression was expected but not read
4535 static expression_t *expected_expression_error(void)
4537 /* skip the error message if the error token was read */
4538 if (token.type != T_ERROR) {
4539 errorf(HERE, "expected expression, got token '%K'", &token);
4543 return create_invalid_expression();
4547 * Parse a string constant.
4549 static expression_t *parse_string_const(void)
4552 if (token.type == T_STRING_LITERAL) {
4553 string_t res = token.v.string;
4555 while (token.type == T_STRING_LITERAL) {
4556 res = concat_strings(&res, &token.v.string);
4559 if (token.type != T_WIDE_STRING_LITERAL) {
4560 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4561 /* note: that we use type_char_ptr here, which is already the
4562 * automatic converted type. revert_automatic_type_conversion
4563 * will construct the array type */
4564 cnst->base.type = type_char_ptr;
4565 cnst->string.value = res;
4569 wres = concat_string_wide_string(&res, &token.v.wide_string);
4571 wres = token.v.wide_string;
4576 switch (token.type) {
4577 case T_WIDE_STRING_LITERAL:
4578 wres = concat_wide_strings(&wres, &token.v.wide_string);
4581 case T_STRING_LITERAL:
4582 wres = concat_wide_string_string(&wres, &token.v.string);
4586 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4587 cnst->base.type = type_wchar_t_ptr;
4588 cnst->wide_string.value = wres;
4597 * Parse an integer constant.
4599 static expression_t *parse_int_const(void)
4601 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4602 cnst->base.source_position = HERE;
4603 cnst->base.type = token.datatype;
4604 cnst->conste.v.int_value = token.v.intvalue;
4612 * Parse a character constant.
4614 static expression_t *parse_character_constant(void)
4616 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4618 cnst->base.source_position = HERE;
4619 cnst->base.type = token.datatype;
4620 cnst->conste.v.character = token.v.string;
4622 if (cnst->conste.v.character.size != 1) {
4623 if (warning.multichar && (c_mode & _GNUC)) {
4625 warningf(HERE, "multi-character character constant");
4627 errorf(HERE, "more than 1 characters in character constant");
4636 * Parse a wide character constant.
4638 static expression_t *parse_wide_character_constant(void)
4640 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4642 cnst->base.source_position = HERE;
4643 cnst->base.type = token.datatype;
4644 cnst->conste.v.wide_character = token.v.wide_string;
4646 if (cnst->conste.v.wide_character.size != 1) {
4647 if (warning.multichar && (c_mode & _GNUC)) {
4649 warningf(HERE, "multi-character character constant");
4651 errorf(HERE, "more than 1 characters in character constant");
4660 * Parse a float constant.
4662 static expression_t *parse_float_const(void)
4664 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4665 cnst->base.type = token.datatype;
4666 cnst->conste.v.float_value = token.v.floatvalue;
4673 static declaration_t *create_implicit_function(symbol_t *symbol,
4674 const source_position_t source_position)
4676 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4677 ntype->function.return_type = type_int;
4678 ntype->function.unspecified_parameters = true;
4680 type_t *type = typehash_insert(ntype);
4685 declaration_t *const declaration = allocate_declaration_zero();
4686 declaration->storage_class = STORAGE_CLASS_EXTERN;
4687 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4688 declaration->type = type;
4689 declaration->symbol = symbol;
4690 declaration->source_position = source_position;
4691 declaration->parent_scope = global_scope;
4693 scope_t *old_scope = scope;
4694 set_scope(global_scope);
4696 environment_push(declaration);
4697 /* prepends the declaration to the global declarations list */
4698 declaration->next = scope->declarations;
4699 scope->declarations = declaration;
4701 assert(scope == global_scope);
4702 set_scope(old_scope);
4708 * Creates a return_type (func)(argument_type) function type if not
4711 * @param return_type the return type
4712 * @param argument_type the argument type
4714 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4716 function_parameter_t *parameter
4717 = obstack_alloc(type_obst, sizeof(parameter[0]));
4718 memset(parameter, 0, sizeof(parameter[0]));
4719 parameter->type = argument_type;
4721 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4722 type->function.return_type = return_type;
4723 type->function.parameters = parameter;
4725 type_t *result = typehash_insert(type);
4726 if(result != type) {
4734 * Creates a function type for some function like builtins.
4736 * @param symbol the symbol describing the builtin
4738 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4740 switch(symbol->ID) {
4741 case T___builtin_alloca:
4742 return make_function_1_type(type_void_ptr, type_size_t);
4743 case T___builtin_nan:
4744 return make_function_1_type(type_double, type_char_ptr);
4745 case T___builtin_nanf:
4746 return make_function_1_type(type_float, type_char_ptr);
4747 case T___builtin_nand:
4748 return make_function_1_type(type_long_double, type_char_ptr);
4749 case T___builtin_va_end:
4750 return make_function_1_type(type_void, type_valist);
4752 internal_errorf(HERE, "not implemented builtin symbol found");
4757 * Performs automatic type cast as described in § 6.3.2.1.
4759 * @param orig_type the original type
4761 static type_t *automatic_type_conversion(type_t *orig_type)
4763 type_t *type = skip_typeref(orig_type);
4764 if(is_type_array(type)) {
4765 array_type_t *array_type = &type->array;
4766 type_t *element_type = array_type->element_type;
4767 unsigned qualifiers = array_type->type.qualifiers;
4769 return make_pointer_type(element_type, qualifiers);
4772 if(is_type_function(type)) {
4773 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4780 * reverts the automatic casts of array to pointer types and function
4781 * to function-pointer types as defined § 6.3.2.1
4783 type_t *revert_automatic_type_conversion(const expression_t *expression)
4785 switch (expression->kind) {
4786 case EXPR_REFERENCE: return expression->reference.declaration->type;
4787 case EXPR_SELECT: return expression->select.compound_entry->type;
4789 case EXPR_UNARY_DEREFERENCE: {
4790 const expression_t *const value = expression->unary.value;
4791 type_t *const type = skip_typeref(value->base.type);
4792 assert(is_type_pointer(type));
4793 return type->pointer.points_to;
4796 case EXPR_BUILTIN_SYMBOL:
4797 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4799 case EXPR_ARRAY_ACCESS: {
4800 const expression_t *array_ref = expression->array_access.array_ref;
4801 type_t *type_left = skip_typeref(array_ref->base.type);
4802 if (!is_type_valid(type_left))
4804 assert(is_type_pointer(type_left));
4805 return type_left->pointer.points_to;
4808 case EXPR_STRING_LITERAL: {
4809 size_t size = expression->string.value.size;
4810 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4813 case EXPR_WIDE_STRING_LITERAL: {
4814 size_t size = expression->wide_string.value.size;
4815 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4818 case EXPR_COMPOUND_LITERAL:
4819 return expression->compound_literal.type;
4824 return expression->base.type;
4827 static expression_t *parse_reference(void)
4829 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4831 reference_expression_t *ref = &expression->reference;
4832 ref->symbol = token.v.symbol;
4834 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4836 source_position_t source_position = token.source_position;
4839 if(declaration == NULL) {
4840 if (! strict_mode && token.type == '(') {
4841 /* an implicitly defined function */
4842 if (warning.implicit_function_declaration) {
4843 warningf(HERE, "implicit declaration of function '%Y'",
4847 declaration = create_implicit_function(ref->symbol,
4850 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4851 return create_invalid_expression();
4855 type_t *type = declaration->type;
4857 /* we always do the auto-type conversions; the & and sizeof parser contains
4858 * code to revert this! */
4859 type = automatic_type_conversion(type);
4861 ref->declaration = declaration;
4862 ref->base.type = type;
4864 /* this declaration is used */
4865 declaration->used = true;
4867 /* check for deprecated functions */
4868 if(declaration->deprecated != 0) {
4869 const char *prefix = "";
4870 if (is_type_function(declaration->type))
4871 prefix = "function ";
4873 if (declaration->deprecated_string != NULL) {
4874 warningf(source_position,
4875 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4876 declaration->deprecated_string);
4878 warningf(source_position,
4879 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4886 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4890 /* TODO check if explicit cast is allowed and issue warnings/errors */
4893 static expression_t *parse_compound_literal(type_t *type)
4895 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4897 parse_initializer_env_t env;
4899 env.declaration = NULL;
4900 env.must_be_constant = false;
4901 initializer_t *initializer = parse_initializer(&env);
4904 expression->compound_literal.initializer = initializer;
4905 expression->compound_literal.type = type;
4906 expression->base.type = automatic_type_conversion(type);
4912 * Parse a cast expression.
4914 static expression_t *parse_cast(void)
4916 source_position_t source_position = token.source_position;
4918 type_t *type = parse_typename();
4920 /* matching add_anchor_token() is at call site */
4921 rem_anchor_token(')');
4924 if(token.type == '{') {
4925 return parse_compound_literal(type);
4928 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4929 cast->base.source_position = source_position;
4931 expression_t *value = parse_sub_expression(20);
4933 check_cast_allowed(value, type);
4935 cast->base.type = type;
4936 cast->unary.value = value;
4940 return create_invalid_expression();
4944 * Parse a statement expression.
4946 static expression_t *parse_statement_expression(void)
4948 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4950 statement_t *statement = parse_compound_statement();
4951 expression->statement.statement = statement;
4952 expression->base.source_position = statement->base.source_position;
4954 /* find last statement and use its type */
4955 type_t *type = type_void;
4956 const statement_t *stmt = statement->compound.statements;
4958 while (stmt->base.next != NULL)
4959 stmt = stmt->base.next;
4961 if (stmt->kind == STATEMENT_EXPRESSION) {
4962 type = stmt->expression.expression->base.type;
4965 warningf(expression->base.source_position, "empty statement expression ({})");
4967 expression->base.type = type;
4973 return create_invalid_expression();
4977 * Parse a braced expression.
4979 static expression_t *parse_brace_expression(void)
4982 add_anchor_token(')');
4984 switch(token.type) {
4986 /* gcc extension: a statement expression */
4987 return parse_statement_expression();
4991 return parse_cast();
4993 if(is_typedef_symbol(token.v.symbol)) {
4994 return parse_cast();
4998 expression_t *result = parse_expression();
4999 rem_anchor_token(')');
5004 return create_invalid_expression();
5007 static expression_t *parse_function_keyword(void)
5012 if (current_function == NULL) {
5013 errorf(HERE, "'__func__' used outside of a function");
5016 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5017 expression->base.type = type_char_ptr;
5018 expression->funcname.kind = FUNCNAME_FUNCTION;
5023 static expression_t *parse_pretty_function_keyword(void)
5025 eat(T___PRETTY_FUNCTION__);
5027 if (current_function == NULL) {
5028 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5031 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5032 expression->base.type = type_char_ptr;
5033 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5038 static expression_t *parse_funcsig_keyword(void)
5042 if (current_function == NULL) {
5043 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5046 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5047 expression->base.type = type_char_ptr;
5048 expression->funcname.kind = FUNCNAME_FUNCSIG;
5053 static expression_t *parse_funcdname_keyword(void)
5055 eat(T___FUNCDNAME__);
5057 if (current_function == NULL) {
5058 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5061 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5062 expression->base.type = type_char_ptr;
5063 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5068 static designator_t *parse_designator(void)
5070 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5071 result->source_position = HERE;
5073 if(token.type != T_IDENTIFIER) {
5074 parse_error_expected("while parsing member designator",
5078 result->symbol = token.v.symbol;
5081 designator_t *last_designator = result;
5083 if(token.type == '.') {
5085 if(token.type != T_IDENTIFIER) {
5086 parse_error_expected("while parsing member designator",
5090 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5091 designator->source_position = HERE;
5092 designator->symbol = token.v.symbol;
5095 last_designator->next = designator;
5096 last_designator = designator;
5099 if(token.type == '[') {
5101 add_anchor_token(']');
5102 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5103 designator->source_position = HERE;
5104 designator->array_index = parse_expression();
5105 rem_anchor_token(']');
5107 if(designator->array_index == NULL) {
5111 last_designator->next = designator;
5112 last_designator = designator;
5124 * Parse the __builtin_offsetof() expression.
5126 static expression_t *parse_offsetof(void)
5128 eat(T___builtin_offsetof);
5130 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5131 expression->base.type = type_size_t;
5134 add_anchor_token(',');
5135 type_t *type = parse_typename();
5136 rem_anchor_token(',');
5138 add_anchor_token(')');
5139 designator_t *designator = parse_designator();
5140 rem_anchor_token(')');
5143 expression->offsetofe.type = type;
5144 expression->offsetofe.designator = designator;
5147 memset(&path, 0, sizeof(path));
5148 path.top_type = type;
5149 path.path = NEW_ARR_F(type_path_entry_t, 0);
5151 descend_into_subtype(&path);
5153 if(!walk_designator(&path, designator, true)) {
5154 return create_invalid_expression();
5157 DEL_ARR_F(path.path);
5161 return create_invalid_expression();
5165 * Parses a _builtin_va_start() expression.
5167 static expression_t *parse_va_start(void)
5169 eat(T___builtin_va_start);
5171 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5174 add_anchor_token(',');
5175 expression->va_starte.ap = parse_assignment_expression();
5176 rem_anchor_token(',');
5178 expression_t *const expr = parse_assignment_expression();
5179 if (expr->kind == EXPR_REFERENCE) {
5180 declaration_t *const decl = expr->reference.declaration;
5182 return create_invalid_expression();
5183 if (decl->parent_scope == ¤t_function->scope &&
5184 decl->next == NULL) {
5185 expression->va_starte.parameter = decl;
5190 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
5192 return create_invalid_expression();
5196 * Parses a _builtin_va_arg() expression.
5198 static expression_t *parse_va_arg(void)
5200 eat(T___builtin_va_arg);
5202 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5205 expression->va_arge.ap = parse_assignment_expression();
5207 expression->base.type = parse_typename();
5212 return create_invalid_expression();
5215 static expression_t *parse_builtin_symbol(void)
5217 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5219 symbol_t *symbol = token.v.symbol;
5221 expression->builtin_symbol.symbol = symbol;
5224 type_t *type = get_builtin_symbol_type(symbol);
5225 type = automatic_type_conversion(type);
5227 expression->base.type = type;
5232 * Parses a __builtin_constant() expression.
5234 static expression_t *parse_builtin_constant(void)
5236 eat(T___builtin_constant_p);
5238 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5241 add_anchor_token(')');
5242 expression->builtin_constant.value = parse_assignment_expression();
5243 rem_anchor_token(')');
5245 expression->base.type = type_int;
5249 return create_invalid_expression();
5253 * Parses a __builtin_prefetch() expression.
5255 static expression_t *parse_builtin_prefetch(void)
5257 eat(T___builtin_prefetch);
5259 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5262 add_anchor_token(')');
5263 expression->builtin_prefetch.adr = parse_assignment_expression();
5264 if (token.type == ',') {
5266 expression->builtin_prefetch.rw = parse_assignment_expression();
5268 if (token.type == ',') {
5270 expression->builtin_prefetch.locality = parse_assignment_expression();
5272 rem_anchor_token(')');
5274 expression->base.type = type_void;
5278 return create_invalid_expression();
5282 * Parses a __builtin_is_*() compare expression.
5284 static expression_t *parse_compare_builtin(void)
5286 expression_t *expression;
5288 switch(token.type) {
5289 case T___builtin_isgreater:
5290 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5292 case T___builtin_isgreaterequal:
5293 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5295 case T___builtin_isless:
5296 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5298 case T___builtin_islessequal:
5299 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5301 case T___builtin_islessgreater:
5302 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5304 case T___builtin_isunordered:
5305 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5308 internal_errorf(HERE, "invalid compare builtin found");
5311 expression->base.source_position = HERE;
5315 expression->binary.left = parse_assignment_expression();
5317 expression->binary.right = parse_assignment_expression();
5320 type_t *const orig_type_left = expression->binary.left->base.type;
5321 type_t *const orig_type_right = expression->binary.right->base.type;
5323 type_t *const type_left = skip_typeref(orig_type_left);
5324 type_t *const type_right = skip_typeref(orig_type_right);
5325 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5326 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5327 type_error_incompatible("invalid operands in comparison",
5328 expression->base.source_position, orig_type_left, orig_type_right);
5331 semantic_comparison(&expression->binary);
5336 return create_invalid_expression();
5340 * Parses a __builtin_expect() expression.
5342 static expression_t *parse_builtin_expect(void)
5344 eat(T___builtin_expect);
5346 expression_t *expression
5347 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5350 expression->binary.left = parse_assignment_expression();
5352 expression->binary.right = parse_constant_expression();
5355 expression->base.type = expression->binary.left->base.type;
5359 return create_invalid_expression();
5363 * Parses a MS assume() expression.
5365 static expression_t *parse_assume(void) {
5368 expression_t *expression
5369 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5372 add_anchor_token(')');
5373 expression->unary.value = parse_assignment_expression();
5374 rem_anchor_token(')');
5377 expression->base.type = type_void;
5380 return create_invalid_expression();
5384 * Parse a microsoft __noop expression.
5386 static expression_t *parse_noop_expression(void) {
5387 source_position_t source_position = HERE;
5390 if (token.type == '(') {
5391 /* parse arguments */
5393 add_anchor_token(')');
5394 add_anchor_token(',');
5396 if(token.type != ')') {
5398 (void)parse_assignment_expression();
5399 if(token.type != ',')
5405 rem_anchor_token(',');
5406 rem_anchor_token(')');
5409 /* the result is a (int)0 */
5410 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5411 cnst->base.source_position = source_position;
5412 cnst->base.type = type_int;
5413 cnst->conste.v.int_value = 0;
5414 cnst->conste.is_ms_noop = true;
5419 return create_invalid_expression();
5423 * Parses a primary expression.
5425 static expression_t *parse_primary_expression(void)
5427 switch (token.type) {
5428 case T_INTEGER: return parse_int_const();
5429 case T_CHARACTER_CONSTANT: return parse_character_constant();
5430 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5431 case T_FLOATINGPOINT: return parse_float_const();
5432 case T_STRING_LITERAL:
5433 case T_WIDE_STRING_LITERAL: return parse_string_const();
5434 case T_IDENTIFIER: return parse_reference();
5435 case T___FUNCTION__:
5436 case T___func__: return parse_function_keyword();
5437 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5438 case T___FUNCSIG__: return parse_funcsig_keyword();
5439 case T___FUNCDNAME__: return parse_funcdname_keyword();
5440 case T___builtin_offsetof: return parse_offsetof();
5441 case T___builtin_va_start: return parse_va_start();
5442 case T___builtin_va_arg: return parse_va_arg();
5443 case T___builtin_expect: return parse_builtin_expect();
5444 case T___builtin_alloca:
5445 case T___builtin_nan:
5446 case T___builtin_nand:
5447 case T___builtin_nanf:
5448 case T___builtin_va_end: return parse_builtin_symbol();
5449 case T___builtin_isgreater:
5450 case T___builtin_isgreaterequal:
5451 case T___builtin_isless:
5452 case T___builtin_islessequal:
5453 case T___builtin_islessgreater:
5454 case T___builtin_isunordered: return parse_compare_builtin();
5455 case T___builtin_constant_p: return parse_builtin_constant();
5456 case T___builtin_prefetch: return parse_builtin_prefetch();
5457 case T__assume: return parse_assume();
5459 case '(': return parse_brace_expression();
5460 case T___noop: return parse_noop_expression();
5463 errorf(HERE, "unexpected token %K, expected an expression", &token);
5464 return create_invalid_expression();
5468 * Check if the expression has the character type and issue a warning then.
5470 static void check_for_char_index_type(const expression_t *expression) {
5471 type_t *const type = expression->base.type;
5472 const type_t *const base_type = skip_typeref(type);
5474 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5475 warning.char_subscripts) {
5476 warningf(expression->base.source_position,
5477 "array subscript has type '%T'", type);
5481 static expression_t *parse_array_expression(unsigned precedence,
5487 add_anchor_token(']');
5489 expression_t *inside = parse_expression();
5491 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5493 array_access_expression_t *array_access = &expression->array_access;
5495 type_t *const orig_type_left = left->base.type;
5496 type_t *const orig_type_inside = inside->base.type;
5498 type_t *const type_left = skip_typeref(orig_type_left);
5499 type_t *const type_inside = skip_typeref(orig_type_inside);
5501 type_t *return_type;
5502 if (is_type_pointer(type_left)) {
5503 return_type = type_left->pointer.points_to;
5504 array_access->array_ref = left;
5505 array_access->index = inside;
5506 check_for_char_index_type(inside);
5507 } else if (is_type_pointer(type_inside)) {
5508 return_type = type_inside->pointer.points_to;
5509 array_access->array_ref = inside;
5510 array_access->index = left;
5511 array_access->flipped = true;
5512 check_for_char_index_type(left);
5514 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5516 "array access on object with non-pointer types '%T', '%T'",
5517 orig_type_left, orig_type_inside);
5519 return_type = type_error_type;
5520 array_access->array_ref = create_invalid_expression();
5523 rem_anchor_token(']');
5524 if(token.type != ']') {
5525 parse_error_expected("Problem while parsing array access", ']', 0);
5530 return_type = automatic_type_conversion(return_type);
5531 expression->base.type = return_type;
5536 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5538 expression_t *tp_expression = allocate_expression_zero(kind);
5539 tp_expression->base.type = type_size_t;
5541 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5543 add_anchor_token(')');
5544 tp_expression->typeprop.type = parse_typename();
5545 rem_anchor_token(')');
5548 expression_t *expression = parse_sub_expression(precedence);
5549 expression->base.type = revert_automatic_type_conversion(expression);
5551 tp_expression->typeprop.type = expression->base.type;
5552 tp_expression->typeprop.tp_expression = expression;
5555 return tp_expression;
5557 return create_invalid_expression();
5560 static expression_t *parse_sizeof(unsigned precedence)
5563 return parse_typeprop(EXPR_SIZEOF, precedence);
5566 static expression_t *parse_alignof(unsigned precedence)
5569 return parse_typeprop(EXPR_SIZEOF, precedence);
5572 static expression_t *parse_select_expression(unsigned precedence,
5573 expression_t *compound)
5576 assert(token.type == '.' || token.type == T_MINUSGREATER);
5578 bool is_pointer = (token.type == T_MINUSGREATER);
5581 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5582 select->select.compound = compound;
5584 if(token.type != T_IDENTIFIER) {
5585 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5588 symbol_t *symbol = token.v.symbol;
5589 select->select.symbol = symbol;
5592 type_t *const orig_type = compound->base.type;
5593 type_t *const type = skip_typeref(orig_type);
5595 type_t *type_left = type;
5597 if (!is_type_pointer(type)) {
5598 if (is_type_valid(type)) {
5599 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5601 return create_invalid_expression();
5603 type_left = type->pointer.points_to;
5605 type_left = skip_typeref(type_left);
5607 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5608 type_left->kind != TYPE_COMPOUND_UNION) {
5609 if (is_type_valid(type_left)) {
5610 errorf(HERE, "request for member '%Y' in something not a struct or "
5611 "union, but '%T'", symbol, type_left);
5613 return create_invalid_expression();
5616 declaration_t *const declaration = type_left->compound.declaration;
5618 if(!declaration->init.is_defined) {
5619 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5621 return create_invalid_expression();
5624 declaration_t *iter = find_compound_entry(declaration, symbol);
5626 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5627 return create_invalid_expression();
5630 /* we always do the auto-type conversions; the & and sizeof parser contains
5631 * code to revert this! */
5632 type_t *expression_type = automatic_type_conversion(iter->type);
5634 select->select.compound_entry = iter;
5635 select->base.type = expression_type;
5637 if(expression_type->kind == TYPE_BITFIELD) {
5638 expression_t *extract
5639 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5640 extract->unary.value = select;
5641 extract->base.type = expression_type->bitfield.base;
5650 * Parse a call expression, ie. expression '( ... )'.
5652 * @param expression the function address
5654 static expression_t *parse_call_expression(unsigned precedence,
5655 expression_t *expression)
5658 expression_t *result = allocate_expression_zero(EXPR_CALL);
5659 result->base.source_position = expression->base.source_position;
5661 call_expression_t *call = &result->call;
5662 call->function = expression;
5664 type_t *const orig_type = expression->base.type;
5665 type_t *const type = skip_typeref(orig_type);
5667 function_type_t *function_type = NULL;
5668 if (is_type_pointer(type)) {
5669 type_t *const to_type = skip_typeref(type->pointer.points_to);
5671 if (is_type_function(to_type)) {
5672 function_type = &to_type->function;
5673 call->base.type = function_type->return_type;
5677 if (function_type == NULL && is_type_valid(type)) {
5678 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5681 /* parse arguments */
5683 add_anchor_token(')');
5684 add_anchor_token(',');
5686 if(token.type != ')') {
5687 call_argument_t *last_argument = NULL;
5690 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5692 argument->expression = parse_assignment_expression();
5693 if(last_argument == NULL) {
5694 call->arguments = argument;
5696 last_argument->next = argument;
5698 last_argument = argument;
5700 if(token.type != ',')
5705 rem_anchor_token(',');
5706 rem_anchor_token(')');
5709 if(function_type != NULL) {
5710 function_parameter_t *parameter = function_type->parameters;
5711 call_argument_t *argument = call->arguments;
5712 for( ; parameter != NULL && argument != NULL;
5713 parameter = parameter->next, argument = argument->next) {
5714 type_t *expected_type = parameter->type;
5715 /* TODO report scope in error messages */
5716 expression_t *const arg_expr = argument->expression;
5717 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call", arg_expr->base.source_position);
5718 if (res_type == NULL) {
5719 /* TODO improve error message */
5720 errorf(arg_expr->base.source_position,
5721 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5722 arg_expr, arg_expr->base.type, expected_type);
5724 argument->expression = create_implicit_cast(argument->expression, expected_type);
5727 /* too few parameters */
5728 if(parameter != NULL) {
5729 errorf(HERE, "too few arguments to function '%E'", expression);
5730 } else if(argument != NULL) {
5731 /* too many parameters */
5732 if(!function_type->variadic
5733 && !function_type->unspecified_parameters) {
5734 errorf(HERE, "too many arguments to function '%E'", expression);
5736 /* do default promotion */
5737 for( ; argument != NULL; argument = argument->next) {
5738 type_t *type = argument->expression->base.type;
5740 type = skip_typeref(type);
5741 if(is_type_integer(type)) {
5742 type = promote_integer(type);
5743 } else if(type == type_float) {
5747 argument->expression
5748 = create_implicit_cast(argument->expression, type);
5751 check_format(&result->call);
5754 check_format(&result->call);
5760 return create_invalid_expression();
5763 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5765 static bool same_compound_type(const type_t *type1, const type_t *type2)
5768 is_type_compound(type1) &&
5769 type1->kind == type2->kind &&
5770 type1->compound.declaration == type2->compound.declaration;
5774 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5776 * @param expression the conditional expression
5778 static expression_t *parse_conditional_expression(unsigned precedence,
5779 expression_t *expression)
5782 add_anchor_token(':');
5784 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5786 conditional_expression_t *conditional = &result->conditional;
5787 conditional->condition = expression;
5790 type_t *const condition_type_orig = expression->base.type;
5791 type_t *const condition_type = skip_typeref(condition_type_orig);
5792 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5793 type_error("expected a scalar type in conditional condition",
5794 expression->base.source_position, condition_type_orig);
5797 expression_t *true_expression = parse_expression();
5798 rem_anchor_token(':');
5800 expression_t *false_expression = parse_sub_expression(precedence);
5802 type_t *const orig_true_type = true_expression->base.type;
5803 type_t *const orig_false_type = false_expression->base.type;
5804 type_t *const true_type = skip_typeref(orig_true_type);
5805 type_t *const false_type = skip_typeref(orig_false_type);
5808 type_t *result_type;
5809 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5810 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5811 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5812 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5813 warningf(expression->base.source_position,
5814 "ISO C forbids conditional expression with only one void side");
5816 result_type = type_void;
5817 } else if (is_type_arithmetic(true_type)
5818 && is_type_arithmetic(false_type)) {
5819 result_type = semantic_arithmetic(true_type, false_type);
5821 true_expression = create_implicit_cast(true_expression, result_type);
5822 false_expression = create_implicit_cast(false_expression, result_type);
5824 conditional->true_expression = true_expression;
5825 conditional->false_expression = false_expression;
5826 conditional->base.type = result_type;
5827 } else if (same_compound_type(true_type, false_type)) {
5828 /* just take 1 of the 2 types */
5829 result_type = true_type;
5830 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5831 type_t *pointer_type;
5833 expression_t *other_expression;
5834 if (is_type_pointer(true_type)) {
5835 pointer_type = true_type;
5836 other_type = false_type;
5837 other_expression = false_expression;
5839 pointer_type = false_type;
5840 other_type = true_type;
5841 other_expression = true_expression;
5844 if(is_type_pointer(other_type)) {
5845 if(!pointers_compatible(true_type, false_type)) {
5846 warningf(expression->base.source_position,
5847 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5849 result_type = true_type;
5850 } else if(is_null_pointer_constant(other_expression)) {
5851 result_type = pointer_type;
5852 } else if(is_type_integer(other_type)) {
5853 warningf(expression->base.source_position,
5854 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5855 result_type = pointer_type;
5857 type_error_incompatible("while parsing conditional",
5858 expression->base.source_position, true_type, false_type);
5859 result_type = type_error_type;
5862 /* TODO: one pointer to void*, other some pointer */
5864 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5865 type_error_incompatible("while parsing conditional",
5866 expression->base.source_position, true_type,
5869 result_type = type_error_type;
5872 conditional->true_expression
5873 = create_implicit_cast(true_expression, result_type);
5874 conditional->false_expression
5875 = create_implicit_cast(false_expression, result_type);
5876 conditional->base.type = result_type;
5879 return create_invalid_expression();
5883 * Parse an extension expression.
5885 static expression_t *parse_extension(unsigned precedence)
5887 eat(T___extension__);
5889 /* TODO enable extensions */
5890 expression_t *expression = parse_sub_expression(precedence);
5891 /* TODO disable extensions */
5896 * Parse a __builtin_classify_type() expression.
5898 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5900 eat(T___builtin_classify_type);
5902 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5903 result->base.type = type_int;
5906 add_anchor_token(')');
5907 expression_t *expression = parse_sub_expression(precedence);
5908 rem_anchor_token(')');
5910 result->classify_type.type_expression = expression;
5914 return create_invalid_expression();
5917 static void semantic_incdec(unary_expression_t *expression)
5919 type_t *const orig_type = expression->value->base.type;
5920 type_t *const type = skip_typeref(orig_type);
5921 /* TODO !is_type_real && !is_type_pointer */
5922 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5923 if (is_type_valid(type)) {
5924 /* TODO: improve error message */
5925 errorf(HERE, "operation needs an arithmetic or pointer type");
5930 expression->base.type = orig_type;
5933 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5935 type_t *const orig_type = expression->value->base.type;
5936 type_t *const type = skip_typeref(orig_type);
5937 if(!is_type_arithmetic(type)) {
5938 if (is_type_valid(type)) {
5939 /* TODO: improve error message */
5940 errorf(HERE, "operation needs an arithmetic type");
5945 expression->base.type = orig_type;
5948 static void semantic_unexpr_scalar(unary_expression_t *expression)
5950 type_t *const orig_type = expression->value->base.type;
5951 type_t *const type = skip_typeref(orig_type);
5952 if (!is_type_scalar(type)) {
5953 if (is_type_valid(type)) {
5954 errorf(HERE, "operand of ! must be of scalar type");
5959 expression->base.type = orig_type;
5962 static void semantic_unexpr_integer(unary_expression_t *expression)
5964 type_t *const orig_type = expression->value->base.type;
5965 type_t *const type = skip_typeref(orig_type);
5966 if (!is_type_integer(type)) {
5967 if (is_type_valid(type)) {
5968 errorf(HERE, "operand of ~ must be of integer type");
5973 expression->base.type = orig_type;
5976 static void semantic_dereference(unary_expression_t *expression)
5978 type_t *const orig_type = expression->value->base.type;
5979 type_t *const type = skip_typeref(orig_type);
5980 if(!is_type_pointer(type)) {
5981 if (is_type_valid(type)) {
5982 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5987 type_t *result_type = type->pointer.points_to;
5988 result_type = automatic_type_conversion(result_type);
5989 expression->base.type = result_type;
5993 * Check the semantic of the address taken expression.
5995 static void semantic_take_addr(unary_expression_t *expression)
5997 expression_t *value = expression->value;
5998 value->base.type = revert_automatic_type_conversion(value);
6000 type_t *orig_type = value->base.type;
6001 if(!is_type_valid(orig_type))
6004 if(value->kind == EXPR_REFERENCE) {
6005 declaration_t *const declaration = value->reference.declaration;
6006 if(declaration != NULL) {
6007 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6008 errorf(expression->base.source_position,
6009 "address of register variable '%Y' requested",
6010 declaration->symbol);
6012 declaration->address_taken = 1;
6016 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6019 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6020 static expression_t *parse_##unexpression_type(unsigned precedence) \
6024 expression_t *unary_expression \
6025 = allocate_expression_zero(unexpression_type); \
6026 unary_expression->base.source_position = HERE; \
6027 unary_expression->unary.value = parse_sub_expression(precedence); \
6029 sfunc(&unary_expression->unary); \
6031 return unary_expression; \
6034 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6035 semantic_unexpr_arithmetic)
6036 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6037 semantic_unexpr_arithmetic)
6038 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6039 semantic_unexpr_scalar)
6040 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6041 semantic_dereference)
6042 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6044 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6045 semantic_unexpr_integer)
6046 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6048 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6051 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6053 static expression_t *parse_##unexpression_type(unsigned precedence, \
6054 expression_t *left) \
6056 (void) precedence; \
6059 expression_t *unary_expression \
6060 = allocate_expression_zero(unexpression_type); \
6061 unary_expression->unary.value = left; \
6063 sfunc(&unary_expression->unary); \
6065 return unary_expression; \
6068 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6069 EXPR_UNARY_POSTFIX_INCREMENT,
6071 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6072 EXPR_UNARY_POSTFIX_DECREMENT,
6075 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6077 /* TODO: handle complex + imaginary types */
6079 /* § 6.3.1.8 Usual arithmetic conversions */
6080 if(type_left == type_long_double || type_right == type_long_double) {
6081 return type_long_double;
6082 } else if(type_left == type_double || type_right == type_double) {
6084 } else if(type_left == type_float || type_right == type_float) {
6088 type_right = promote_integer(type_right);
6089 type_left = promote_integer(type_left);
6091 if(type_left == type_right)
6094 bool signed_left = is_type_signed(type_left);
6095 bool signed_right = is_type_signed(type_right);
6096 int rank_left = get_rank(type_left);
6097 int rank_right = get_rank(type_right);
6098 if(rank_left < rank_right) {
6099 if(signed_left == signed_right || !signed_right) {
6105 if(signed_left == signed_right || !signed_left) {
6114 * Check the semantic restrictions for a binary expression.
6116 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6118 expression_t *const left = expression->left;
6119 expression_t *const right = expression->right;
6120 type_t *const orig_type_left = left->base.type;
6121 type_t *const orig_type_right = right->base.type;
6122 type_t *const type_left = skip_typeref(orig_type_left);
6123 type_t *const type_right = skip_typeref(orig_type_right);
6125 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6126 /* TODO: improve error message */
6127 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6128 errorf(HERE, "operation needs arithmetic types");
6133 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6134 expression->left = create_implicit_cast(left, arithmetic_type);
6135 expression->right = create_implicit_cast(right, arithmetic_type);
6136 expression->base.type = arithmetic_type;
6139 static void semantic_shift_op(binary_expression_t *expression)
6141 expression_t *const left = expression->left;
6142 expression_t *const right = expression->right;
6143 type_t *const orig_type_left = left->base.type;
6144 type_t *const orig_type_right = right->base.type;
6145 type_t * type_left = skip_typeref(orig_type_left);
6146 type_t * type_right = skip_typeref(orig_type_right);
6148 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6149 /* TODO: improve error message */
6150 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6151 errorf(HERE, "operation needs integer types");
6156 type_left = promote_integer(type_left);
6157 type_right = promote_integer(type_right);
6159 expression->left = create_implicit_cast(left, type_left);
6160 expression->right = create_implicit_cast(right, type_right);
6161 expression->base.type = type_left;
6164 static void semantic_add(binary_expression_t *expression)
6166 expression_t *const left = expression->left;
6167 expression_t *const right = expression->right;
6168 type_t *const orig_type_left = left->base.type;
6169 type_t *const orig_type_right = right->base.type;
6170 type_t *const type_left = skip_typeref(orig_type_left);
6171 type_t *const type_right = skip_typeref(orig_type_right);
6174 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6175 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6176 expression->left = create_implicit_cast(left, arithmetic_type);
6177 expression->right = create_implicit_cast(right, arithmetic_type);
6178 expression->base.type = arithmetic_type;
6180 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6181 expression->base.type = type_left;
6182 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
6183 expression->base.type = type_right;
6184 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6185 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
6189 static void semantic_sub(binary_expression_t *expression)
6191 expression_t *const left = expression->left;
6192 expression_t *const right = expression->right;
6193 type_t *const orig_type_left = left->base.type;
6194 type_t *const orig_type_right = right->base.type;
6195 type_t *const type_left = skip_typeref(orig_type_left);
6196 type_t *const type_right = skip_typeref(orig_type_right);
6199 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6200 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6201 expression->left = create_implicit_cast(left, arithmetic_type);
6202 expression->right = create_implicit_cast(right, arithmetic_type);
6203 expression->base.type = arithmetic_type;
6205 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6206 expression->base.type = type_left;
6207 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6208 if(!pointers_compatible(type_left, type_right)) {
6210 "pointers to incompatible objects to binary '-' ('%T', '%T')",
6211 orig_type_left, orig_type_right);
6213 expression->base.type = type_ptrdiff_t;
6215 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6216 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6217 orig_type_left, orig_type_right);
6222 * Check the semantics of comparison expressions.
6224 * @param expression The expression to check.
6226 static void semantic_comparison(binary_expression_t *expression)
6228 expression_t *left = expression->left;
6229 expression_t *right = expression->right;
6230 type_t *orig_type_left = left->base.type;
6231 type_t *orig_type_right = right->base.type;
6233 type_t *type_left = skip_typeref(orig_type_left);
6234 type_t *type_right = skip_typeref(orig_type_right);
6236 /* TODO non-arithmetic types */
6237 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6238 if (warning.sign_compare &&
6239 (expression->base.kind != EXPR_BINARY_EQUAL &&
6240 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6241 (is_type_signed(type_left) != is_type_signed(type_right))) {
6242 warningf(expression->base.source_position,
6243 "comparison between signed and unsigned");
6245 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6246 expression->left = create_implicit_cast(left, arithmetic_type);
6247 expression->right = create_implicit_cast(right, arithmetic_type);
6248 expression->base.type = arithmetic_type;
6249 if (warning.float_equal &&
6250 (expression->base.kind == EXPR_BINARY_EQUAL ||
6251 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6252 is_type_float(arithmetic_type)) {
6253 warningf(expression->base.source_position,
6254 "comparing floating point with == or != is unsafe");
6256 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6257 /* TODO check compatibility */
6258 } else if (is_type_pointer(type_left)) {
6259 expression->right = create_implicit_cast(right, type_left);
6260 } else if (is_type_pointer(type_right)) {
6261 expression->left = create_implicit_cast(left, type_right);
6262 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6263 type_error_incompatible("invalid operands in comparison",
6264 expression->base.source_position,
6265 type_left, type_right);
6267 expression->base.type = type_int;
6270 static void semantic_arithmetic_assign(binary_expression_t *expression)
6272 expression_t *left = expression->left;
6273 expression_t *right = expression->right;
6274 type_t *orig_type_left = left->base.type;
6275 type_t *orig_type_right = right->base.type;
6277 type_t *type_left = skip_typeref(orig_type_left);
6278 type_t *type_right = skip_typeref(orig_type_right);
6280 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6281 /* TODO: improve error message */
6282 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6283 errorf(HERE, "operation needs arithmetic types");
6288 /* combined instructions are tricky. We can't create an implicit cast on
6289 * the left side, because we need the uncasted form for the store.
6290 * The ast2firm pass has to know that left_type must be right_type
6291 * for the arithmetic operation and create a cast by itself */
6292 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6293 expression->right = create_implicit_cast(right, arithmetic_type);
6294 expression->base.type = type_left;
6297 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6299 expression_t *const left = expression->left;
6300 expression_t *const right = expression->right;
6301 type_t *const orig_type_left = left->base.type;
6302 type_t *const orig_type_right = right->base.type;
6303 type_t *const type_left = skip_typeref(orig_type_left);
6304 type_t *const type_right = skip_typeref(orig_type_right);
6306 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6307 /* combined instructions are tricky. We can't create an implicit cast on
6308 * the left side, because we need the uncasted form for the store.
6309 * The ast2firm pass has to know that left_type must be right_type
6310 * for the arithmetic operation and create a cast by itself */
6311 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6312 expression->right = create_implicit_cast(right, arithmetic_type);
6313 expression->base.type = type_left;
6314 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6315 expression->base.type = type_left;
6316 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6317 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6322 * Check the semantic restrictions of a logical expression.
6324 static void semantic_logical_op(binary_expression_t *expression)
6326 expression_t *const left = expression->left;
6327 expression_t *const right = expression->right;
6328 type_t *const orig_type_left = left->base.type;
6329 type_t *const orig_type_right = right->base.type;
6330 type_t *const type_left = skip_typeref(orig_type_left);
6331 type_t *const type_right = skip_typeref(orig_type_right);
6333 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6334 /* TODO: improve error message */
6335 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6336 errorf(HERE, "operation needs scalar types");
6341 expression->base.type = type_int;
6345 * Checks if a compound type has constant fields.
6347 static bool has_const_fields(const compound_type_t *type)
6349 const scope_t *scope = &type->declaration->scope;
6350 const declaration_t *declaration = scope->declarations;
6352 for (; declaration != NULL; declaration = declaration->next) {
6353 if (declaration->namespc != NAMESPACE_NORMAL)
6356 const type_t *decl_type = skip_typeref(declaration->type);
6357 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6365 * Check the semantic restrictions of a binary assign expression.
6367 static void semantic_binexpr_assign(binary_expression_t *expression)
6369 expression_t *left = expression->left;
6370 type_t *orig_type_left = left->base.type;
6372 type_t *type_left = revert_automatic_type_conversion(left);
6373 type_left = skip_typeref(orig_type_left);
6375 /* must be a modifiable lvalue */
6376 if (is_type_array(type_left)) {
6377 errorf(HERE, "cannot assign to arrays ('%E')", left);
6380 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6381 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6385 if(is_type_incomplete(type_left)) {
6387 "left-hand side of assignment '%E' has incomplete type '%T'",
6388 left, orig_type_left);
6391 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6392 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6393 left, orig_type_left);
6397 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6398 "assignment", left->base.source_position);
6399 if (res_type == NULL) {
6400 errorf(expression->base.source_position,
6401 "cannot assign to '%T' from '%T'",
6402 orig_type_left, expression->right->base.type);
6404 expression->right = create_implicit_cast(expression->right, res_type);
6407 expression->base.type = orig_type_left;
6411 * Determine if the outermost operation (or parts thereof) of the given
6412 * expression has no effect in order to generate a warning about this fact.
6413 * Therefore in some cases this only examines some of the operands of the
6414 * expression (see comments in the function and examples below).
6416 * f() + 23; // warning, because + has no effect
6417 * x || f(); // no warning, because x controls execution of f()
6418 * x ? y : f(); // warning, because y has no effect
6419 * (void)x; // no warning to be able to suppress the warning
6420 * This function can NOT be used for an "expression has definitely no effect"-
6422 static bool expression_has_effect(const expression_t *const expr)
6424 switch (expr->kind) {
6425 case EXPR_UNKNOWN: break;
6426 case EXPR_INVALID: return true; /* do NOT warn */
6427 case EXPR_REFERENCE: return false;
6428 /* suppress the warning for microsoft __noop operations */
6429 case EXPR_CONST: return expr->conste.is_ms_noop;
6430 case EXPR_CHARACTER_CONSTANT: return false;
6431 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6432 case EXPR_STRING_LITERAL: return false;
6433 case EXPR_WIDE_STRING_LITERAL: return false;
6436 const call_expression_t *const call = &expr->call;
6437 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6440 switch (call->function->builtin_symbol.symbol->ID) {
6441 case T___builtin_va_end: return true;
6442 default: return false;
6446 /* Generate the warning if either the left or right hand side of a
6447 * conditional expression has no effect */
6448 case EXPR_CONDITIONAL: {
6449 const conditional_expression_t *const cond = &expr->conditional;
6451 expression_has_effect(cond->true_expression) &&
6452 expression_has_effect(cond->false_expression);
6455 case EXPR_SELECT: return false;
6456 case EXPR_ARRAY_ACCESS: return false;
6457 case EXPR_SIZEOF: return false;
6458 case EXPR_CLASSIFY_TYPE: return false;
6459 case EXPR_ALIGNOF: return false;
6461 case EXPR_FUNCNAME: return false;
6462 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6463 case EXPR_BUILTIN_CONSTANT_P: return false;
6464 case EXPR_BUILTIN_PREFETCH: return true;
6465 case EXPR_OFFSETOF: return false;
6466 case EXPR_VA_START: return true;
6467 case EXPR_VA_ARG: return true;
6468 case EXPR_STATEMENT: return true; // TODO
6469 case EXPR_COMPOUND_LITERAL: return false;
6471 case EXPR_UNARY_NEGATE: return false;
6472 case EXPR_UNARY_PLUS: return false;
6473 case EXPR_UNARY_BITWISE_NEGATE: return false;
6474 case EXPR_UNARY_NOT: return false;
6475 case EXPR_UNARY_DEREFERENCE: return false;
6476 case EXPR_UNARY_TAKE_ADDRESS: return false;
6477 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6478 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6479 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6480 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6482 /* Treat void casts as if they have an effect in order to being able to
6483 * suppress the warning */
6484 case EXPR_UNARY_CAST: {
6485 type_t *const type = skip_typeref(expr->base.type);
6486 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6489 case EXPR_UNARY_CAST_IMPLICIT: return true;
6490 case EXPR_UNARY_ASSUME: return true;
6491 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6493 case EXPR_BINARY_ADD: return false;
6494 case EXPR_BINARY_SUB: return false;
6495 case EXPR_BINARY_MUL: return false;
6496 case EXPR_BINARY_DIV: return false;
6497 case EXPR_BINARY_MOD: return false;
6498 case EXPR_BINARY_EQUAL: return false;
6499 case EXPR_BINARY_NOTEQUAL: return false;
6500 case EXPR_BINARY_LESS: return false;
6501 case EXPR_BINARY_LESSEQUAL: return false;
6502 case EXPR_BINARY_GREATER: return false;
6503 case EXPR_BINARY_GREATEREQUAL: return false;
6504 case EXPR_BINARY_BITWISE_AND: return false;
6505 case EXPR_BINARY_BITWISE_OR: return false;
6506 case EXPR_BINARY_BITWISE_XOR: return false;
6507 case EXPR_BINARY_SHIFTLEFT: return false;
6508 case EXPR_BINARY_SHIFTRIGHT: return false;
6509 case EXPR_BINARY_ASSIGN: return true;
6510 case EXPR_BINARY_MUL_ASSIGN: return true;
6511 case EXPR_BINARY_DIV_ASSIGN: return true;
6512 case EXPR_BINARY_MOD_ASSIGN: return true;
6513 case EXPR_BINARY_ADD_ASSIGN: return true;
6514 case EXPR_BINARY_SUB_ASSIGN: return true;
6515 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6516 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6517 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6518 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6519 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6521 /* Only examine the right hand side of && and ||, because the left hand
6522 * side already has the effect of controlling the execution of the right
6524 case EXPR_BINARY_LOGICAL_AND:
6525 case EXPR_BINARY_LOGICAL_OR:
6526 /* Only examine the right hand side of a comma expression, because the left
6527 * hand side has a separate warning */
6528 case EXPR_BINARY_COMMA:
6529 return expression_has_effect(expr->binary.right);
6531 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6532 case EXPR_BINARY_ISGREATER: return false;
6533 case EXPR_BINARY_ISGREATEREQUAL: return false;
6534 case EXPR_BINARY_ISLESS: return false;
6535 case EXPR_BINARY_ISLESSEQUAL: return false;
6536 case EXPR_BINARY_ISLESSGREATER: return false;
6537 case EXPR_BINARY_ISUNORDERED: return false;
6540 internal_errorf(HERE, "unexpected expression");
6543 static void semantic_comma(binary_expression_t *expression)
6545 if (warning.unused_value) {
6546 const expression_t *const left = expression->left;
6547 if (!expression_has_effect(left)) {
6548 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6551 expression->base.type = expression->right->base.type;
6554 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6555 static expression_t *parse_##binexpression_type(unsigned precedence, \
6556 expression_t *left) \
6559 source_position_t pos = HERE; \
6561 expression_t *right = parse_sub_expression(precedence + lr); \
6563 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6564 binexpr->base.source_position = pos; \
6565 binexpr->binary.left = left; \
6566 binexpr->binary.right = right; \
6567 sfunc(&binexpr->binary); \
6572 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6573 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6574 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6575 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6576 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6577 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6578 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6579 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6580 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6582 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6583 semantic_comparison, 1)
6584 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6585 semantic_comparison, 1)
6586 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6587 semantic_comparison, 1)
6588 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6589 semantic_comparison, 1)
6591 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6592 semantic_binexpr_arithmetic, 1)
6593 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6594 semantic_binexpr_arithmetic, 1)
6595 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6596 semantic_binexpr_arithmetic, 1)
6597 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6598 semantic_logical_op, 1)
6599 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6600 semantic_logical_op, 1)
6601 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6602 semantic_shift_op, 1)
6603 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6604 semantic_shift_op, 1)
6605 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6606 semantic_arithmetic_addsubb_assign, 0)
6607 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6608 semantic_arithmetic_addsubb_assign, 0)
6609 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6610 semantic_arithmetic_assign, 0)
6611 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6612 semantic_arithmetic_assign, 0)
6613 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6614 semantic_arithmetic_assign, 0)
6615 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6616 semantic_arithmetic_assign, 0)
6617 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6618 semantic_arithmetic_assign, 0)
6619 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6620 semantic_arithmetic_assign, 0)
6621 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6622 semantic_arithmetic_assign, 0)
6623 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6624 semantic_arithmetic_assign, 0)
6626 static expression_t *parse_sub_expression(unsigned precedence)
6628 if(token.type < 0) {
6629 return expected_expression_error();
6632 expression_parser_function_t *parser
6633 = &expression_parsers[token.type];
6634 source_position_t source_position = token.source_position;
6637 if(parser->parser != NULL) {
6638 left = parser->parser(parser->precedence);
6640 left = parse_primary_expression();
6642 assert(left != NULL);
6643 left->base.source_position = source_position;
6646 if(token.type < 0) {
6647 return expected_expression_error();
6650 parser = &expression_parsers[token.type];
6651 if(parser->infix_parser == NULL)
6653 if(parser->infix_precedence < precedence)
6656 left = parser->infix_parser(parser->infix_precedence, left);
6658 assert(left != NULL);
6659 assert(left->kind != EXPR_UNKNOWN);
6660 left->base.source_position = source_position;
6667 * Parse an expression.
6669 static expression_t *parse_expression(void)
6671 return parse_sub_expression(1);
6675 * Register a parser for a prefix-like operator with given precedence.
6677 * @param parser the parser function
6678 * @param token_type the token type of the prefix token
6679 * @param precedence the precedence of the operator
6681 static void register_expression_parser(parse_expression_function parser,
6682 int token_type, unsigned precedence)
6684 expression_parser_function_t *entry = &expression_parsers[token_type];
6686 if(entry->parser != NULL) {
6687 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6688 panic("trying to register multiple expression parsers for a token");
6690 entry->parser = parser;
6691 entry->precedence = precedence;
6695 * Register a parser for an infix operator with given precedence.
6697 * @param parser the parser function
6698 * @param token_type the token type of the infix operator
6699 * @param precedence the precedence of the operator
6701 static void register_infix_parser(parse_expression_infix_function parser,
6702 int token_type, unsigned precedence)
6704 expression_parser_function_t *entry = &expression_parsers[token_type];
6706 if(entry->infix_parser != NULL) {
6707 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6708 panic("trying to register multiple infix expression parsers for a "
6711 entry->infix_parser = parser;
6712 entry->infix_precedence = precedence;
6716 * Initialize the expression parsers.
6718 static void init_expression_parsers(void)
6720 memset(&expression_parsers, 0, sizeof(expression_parsers));
6722 register_infix_parser(parse_array_expression, '[', 30);
6723 register_infix_parser(parse_call_expression, '(', 30);
6724 register_infix_parser(parse_select_expression, '.', 30);
6725 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6726 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6728 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6731 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6732 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6733 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6734 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6735 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6736 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6737 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6738 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6739 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6740 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6741 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6742 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6743 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6744 T_EXCLAMATIONMARKEQUAL, 13);
6745 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6746 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6747 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6748 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6749 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6750 register_infix_parser(parse_conditional_expression, '?', 7);
6751 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6752 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6753 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6754 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6755 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6756 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6757 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6758 T_LESSLESSEQUAL, 2);
6759 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6760 T_GREATERGREATEREQUAL, 2);
6761 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6763 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6765 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6768 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6770 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6771 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6772 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6773 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6774 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6775 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6776 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6778 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6780 register_expression_parser(parse_sizeof, T_sizeof, 25);
6781 register_expression_parser(parse_alignof, T___alignof__, 25);
6782 register_expression_parser(parse_extension, T___extension__, 25);
6783 register_expression_parser(parse_builtin_classify_type,
6784 T___builtin_classify_type, 25);
6788 * Parse a asm statement constraints specification.
6790 static asm_constraint_t *parse_asm_constraints(void)
6792 asm_constraint_t *result = NULL;
6793 asm_constraint_t *last = NULL;
6795 while(token.type == T_STRING_LITERAL || token.type == '[') {
6796 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6797 memset(constraint, 0, sizeof(constraint[0]));
6799 if(token.type == '[') {
6801 if(token.type != T_IDENTIFIER) {
6802 parse_error_expected("while parsing asm constraint",
6806 constraint->symbol = token.v.symbol;
6811 constraint->constraints = parse_string_literals();
6813 constraint->expression = parse_expression();
6817 last->next = constraint;
6819 result = constraint;
6823 if(token.type != ',')
6834 * Parse a asm statement clobber specification.
6836 static asm_clobber_t *parse_asm_clobbers(void)
6838 asm_clobber_t *result = NULL;
6839 asm_clobber_t *last = NULL;
6841 while(token.type == T_STRING_LITERAL) {
6842 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6843 clobber->clobber = parse_string_literals();
6846 last->next = clobber;
6852 if(token.type != ',')
6861 * Parse an asm statement.
6863 static statement_t *parse_asm_statement(void)
6867 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6868 statement->base.source_position = token.source_position;
6870 asm_statement_t *asm_statement = &statement->asms;
6872 if(token.type == T_volatile) {
6874 asm_statement->is_volatile = true;
6878 add_anchor_token(')');
6879 add_anchor_token(':');
6880 asm_statement->asm_text = parse_string_literals();
6882 if(token.type != ':') {
6883 rem_anchor_token(':');
6888 asm_statement->inputs = parse_asm_constraints();
6889 if(token.type != ':') {
6890 rem_anchor_token(':');
6895 asm_statement->outputs = parse_asm_constraints();
6896 if(token.type != ':') {
6897 rem_anchor_token(':');
6900 rem_anchor_token(':');
6903 asm_statement->clobbers = parse_asm_clobbers();
6906 rem_anchor_token(')');
6911 return create_invalid_statement();
6915 * Parse a case statement.
6917 static statement_t *parse_case_statement(void)
6921 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6923 statement->base.source_position = token.source_position;
6924 statement->case_label.expression = parse_expression();
6926 if (c_mode & _GNUC) {
6927 if (token.type == T_DOTDOTDOT) {
6929 statement->case_label.end_range = parse_expression();
6935 if (! is_constant_expression(statement->case_label.expression)) {
6936 errorf(statement->base.source_position,
6937 "case label does not reduce to an integer constant");
6939 /* TODO: check if the case label is already known */
6940 if (current_switch != NULL) {
6941 /* link all cases into the switch statement */
6942 if (current_switch->last_case == NULL) {
6943 current_switch->first_case =
6944 current_switch->last_case = &statement->case_label;
6946 current_switch->last_case->next = &statement->case_label;
6949 errorf(statement->base.source_position,
6950 "case label not within a switch statement");
6953 statement->case_label.statement = parse_statement();
6957 return create_invalid_statement();
6961 * Finds an existing default label of a switch statement.
6963 static case_label_statement_t *
6964 find_default_label(const switch_statement_t *statement)
6966 case_label_statement_t *label = statement->first_case;
6967 for ( ; label != NULL; label = label->next) {
6968 if (label->expression == NULL)
6975 * Parse a default statement.
6977 static statement_t *parse_default_statement(void)
6981 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6983 statement->base.source_position = token.source_position;
6986 if (current_switch != NULL) {
6987 const case_label_statement_t *def_label = find_default_label(current_switch);
6988 if (def_label != NULL) {
6989 errorf(HERE, "multiple default labels in one switch");
6990 errorf(def_label->base.source_position,
6991 "this is the first default label");
6993 /* link all cases into the switch statement */
6994 if (current_switch->last_case == NULL) {
6995 current_switch->first_case =
6996 current_switch->last_case = &statement->case_label;
6998 current_switch->last_case->next = &statement->case_label;
7002 errorf(statement->base.source_position,
7003 "'default' label not within a switch statement");
7005 statement->case_label.statement = parse_statement();
7009 return create_invalid_statement();
7013 * Return the declaration for a given label symbol or create a new one.
7015 static declaration_t *get_label(symbol_t *symbol)
7017 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7018 assert(current_function != NULL);
7019 /* if we found a label in the same function, then we already created the
7021 if(candidate != NULL
7022 && candidate->parent_scope == ¤t_function->scope) {
7026 /* otherwise we need to create a new one */
7027 declaration_t *const declaration = allocate_declaration_zero();
7028 declaration->namespc = NAMESPACE_LABEL;
7029 declaration->symbol = symbol;
7031 label_push(declaration);
7037 * Parse a label statement.
7039 static statement_t *parse_label_statement(void)
7041 assert(token.type == T_IDENTIFIER);
7042 symbol_t *symbol = token.v.symbol;
7045 declaration_t *label = get_label(symbol);
7047 /* if source position is already set then the label is defined twice,
7048 * otherwise it was just mentioned in a goto so far */
7049 if(label->source_position.input_name != NULL) {
7050 errorf(HERE, "duplicate label '%Y' (declared %P)",
7051 symbol, label->source_position);
7053 label->source_position = token.source_position;
7056 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7058 statement->base.source_position = token.source_position;
7059 statement->label.label = label;
7063 if(token.type == '}') {
7064 /* TODO only warn? */
7066 warningf(HERE, "label at end of compound statement");
7067 statement->label.statement = create_empty_statement();
7069 errorf(HERE, "label at end of compound statement");
7070 statement->label.statement = create_invalid_statement();
7074 if (token.type == ';') {
7075 /* eat an empty statement here, to avoid the warning about an empty
7076 * after a label. label:; is commonly used to have a label before
7078 statement->label.statement = create_empty_statement();
7081 statement->label.statement = parse_statement();
7085 /* remember the labels's in a list for later checking */
7086 if (label_last == NULL) {
7087 label_first = &statement->label;
7089 label_last->next = &statement->label;
7091 label_last = &statement->label;
7097 * Parse an if statement.
7099 static statement_t *parse_if(void)
7103 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7104 statement->base.source_position = token.source_position;
7107 add_anchor_token(')');
7108 statement->ifs.condition = parse_expression();
7109 rem_anchor_token(')');
7112 add_anchor_token(T_else);
7113 statement->ifs.true_statement = parse_statement();
7114 rem_anchor_token(T_else);
7116 if(token.type == T_else) {
7118 statement->ifs.false_statement = parse_statement();
7123 return create_invalid_statement();
7127 * Parse a switch statement.
7129 static statement_t *parse_switch(void)
7133 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7134 statement->base.source_position = token.source_position;
7137 expression_t *const expr = parse_expression();
7138 type_t * type = skip_typeref(expr->base.type);
7139 if (is_type_integer(type)) {
7140 type = promote_integer(type);
7141 } else if (is_type_valid(type)) {
7142 errorf(expr->base.source_position,
7143 "switch quantity is not an integer, but '%T'", type);
7144 type = type_error_type;
7146 statement->switchs.expression = create_implicit_cast(expr, type);
7149 switch_statement_t *rem = current_switch;
7150 current_switch = &statement->switchs;
7151 statement->switchs.body = parse_statement();
7152 current_switch = rem;
7154 if (warning.switch_default
7155 && find_default_label(&statement->switchs) == NULL) {
7156 warningf(statement->base.source_position, "switch has no default case");
7161 return create_invalid_statement();
7164 static statement_t *parse_loop_body(statement_t *const loop)
7166 statement_t *const rem = current_loop;
7167 current_loop = loop;
7169 statement_t *const body = parse_statement();
7176 * Parse a while statement.
7178 static statement_t *parse_while(void)
7182 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7183 statement->base.source_position = token.source_position;
7186 add_anchor_token(')');
7187 statement->whiles.condition = parse_expression();
7188 rem_anchor_token(')');
7191 statement->whiles.body = parse_loop_body(statement);
7195 return create_invalid_statement();
7199 * Parse a do statement.
7201 static statement_t *parse_do(void)
7205 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7207 statement->base.source_position = token.source_position;
7209 add_anchor_token(T_while);
7210 statement->do_while.body = parse_loop_body(statement);
7211 rem_anchor_token(T_while);
7215 add_anchor_token(')');
7216 statement->do_while.condition = parse_expression();
7217 rem_anchor_token(')');
7223 return create_invalid_statement();
7227 * Parse a for statement.
7229 static statement_t *parse_for(void)
7233 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7234 statement->base.source_position = token.source_position;
7236 int top = environment_top();
7237 scope_t *last_scope = scope;
7238 set_scope(&statement->fors.scope);
7241 add_anchor_token(')');
7243 if(token.type != ';') {
7244 if(is_declaration_specifier(&token, false)) {
7245 parse_declaration(record_declaration);
7247 expression_t *const init = parse_expression();
7248 statement->fors.initialisation = init;
7249 if (warning.unused_value && !expression_has_effect(init)) {
7250 warningf(init->base.source_position,
7251 "initialisation of 'for'-statement has no effect");
7259 if(token.type != ';') {
7260 statement->fors.condition = parse_expression();
7263 if(token.type != ')') {
7264 expression_t *const step = parse_expression();
7265 statement->fors.step = step;
7266 if (warning.unused_value && !expression_has_effect(step)) {
7267 warningf(step->base.source_position,
7268 "step of 'for'-statement has no effect");
7271 rem_anchor_token(')');
7273 statement->fors.body = parse_loop_body(statement);
7275 assert(scope == &statement->fors.scope);
7276 set_scope(last_scope);
7277 environment_pop_to(top);
7282 rem_anchor_token(')');
7283 assert(scope == &statement->fors.scope);
7284 set_scope(last_scope);
7285 environment_pop_to(top);
7287 return create_invalid_statement();
7291 * Parse a goto statement.
7293 static statement_t *parse_goto(void)
7297 if(token.type != T_IDENTIFIER) {
7298 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
7302 symbol_t *symbol = token.v.symbol;
7305 declaration_t *label = get_label(symbol);
7307 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7308 statement->base.source_position = token.source_position;
7310 statement->gotos.label = label;
7312 /* remember the goto's in a list for later checking */
7313 if (goto_last == NULL) {
7314 goto_first = &statement->gotos;
7316 goto_last->next = &statement->gotos;
7318 goto_last = &statement->gotos;
7324 return create_invalid_statement();
7328 * Parse a continue statement.
7330 static statement_t *parse_continue(void)
7332 statement_t *statement;
7333 if (current_loop == NULL) {
7334 errorf(HERE, "continue statement not within loop");
7337 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7339 statement->base.source_position = token.source_position;
7347 return create_invalid_statement();
7351 * Parse a break statement.
7353 static statement_t *parse_break(void)
7355 statement_t *statement;
7356 if (current_switch == NULL && current_loop == NULL) {
7357 errorf(HERE, "break statement not within loop or switch");
7360 statement = allocate_statement_zero(STATEMENT_BREAK);
7362 statement->base.source_position = token.source_position;
7370 return create_invalid_statement();
7374 * Check if a given declaration represents a local variable.
7376 static bool is_local_var_declaration(const declaration_t *declaration) {
7377 switch ((storage_class_tag_t) declaration->storage_class) {
7378 case STORAGE_CLASS_AUTO:
7379 case STORAGE_CLASS_REGISTER: {
7380 const type_t *type = skip_typeref(declaration->type);
7381 if(is_type_function(type)) {
7393 * Check if a given declaration represents a variable.
7395 static bool is_var_declaration(const declaration_t *declaration) {
7396 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7399 const type_t *type = skip_typeref(declaration->type);
7400 return !is_type_function(type);
7404 * Check if a given expression represents a local variable.
7406 static bool is_local_variable(const expression_t *expression)
7408 if (expression->base.kind != EXPR_REFERENCE) {
7411 const declaration_t *declaration = expression->reference.declaration;
7412 return is_local_var_declaration(declaration);
7416 * Check if a given expression represents a local variable and
7417 * return its declaration then, else return NULL.
7419 declaration_t *expr_is_variable(const expression_t *expression)
7421 if (expression->base.kind != EXPR_REFERENCE) {
7424 declaration_t *declaration = expression->reference.declaration;
7425 if (is_var_declaration(declaration))
7431 * Parse a return statement.
7433 static statement_t *parse_return(void)
7435 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7436 statement->base.source_position = token.source_position;
7440 expression_t *return_value = NULL;
7441 if(token.type != ';') {
7442 return_value = parse_expression();
7446 const type_t *const func_type = current_function->type;
7447 assert(is_type_function(func_type));
7448 type_t *const return_type = skip_typeref(func_type->function.return_type);
7450 if(return_value != NULL) {
7451 type_t *return_value_type = skip_typeref(return_value->base.type);
7453 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7454 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7455 warningf(statement->base.source_position,
7456 "'return' with a value, in function returning void");
7457 return_value = NULL;
7459 type_t *const res_type = semantic_assign(return_type,
7460 return_value, "'return'", statement->base.source_position);
7461 if (res_type == NULL) {
7462 errorf(statement->base.source_position,
7463 "cannot return something of type '%T' in function returning '%T'",
7464 return_value->base.type, return_type);
7466 return_value = create_implicit_cast(return_value, res_type);
7469 /* check for returning address of a local var */
7470 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7471 const expression_t *expression = return_value->unary.value;
7472 if (is_local_variable(expression)) {
7473 warningf(statement->base.source_position,
7474 "function returns address of local variable");
7478 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7479 warningf(statement->base.source_position,
7480 "'return' without value, in function returning non-void");
7483 statement->returns.value = return_value;
7487 return create_invalid_statement();
7491 * Parse a declaration statement.
7493 static statement_t *parse_declaration_statement(void)
7495 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7497 statement->base.source_position = token.source_position;
7499 declaration_t *before = last_declaration;
7500 parse_declaration(record_declaration);
7502 if(before == NULL) {
7503 statement->declaration.declarations_begin = scope->declarations;
7505 statement->declaration.declarations_begin = before->next;
7507 statement->declaration.declarations_end = last_declaration;
7513 * Parse an expression statement, ie. expr ';'.
7515 static statement_t *parse_expression_statement(void)
7517 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7519 statement->base.source_position = token.source_position;
7520 expression_t *const expr = parse_expression();
7521 statement->expression.expression = expr;
7523 if (warning.unused_value && !expression_has_effect(expr)) {
7524 warningf(expr->base.source_position, "statement has no effect");
7531 return create_invalid_statement();
7535 * Parse a statement.
7537 static statement_t *parse_statement(void)
7539 statement_t *statement = NULL;
7541 /* declaration or statement */
7542 add_anchor_token(';');
7543 switch(token.type) {
7545 statement = parse_asm_statement();
7549 statement = parse_case_statement();
7553 statement = parse_default_statement();
7557 statement = parse_compound_statement();
7561 statement = parse_if();
7565 statement = parse_switch();
7569 statement = parse_while();
7573 statement = parse_do();
7577 statement = parse_for();
7581 statement = parse_goto();
7585 statement = parse_continue();
7589 statement = parse_break();
7593 statement = parse_return();
7597 if(warning.empty_statement) {
7598 warningf(HERE, "statement is empty");
7600 statement = create_empty_statement();
7605 if(look_ahead(1)->type == ':') {
7606 statement = parse_label_statement();
7610 if(is_typedef_symbol(token.v.symbol)) {
7611 statement = parse_declaration_statement();
7615 statement = parse_expression_statement();
7618 case T___extension__:
7619 /* this can be a prefix to a declaration or an expression statement */
7620 /* we simply eat it now and parse the rest with tail recursion */
7623 } while(token.type == T___extension__);
7624 statement = parse_statement();
7628 statement = parse_declaration_statement();
7632 statement = parse_expression_statement();
7635 rem_anchor_token(';');
7637 assert(statement != NULL
7638 && statement->base.source_position.input_name != NULL);
7644 * Parse a compound statement.
7646 static statement_t *parse_compound_statement(void)
7648 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7650 statement->base.source_position = token.source_position;
7653 add_anchor_token('}');
7655 int top = environment_top();
7656 scope_t *last_scope = scope;
7657 set_scope(&statement->compound.scope);
7659 statement_t *last_statement = NULL;
7661 while(token.type != '}' && token.type != T_EOF) {
7662 statement_t *sub_statement = parse_statement();
7663 if(is_invalid_statement(sub_statement)) {
7664 /* an error occurred. if we are at an anchor, return */
7670 if(last_statement != NULL) {
7671 last_statement->base.next = sub_statement;
7673 statement->compound.statements = sub_statement;
7676 while(sub_statement->base.next != NULL)
7677 sub_statement = sub_statement->base.next;
7679 last_statement = sub_statement;
7682 if(token.type == '}') {
7685 errorf(statement->base.source_position,
7686 "end of file while looking for closing '}'");
7690 rem_anchor_token('}');
7691 assert(scope == &statement->compound.scope);
7692 set_scope(last_scope);
7693 environment_pop_to(top);
7699 * Initialize builtin types.
7701 static void initialize_builtin_types(void)
7703 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7704 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7705 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7706 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7707 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7708 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7709 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7710 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7712 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7713 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7714 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7715 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7719 * Check for unused global static functions and variables
7721 static void check_unused_globals(void)
7723 if (!warning.unused_function && !warning.unused_variable)
7726 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7727 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7730 type_t *const type = decl->type;
7732 if (is_type_function(skip_typeref(type))) {
7733 if (!warning.unused_function || decl->is_inline)
7736 s = (decl->init.statement != NULL ? "defined" : "declared");
7738 if (!warning.unused_variable)
7744 warningf(decl->source_position, "'%#T' %s but not used",
7745 type, decl->symbol, s);
7750 * Parse a translation unit.
7752 static translation_unit_t *parse_translation_unit(void)
7754 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7756 assert(global_scope == NULL);
7757 global_scope = &unit->scope;
7759 assert(scope == NULL);
7760 set_scope(&unit->scope);
7762 initialize_builtin_types();
7764 while(token.type != T_EOF) {
7765 if (token.type == ';') {
7766 /* TODO error in strict mode */
7767 warningf(HERE, "stray ';' outside of function");
7770 parse_external_declaration();
7774 assert(scope == &unit->scope);
7776 last_declaration = NULL;
7778 assert(global_scope == &unit->scope);
7779 check_unused_globals();
7780 global_scope = NULL;
7788 * @return the translation unit or NULL if errors occurred.
7790 translation_unit_t *parse(void)
7792 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7793 label_stack = NEW_ARR_F(stack_entry_t, 0);
7794 diagnostic_count = 0;
7798 type_set_output(stderr);
7799 ast_set_output(stderr);
7801 lookahead_bufpos = 0;
7802 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7805 translation_unit_t *unit = parse_translation_unit();
7807 DEL_ARR_F(environment_stack);
7808 DEL_ARR_F(label_stack);
7814 * Initialize the parser.
7816 void init_parser(void)
7819 /* add predefined symbols for extended-decl-modifier */
7820 sym_align = symbol_table_insert("align");
7821 sym_allocate = symbol_table_insert("allocate");
7822 sym_dllimport = symbol_table_insert("dllimport");
7823 sym_dllexport = symbol_table_insert("dllexport");
7824 sym_naked = symbol_table_insert("naked");
7825 sym_noinline = symbol_table_insert("noinline");
7826 sym_noreturn = symbol_table_insert("noreturn");
7827 sym_nothrow = symbol_table_insert("nothrow");
7828 sym_novtable = symbol_table_insert("novtable");
7829 sym_property = symbol_table_insert("property");
7830 sym_get = symbol_table_insert("get");
7831 sym_put = symbol_table_insert("put");
7832 sym_selectany = symbol_table_insert("selectany");
7833 sym_thread = symbol_table_insert("thread");
7834 sym_uuid = symbol_table_insert("uuid");
7835 sym_deprecated = symbol_table_insert("deprecated");
7836 sym_restrict = symbol_table_insert("restrict");
7837 sym_noalias = symbol_table_insert("noalias");
7839 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7841 init_expression_parsers();
7842 obstack_init(&temp_obst);
7844 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7845 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7849 * Terminate the parser.
7851 void exit_parser(void)
7853 obstack_free(&temp_obst, NULL);