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 static source_position_t null_position = { NULL, 0 };
110 /* symbols for Microsoft extended-decl-modifier */
111 static const symbol_t *sym_align = NULL;
112 static const symbol_t *sym_allocate = NULL;
113 static const symbol_t *sym_dllimport = NULL;
114 static const symbol_t *sym_dllexport = NULL;
115 static const symbol_t *sym_naked = NULL;
116 static const symbol_t *sym_noinline = NULL;
117 static const symbol_t *sym_noreturn = NULL;
118 static const symbol_t *sym_nothrow = NULL;
119 static const symbol_t *sym_novtable = NULL;
120 static const symbol_t *sym_property = NULL;
121 static const symbol_t *sym_get = NULL;
122 static const symbol_t *sym_put = NULL;
123 static const symbol_t *sym_selectany = NULL;
124 static const symbol_t *sym_thread = NULL;
125 static const symbol_t *sym_uuid = NULL;
126 static const symbol_t *sym_deprecated = NULL;
127 static const symbol_t *sym_restrict = NULL;
128 static const symbol_t *sym_noalias = NULL;
130 /** The token anchor set */
131 static unsigned char token_anchor_set[T_LAST_TOKEN];
133 /** The current source position. */
134 #define HERE &token.source_position
136 static type_t *type_valist;
138 static statement_t *parse_compound_statement(void);
139 static statement_t *parse_statement(void);
141 static expression_t *parse_sub_expression(unsigned precedence);
142 static expression_t *parse_expression(void);
143 static type_t *parse_typename(void);
145 static void parse_compound_type_entries(declaration_t *compound_declaration);
146 static declaration_t *parse_declarator(
147 const declaration_specifiers_t *specifiers, bool may_be_abstract);
148 static declaration_t *record_declaration(declaration_t *declaration);
150 static void semantic_comparison(binary_expression_t *expression);
152 #define STORAGE_CLASSES \
159 #define TYPE_QUALIFIERS \
166 #ifdef PROVIDE_COMPLEX
167 #define COMPLEX_SPECIFIERS \
169 #define IMAGINARY_SPECIFIERS \
172 #define COMPLEX_SPECIFIERS
173 #define IMAGINARY_SPECIFIERS
176 #define TYPE_SPECIFIERS \
191 case T___builtin_va_list: \
196 #define DECLARATION_START \
201 #define TYPENAME_START \
206 * Allocate an AST node with given size and
207 * initialize all fields with zero.
209 static void *allocate_ast_zero(size_t size)
211 void *res = allocate_ast(size);
212 memset(res, 0, size);
216 static declaration_t *allocate_declaration_zero(void)
218 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
219 declaration->type = type_error_type;
220 declaration->alignment = 0;
225 * Returns the size of a statement node.
227 * @param kind the statement kind
229 static size_t get_statement_struct_size(statement_kind_t kind)
231 static const size_t sizes[] = {
232 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
233 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
234 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
235 [STATEMENT_RETURN] = sizeof(return_statement_t),
236 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
237 [STATEMENT_IF] = sizeof(if_statement_t),
238 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
239 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
240 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
241 [STATEMENT_BREAK] = sizeof(statement_base_t),
242 [STATEMENT_GOTO] = sizeof(goto_statement_t),
243 [STATEMENT_LABEL] = sizeof(label_statement_t),
244 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
245 [STATEMENT_WHILE] = sizeof(while_statement_t),
246 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
247 [STATEMENT_FOR] = sizeof(for_statement_t),
248 [STATEMENT_ASM] = sizeof(asm_statement_t)
250 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
251 assert(sizes[kind] != 0);
256 * Returns the size of an expression node.
258 * @param kind the expression kind
260 static size_t get_expression_struct_size(expression_kind_t kind)
262 static const size_t sizes[] = {
263 [EXPR_INVALID] = sizeof(expression_base_t),
264 [EXPR_REFERENCE] = sizeof(reference_expression_t),
265 [EXPR_CONST] = sizeof(const_expression_t),
266 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
267 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
268 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
269 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
270 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
271 [EXPR_CALL] = sizeof(call_expression_t),
272 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
273 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
274 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
275 [EXPR_SELECT] = sizeof(select_expression_t),
276 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
277 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
278 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
279 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
280 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
281 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
282 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
283 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
284 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
285 [EXPR_VA_START] = sizeof(va_start_expression_t),
286 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
287 [EXPR_STATEMENT] = sizeof(statement_expression_t),
289 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
290 return sizes[EXPR_UNARY_FIRST];
292 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
293 return sizes[EXPR_BINARY_FIRST];
295 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
296 assert(sizes[kind] != 0);
301 * Allocate a statement node of given kind and initialize all
304 static statement_t *allocate_statement_zero(statement_kind_t kind)
306 size_t size = get_statement_struct_size(kind);
307 statement_t *res = allocate_ast_zero(size);
309 res->base.kind = kind;
314 * Allocate an expression node of given kind and initialize all
317 static expression_t *allocate_expression_zero(expression_kind_t kind)
319 size_t size = get_expression_struct_size(kind);
320 expression_t *res = allocate_ast_zero(size);
322 res->base.kind = kind;
323 res->base.type = type_error_type;
328 * Creates a new invalid expression.
330 static expression_t *create_invalid_expression(void)
332 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
333 expression->base.source_position = token.source_position;
338 * Creates a new invalid statement.
340 static statement_t *create_invalid_statement(void)
342 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
343 statement->base.source_position = token.source_position;
348 * Allocate a new empty statement.
350 static statement_t *create_empty_statement(void)
352 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
353 statement->base.source_position = token.source_position;
358 * Returns the size of a type node.
360 * @param kind the type kind
362 static size_t get_type_struct_size(type_kind_t kind)
364 static const size_t sizes[] = {
365 [TYPE_ATOMIC] = sizeof(atomic_type_t),
366 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
367 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
368 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
369 [TYPE_ENUM] = sizeof(enum_type_t),
370 [TYPE_FUNCTION] = sizeof(function_type_t),
371 [TYPE_POINTER] = sizeof(pointer_type_t),
372 [TYPE_ARRAY] = sizeof(array_type_t),
373 [TYPE_BUILTIN] = sizeof(builtin_type_t),
374 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
375 [TYPE_TYPEOF] = sizeof(typeof_type_t),
377 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
378 assert(kind <= TYPE_TYPEOF);
379 assert(sizes[kind] != 0);
384 * Allocate a type node of given kind and initialize all
387 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
389 size_t size = get_type_struct_size(kind);
390 type_t *res = obstack_alloc(type_obst, size);
391 memset(res, 0, size);
393 res->base.kind = kind;
394 res->base.source_position = *source_position;
399 * Returns the size of an initializer node.
401 * @param kind the initializer kind
403 static size_t get_initializer_size(initializer_kind_t kind)
405 static const size_t sizes[] = {
406 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
407 [INITIALIZER_STRING] = sizeof(initializer_string_t),
408 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
409 [INITIALIZER_LIST] = sizeof(initializer_list_t),
410 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
412 assert(kind < sizeof(sizes) / sizeof(*sizes));
413 assert(sizes[kind] != 0);
418 * Allocate an initializer node of given kind and initialize all
421 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
423 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
430 * Free a type from the type obstack.
432 static void free_type(void *type)
434 obstack_free(type_obst, type);
438 * Returns the index of the top element of the environment stack.
440 static size_t environment_top(void)
442 return ARR_LEN(environment_stack);
446 * Returns the index of the top element of the label stack.
448 static size_t label_top(void)
450 return ARR_LEN(label_stack);
454 * Return the next token.
456 static inline void next_token(void)
458 token = lookahead_buffer[lookahead_bufpos];
459 lookahead_buffer[lookahead_bufpos] = lexer_token;
462 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
465 print_token(stderr, &token);
466 fprintf(stderr, "\n");
471 * Return the next token with a given lookahead.
473 static inline const token_t *look_ahead(int num)
475 assert(num > 0 && num <= MAX_LOOKAHEAD);
476 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
477 return &lookahead_buffer[pos];
481 * Adds a token to the token anchor set (a multi-set).
483 static void add_anchor_token(int token_type) {
484 assert(0 <= token_type && token_type < T_LAST_TOKEN);
485 ++token_anchor_set[token_type];
489 * Remove a token from the token anchor set (a multi-set).
491 static void rem_anchor_token(int token_type) {
492 assert(0 <= token_type && token_type < T_LAST_TOKEN);
493 --token_anchor_set[token_type];
496 static bool at_anchor(void) {
499 return token_anchor_set[token.type];
503 * Eat tokens until a matching token is found.
505 static void eat_until_matching_token(int type) {
506 unsigned parenthesis_count = 0;
507 unsigned brace_count = 0;
508 unsigned bracket_count = 0;
509 int end_token = type;
518 while(token.type != end_token ||
519 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
523 case '(': ++parenthesis_count; break;
524 case '{': ++brace_count; break;
525 case '[': ++bracket_count; break;
527 if(parenthesis_count > 0)
535 if(bracket_count > 0)
546 * Eat input tokens until an anchor is found.
548 static void eat_until_anchor(void) {
549 if(token.type == T_EOF)
551 while(token_anchor_set[token.type] == 0) {
552 if(token.type == '(' || token.type == '{' || token.type == '[')
553 eat_until_matching_token(token.type);
554 if(token.type == T_EOF)
560 static void eat_block(void) {
561 eat_until_matching_token('{');
562 if(token.type == '}')
567 * eat all token until a ';' is reached
568 * or a stop token is found.
570 static void eat_statement(void) {
571 eat_until_matching_token(';');
572 if(token.type == ';')
576 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
579 * Report a parse error because an expected token was not found.
581 static void parse_error_expected(const char *message, ...)
583 if(message != NULL) {
584 errorf(HERE, "%s", message);
587 va_start(ap, message);
588 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
593 * Report a type error.
595 static void type_error(const char *msg, const source_position_t *source_position,
598 errorf(source_position, "%s, but found type '%T'", msg, type);
602 * Report an incompatible type.
604 static void type_error_incompatible(const char *msg,
605 const source_position_t *source_position, type_t *type1, type_t *type2)
607 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
611 * Expect the the current token is the expected token.
612 * If not, generate an error, eat the current statement,
613 * and goto the end_error label.
615 #define expect(expected) \
617 if(UNLIKELY(token.type != (expected))) { \
618 parse_error_expected(NULL, (expected), 0); \
619 add_anchor_token(expected); \
620 eat_until_anchor(); \
621 rem_anchor_token(expected); \
627 static void set_scope(scope_t *new_scope)
630 scope->last_declaration = last_declaration;
634 last_declaration = new_scope->last_declaration;
638 * Search a symbol in a given namespace and returns its declaration or
639 * NULL if this symbol was not found.
641 static declaration_t *get_declaration(const symbol_t *const symbol,
642 const namespace_t namespc)
644 declaration_t *declaration = symbol->declaration;
645 for( ; declaration != NULL; declaration = declaration->symbol_next) {
646 if(declaration->namespc == namespc)
654 * pushs an environment_entry on the environment stack and links the
655 * corresponding symbol to the new entry
657 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
659 symbol_t *symbol = declaration->symbol;
660 namespace_t namespc = (namespace_t) declaration->namespc;
662 /* replace/add declaration into declaration list of the symbol */
663 declaration_t *iter = symbol->declaration;
665 symbol->declaration = declaration;
667 declaration_t *iter_last = NULL;
668 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
669 /* replace an entry? */
670 if(iter->namespc == namespc) {
671 if(iter_last == NULL) {
672 symbol->declaration = declaration;
674 iter_last->symbol_next = declaration;
676 declaration->symbol_next = iter->symbol_next;
681 assert(iter_last->symbol_next == NULL);
682 iter_last->symbol_next = declaration;
686 /* remember old declaration */
688 entry.symbol = symbol;
689 entry.old_declaration = iter;
690 entry.namespc = (unsigned short) namespc;
691 ARR_APP1(stack_entry_t, *stack_ptr, entry);
694 static void environment_push(declaration_t *declaration)
696 assert(declaration->source_position.input_name != NULL);
697 assert(declaration->parent_scope != NULL);
698 stack_push(&environment_stack, declaration);
701 static void label_push(declaration_t *declaration)
703 declaration->parent_scope = ¤t_function->scope;
704 stack_push(&label_stack, declaration);
708 * pops symbols from the environment stack until @p new_top is the top element
710 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
712 stack_entry_t *stack = *stack_ptr;
713 size_t top = ARR_LEN(stack);
716 assert(new_top <= top);
720 for(i = top; i > new_top; --i) {
721 stack_entry_t *entry = &stack[i - 1];
723 declaration_t *old_declaration = entry->old_declaration;
724 symbol_t *symbol = entry->symbol;
725 namespace_t namespc = (namespace_t)entry->namespc;
727 /* replace/remove declaration */
728 declaration_t *declaration = symbol->declaration;
729 assert(declaration != NULL);
730 if(declaration->namespc == namespc) {
731 if(old_declaration == NULL) {
732 symbol->declaration = declaration->symbol_next;
734 symbol->declaration = old_declaration;
737 declaration_t *iter_last = declaration;
738 declaration_t *iter = declaration->symbol_next;
739 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
740 /* replace an entry? */
741 if(iter->namespc == namespc) {
742 assert(iter_last != NULL);
743 iter_last->symbol_next = old_declaration;
744 if(old_declaration != NULL) {
745 old_declaration->symbol_next = iter->symbol_next;
750 assert(iter != NULL);
754 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
757 static void environment_pop_to(size_t new_top)
759 stack_pop_to(&environment_stack, new_top);
762 static void label_pop_to(size_t new_top)
764 stack_pop_to(&label_stack, new_top);
768 static int get_rank(const type_t *type)
770 assert(!is_typeref(type));
771 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
772 * and esp. footnote 108). However we can't fold constants (yet), so we
773 * can't decide whether unsigned int is possible, while int always works.
774 * (unsigned int would be preferable when possible... for stuff like
775 * struct { enum { ... } bla : 4; } ) */
776 if(type->kind == TYPE_ENUM)
777 return ATOMIC_TYPE_INT;
779 assert(type->kind == TYPE_ATOMIC);
780 return type->atomic.akind;
783 static type_t *promote_integer(type_t *type)
785 if(type->kind == TYPE_BITFIELD)
786 type = type->bitfield.base;
788 if(get_rank(type) < ATOMIC_TYPE_INT)
795 * Create a cast expression.
797 * @param expression the expression to cast
798 * @param dest_type the destination type
800 static expression_t *create_cast_expression(expression_t *expression,
803 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
805 cast->unary.value = expression;
806 cast->base.type = dest_type;
812 * Check if a given expression represents the 0 pointer constant.
814 static bool is_null_pointer_constant(const expression_t *expression)
816 /* skip void* cast */
817 if(expression->kind == EXPR_UNARY_CAST
818 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
819 expression = expression->unary.value;
822 /* TODO: not correct yet, should be any constant integer expression
823 * which evaluates to 0 */
824 if (expression->kind != EXPR_CONST)
827 type_t *const type = skip_typeref(expression->base.type);
828 if (!is_type_integer(type))
831 return expression->conste.v.int_value == 0;
835 * Create an implicit cast expression.
837 * @param expression the expression to cast
838 * @param dest_type the destination type
840 static expression_t *create_implicit_cast(expression_t *expression,
843 type_t *const source_type = expression->base.type;
845 if (source_type == dest_type)
848 return create_cast_expression(expression, dest_type);
851 /** Implements the rules from § 6.5.16.1 */
852 static type_t *semantic_assign(type_t *orig_type_left,
853 const expression_t *const right,
855 const source_position_t *source_position)
857 type_t *const orig_type_right = right->base.type;
858 type_t *const type_left = skip_typeref(orig_type_left);
859 type_t *const type_right = skip_typeref(orig_type_right);
861 if(is_type_pointer(type_left)) {
862 if(is_null_pointer_constant(right)) {
863 return orig_type_left;
864 } else if(is_type_pointer(type_right)) {
865 type_t *points_to_left
866 = skip_typeref(type_left->pointer.points_to);
867 type_t *points_to_right
868 = skip_typeref(type_right->pointer.points_to);
870 /* the left type has all qualifiers from the right type */
871 unsigned missing_qualifiers
872 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
873 if(missing_qualifiers != 0) {
874 errorf(source_position,
875 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
876 return orig_type_left;
879 points_to_left = get_unqualified_type(points_to_left);
880 points_to_right = get_unqualified_type(points_to_right);
882 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
883 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
884 return orig_type_left;
887 if (!types_compatible(points_to_left, points_to_right)) {
888 warningf(source_position,
889 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
890 orig_type_left, context, right, orig_type_right);
893 return orig_type_left;
894 } else if(is_type_integer(type_right)) {
895 warningf(source_position,
896 "%s makes pointer '%T' from integer '%T' without a cast",
897 context, orig_type_left, orig_type_right);
898 return orig_type_left;
900 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
901 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
902 && is_type_pointer(type_right))) {
903 return orig_type_left;
904 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
905 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
906 type_t *const unqual_type_left = get_unqualified_type(type_left);
907 type_t *const unqual_type_right = get_unqualified_type(type_right);
908 if (types_compatible(unqual_type_left, unqual_type_right)) {
909 return orig_type_left;
911 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
912 warningf(source_position,
913 "%s makes integer '%T' from pointer '%T' without a cast",
914 context, orig_type_left, orig_type_right);
915 return orig_type_left;
918 if (!is_type_valid(type_left))
921 if (!is_type_valid(type_right))
922 return orig_type_right;
927 static expression_t *parse_constant_expression(void)
929 /* start parsing at precedence 7 (conditional expression) */
930 expression_t *result = parse_sub_expression(7);
932 if(!is_constant_expression(result)) {
933 errorf(&result->base.source_position, "expression '%E' is not constant\n", result);
939 static expression_t *parse_assignment_expression(void)
941 /* start parsing at precedence 2 (assignment expression) */
942 return parse_sub_expression(2);
945 static type_t *make_global_typedef(const char *name, type_t *type)
947 symbol_t *const symbol = symbol_table_insert(name);
949 declaration_t *const declaration = allocate_declaration_zero();
950 declaration->namespc = NAMESPACE_NORMAL;
951 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
952 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
953 declaration->type = type;
954 declaration->symbol = symbol;
955 declaration->source_position = builtin_source_position;
957 record_declaration(declaration);
959 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
960 typedef_type->typedeft.declaration = declaration;
965 static string_t parse_string_literals(void)
967 assert(token.type == T_STRING_LITERAL);
968 string_t result = token.v.string;
972 while (token.type == T_STRING_LITERAL) {
973 result = concat_strings(&result, &token.v.string);
980 static const char *gnu_attribute_names[GNU_AK_LAST] = {
981 [GNU_AK_CONST] = "const",
982 [GNU_AK_VOLATILE] = "volatile",
983 [GNU_AK_CDECL] = "cdecl",
984 [GNU_AK_STDCALL] = "stdcall",
985 [GNU_AK_FASTCALL] = "fastcall",
986 [GNU_AK_DEPRECATED] = "deprecated",
987 [GNU_AK_NOINLINE] = "noinline",
988 [GNU_AK_NORETURN] = "noreturn",
989 [GNU_AK_NAKED] = "naked",
990 [GNU_AK_PURE] = "pure",
991 [GNU_AK_ALWAYS_INLINE] = "always_inline",
992 [GNU_AK_MALLOC] = "malloc",
993 [GNU_AK_WEAK] = "weak",
994 [GNU_AK_CONSTRUCTOR] = "constructor",
995 [GNU_AK_DESTRUCTOR] = "destructor",
996 [GNU_AK_NOTHROW] = "nothrow",
997 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
998 [GNU_AK_COMMON] = "coommon",
999 [GNU_AK_NOCOMMON] = "nocommon",
1000 [GNU_AK_PACKED] = "packed",
1001 [GNU_AK_SHARED] = "shared",
1002 [GNU_AK_NOTSHARED] = "notshared",
1003 [GNU_AK_USED] = "used",
1004 [GNU_AK_UNUSED] = "unused",
1005 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1006 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1007 [GNU_AK_LONGCALL] = "longcall",
1008 [GNU_AK_SHORTCALL] = "shortcall",
1009 [GNU_AK_LONG_CALL] = "long_call",
1010 [GNU_AK_SHORT_CALL] = "short_call",
1011 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1012 [GNU_AK_INTERRUPT] = "interrupt",
1013 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1014 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1015 [GNU_AK_NESTING] = "nesting",
1016 [GNU_AK_NEAR] = "near",
1017 [GNU_AK_FAR] = "far",
1018 [GNU_AK_SIGNAL] = "signal",
1019 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1020 [GNU_AK_TINY_DATA] = "tiny_data",
1021 [GNU_AK_SAVEALL] = "saveall",
1022 [GNU_AK_FLATTEN] = "flatten",
1023 [GNU_AK_SSEREGPARM] = "sseregparm",
1024 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1025 [GNU_AK_RETURN_TWICE] = "return_twice",
1026 [GNU_AK_MAY_ALIAS] = "may_alias",
1027 [GNU_AK_MS_STRUCT] = "ms_struct",
1028 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1029 [GNU_AK_ALIGNED] = "aligned",
1030 [GNU_AK_ALIAS] = "alias",
1031 [GNU_AK_SECTION] = "section",
1032 [GNU_AK_FORMAT] = "format",
1033 [GNU_AK_FORMAT_ARG] = "format_arg",
1034 [GNU_AK_WEAKREF] = "weakref",
1035 [GNU_AK_NONNULL] = "nonnull",
1036 [GNU_AK_TLS_MODEL] = "tls_model",
1037 [GNU_AK_VISIBILITY] = "visibility",
1038 [GNU_AK_REGPARM] = "regparm",
1039 [GNU_AK_MODEL] = "model",
1040 [GNU_AK_TRAP_EXIT] = "trap_exit",
1041 [GNU_AK_SP_SWITCH] = "sp_switch",
1042 [GNU_AK_SENTINEL] = "sentinel"
1046 * compare two string, ignoring double underscores on the second.
1048 static int strcmp_underscore(const char *s1, const char *s2) {
1049 if(s2[0] == '_' && s2[1] == '_') {
1051 size_t l1 = strlen(s1);
1052 if(l1 + 2 != strlen(s2)) {
1056 return strncmp(s1, s2, l1);
1058 return strcmp(s1, s2);
1062 * Allocate a new gnu temporal attribute.
1064 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1065 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1066 attribute->kind = kind;
1067 attribute->next = NULL;
1068 attribute->invalid = false;
1069 attribute->have_arguments = false;
1073 * parse one constant expression argument.
1075 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1076 expression_t *expression;
1077 add_anchor_token(')');
1078 expression = parse_constant_expression();
1079 rem_anchor_token(')');
1084 attribute->invalid = true;
1088 * parse a list of constant expressions arguments.
1090 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1091 expression_t *expression;
1092 add_anchor_token(')');
1093 add_anchor_token(',');
1095 expression = parse_constant_expression();
1096 if(token.type != ',')
1100 rem_anchor_token(',');
1101 rem_anchor_token(')');
1106 attribute->invalid = true;
1110 * parse one string literal argument.
1112 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute, string_t *string) {
1113 add_anchor_token('(');
1114 if(token.type != T_STRING_LITERAL) {
1115 parse_error_expected("while parsing attribute directive", T_STRING_LITERAL);
1118 *string = parse_string_literals();
1119 rem_anchor_token('(');
1123 attribute->invalid = true;
1127 * parse one tls model.
1129 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1130 static const char *tls_models[] = {
1136 string_t string = { NULL, 0 };
1137 parse_gnu_attribute_string_arg(attribute, &string);
1138 if(string.begin != NULL) {
1139 for(size_t i = 0; i < 4; ++i) {
1140 if(strcmp(tls_models[i], string.begin) == 0) {
1141 attribute->u.value = i;
1146 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1147 attribute->invalid = true;
1151 * parse one tls model.
1153 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1154 static const char *visibilities[] = {
1160 string_t string = { NULL, 0 };
1161 parse_gnu_attribute_string_arg(attribute, &string);
1162 if(string.begin != NULL) {
1163 for(size_t i = 0; i < 4; ++i) {
1164 if(strcmp(visibilities[i], string.begin) == 0) {
1165 attribute->u.value = i;
1170 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1171 attribute->invalid = true;
1175 * parse one (code) model.
1177 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1178 static const char *visibilities[] = {
1183 string_t string = { NULL, 0 };
1184 parse_gnu_attribute_string_arg(attribute, &string);
1185 if(string.begin != NULL) {
1186 for(int i = 0; i < 3; ++i) {
1187 if(strcmp(visibilities[i], string.begin) == 0) {
1188 attribute->u.value = i;
1193 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1194 attribute->invalid = true;
1198 * parse one interrupt argument.
1200 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1201 static const char *interrupts[] = {
1208 string_t string = { NULL, 0 };
1209 parse_gnu_attribute_string_arg(attribute, &string);
1210 if(string.begin != NULL) {
1211 for(size_t i = 0; i < 5; ++i) {
1212 if(strcmp(interrupts[i], string.begin) == 0) {
1213 attribute->u.value = i;
1218 errorf(HERE, "'%s' is an interrupt", string.begin);
1219 attribute->invalid = true;
1223 * parse ( identifier, const expression, const expression )
1225 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1226 static const char *format_names[] = {
1234 if(token.type != T_IDENTIFIER) {
1235 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER);
1238 const char *name = token.v.symbol->string;
1239 for(i = 0; i < 4; ++i) {
1240 if(strcmp_underscore(format_names[i], name) == 0)
1244 if(warning.attribute)
1245 warningf(HERE, "'%s' is an unrecognized format function type", name);
1250 add_anchor_token(')');
1251 add_anchor_token(',');
1252 parse_constant_expression();
1253 rem_anchor_token(',');
1254 rem_anchor_token('(');
1257 add_anchor_token(')');
1258 parse_constant_expression();
1259 rem_anchor_token('(');
1263 attribute->u.value = true;
1267 * Parse one GNU attribute.
1269 * Note that attribute names can be specified WITH or WITHOUT
1270 * double underscores, ie const or __const__.
1272 * The following attributes are parsed without arguments
1297 * no_instrument_function
1298 * warn_unused_result
1315 * externally_visible
1321 * The following attributes are parsed with arguments
1322 * aligned( const expression )
1323 * alias( string literal )
1324 * section( string literal )
1325 * format( identifier, const expression, const expression )
1326 * format_arg( const expression )
1327 * tls_model( string literal )
1328 * visibility( string literal )
1329 * regparm( const expression )
1330 * model( string leteral )
1331 * trap_exit( const expression )
1332 * sp_switch( string literal )
1334 * The following attributes might have arguments
1335 * weak_ref( string literal )
1336 * non_null( const expression // ',' )
1337 * interrupt( string literal )
1338 * sentinel( constant expression )
1340 static void parse_gnu_attribute(gnu_attribute_t **attributes)
1342 gnu_attribute_t *head = *attributes;
1343 gnu_attribute_t *last = *attributes;
1344 gnu_attribute_t *attribute;
1346 eat(T___attribute__);
1350 if(token.type != ')') {
1351 /* find the end of the list */
1353 while(last->next != NULL)
1357 /* non-empty attribute list */
1360 if(token.type == T_const) {
1362 } else if(token.type == T_volatile) {
1364 } else if(token.type == T_cdecl) {
1365 /* __attribute__((cdecl)), WITH ms mode */
1367 } else if(token.type != T_IDENTIFIER) {
1368 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1371 const symbol_t *sym = token.v.symbol;
1376 for(i = 0; i < GNU_AK_LAST; ++i) {
1377 if(strcmp_underscore(gnu_attribute_names[i], name) == 0)
1380 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1383 if(kind == GNU_AK_LAST) {
1384 if(warning.attribute)
1385 warningf(HERE, "'%s' attribute directive ignored", name);
1387 /* skip possible arguments */
1388 if(token.type == '(') {
1389 eat_until_matching_token(')');
1392 /* check for arguments */
1393 attribute = allocate_gnu_attribute(kind);
1394 if(token.type == '(') {
1396 if(token.type == ')') {
1397 /* empty args are allowed */
1400 attribute->have_arguments = true;
1405 case GNU_AK_VOLATILE:
1407 case GNU_AK_STDCALL:
1408 case GNU_AK_FASTCALL:
1409 case GNU_AK_DEPRECATED:
1410 case GNU_AK_NOINLINE:
1411 case GNU_AK_NORETURN:
1414 case GNU_AK_ALWAYS_INLINE:
1417 case GNU_AK_CONSTRUCTOR:
1418 case GNU_AK_DESTRUCTOR:
1419 case GNU_AK_NOTHROW:
1420 case GNU_AK_TRANSPARENT_UNION:
1422 case GNU_AK_NOCOMMON:
1425 case GNU_AK_NOTSHARED:
1428 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1429 case GNU_AK_WARN_UNUSED_RESULT:
1430 case GNU_AK_LONGCALL:
1431 case GNU_AK_SHORTCALL:
1432 case GNU_AK_LONG_CALL:
1433 case GNU_AK_SHORT_CALL:
1434 case GNU_AK_FUNCTION_VECTOR:
1435 case GNU_AK_INTERRUPT_HANDLER:
1436 case GNU_AK_NMI_HANDLER:
1437 case GNU_AK_NESTING:
1441 case GNU_AK_EIGTHBIT_DATA:
1442 case GNU_AK_TINY_DATA:
1443 case GNU_AK_SAVEALL:
1444 case GNU_AK_FLATTEN:
1445 case GNU_AK_SSEREGPARM:
1446 case GNU_AK_EXTERNALLY_VISIBLE:
1447 case GNU_AK_RETURN_TWICE:
1448 case GNU_AK_MAY_ALIAS:
1449 case GNU_AK_MS_STRUCT:
1450 case GNU_AK_GCC_STRUCT:
1451 if(attribute->have_arguments) {
1452 /* should have no arguments */
1453 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1454 eat_until_matching_token('(');
1455 /* we have already consumed '(', so we stop before ')', eat it */
1457 attribute->invalid = true;
1461 case GNU_AK_ALIGNED:
1462 case GNU_AK_FORMAT_ARG:
1463 case GNU_AK_REGPARM:
1464 case GNU_AK_TRAP_EXIT:
1465 if(!attribute->have_arguments) {
1466 /* should have arguments */
1467 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1468 attribute->invalid = true;
1470 parse_gnu_attribute_const_arg(attribute);
1473 case GNU_AK_SECTION:
1474 case GNU_AK_SP_SWITCH:
1475 if(!attribute->have_arguments) {
1476 /* should have arguments */
1477 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1478 attribute->invalid = true;
1480 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1483 if(!attribute->have_arguments) {
1484 /* should have arguments */
1485 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1486 attribute->invalid = true;
1488 parse_gnu_attribute_format_args(attribute);
1490 case GNU_AK_WEAKREF:
1491 /* may have one string argument */
1492 if(attribute->have_arguments)
1493 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1495 case GNU_AK_NONNULL:
1496 if(attribute->have_arguments)
1497 parse_gnu_attribute_const_arg_list(attribute);
1499 case GNU_AK_TLS_MODEL:
1500 if(!attribute->have_arguments) {
1501 /* should have arguments */
1502 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1504 parse_gnu_attribute_tls_model_arg(attribute);
1506 case GNU_AK_VISIBILITY:
1507 if(!attribute->have_arguments) {
1508 /* should have arguments */
1509 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1511 parse_gnu_attribute_visibility_arg(attribute);
1514 if(!attribute->have_arguments) {
1515 /* should have arguments */
1516 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1518 parse_gnu_attribute_model_arg(attribute);
1519 case GNU_AK_INTERRUPT:
1520 /* may have one string argument */
1521 if(attribute->have_arguments)
1522 parse_gnu_attribute_interrupt_arg(attribute);
1524 case GNU_AK_SENTINEL:
1525 /* may have one string argument */
1526 if(attribute->have_arguments)
1527 parse_gnu_attribute_const_arg(attribute);
1530 /* already handled */
1534 if(attribute != NULL) {
1536 last->next = attribute;
1539 head = last = attribute;
1543 if(token.type != ',')
1555 * Parse GNU attributes.
1557 static void parse_attributes(gnu_attribute_t **attributes)
1560 switch(token.type) {
1561 case T___attribute__: {
1562 parse_gnu_attribute(attributes);
1568 if(token.type != T_STRING_LITERAL) {
1569 parse_error_expected("while parsing assembler attribute",
1571 eat_until_matching_token('(');
1574 parse_string_literals();
1579 goto attributes_finished;
1583 attributes_finished:
1588 static designator_t *parse_designation(void)
1590 designator_t *result = NULL;
1591 designator_t *last = NULL;
1594 designator_t *designator;
1595 switch(token.type) {
1597 designator = allocate_ast_zero(sizeof(designator[0]));
1598 designator->source_position = token.source_position;
1600 add_anchor_token(']');
1601 designator->array_index = parse_constant_expression();
1602 rem_anchor_token(']');
1606 designator = allocate_ast_zero(sizeof(designator[0]));
1607 designator->source_position = token.source_position;
1609 if(token.type != T_IDENTIFIER) {
1610 parse_error_expected("while parsing designator",
1614 designator->symbol = token.v.symbol;
1622 assert(designator != NULL);
1624 last->next = designator;
1626 result = designator;
1634 static initializer_t *initializer_from_string(array_type_t *type,
1635 const string_t *const string)
1637 /* TODO: check len vs. size of array type */
1640 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1641 initializer->string.string = *string;
1646 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1647 wide_string_t *const string)
1649 /* TODO: check len vs. size of array type */
1652 initializer_t *const initializer =
1653 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1654 initializer->wide_string.string = *string;
1660 * Build an initializer from a given expression.
1662 static initializer_t *initializer_from_expression(type_t *orig_type,
1663 expression_t *expression)
1665 /* TODO check that expression is a constant expression */
1667 /* § 6.7.8.14/15 char array may be initialized by string literals */
1668 type_t *type = skip_typeref(orig_type);
1669 type_t *expr_type_orig = expression->base.type;
1670 type_t *expr_type = skip_typeref(expr_type_orig);
1671 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1672 array_type_t *const array_type = &type->array;
1673 type_t *const element_type = skip_typeref(array_type->element_type);
1675 if (element_type->kind == TYPE_ATOMIC) {
1676 atomic_type_kind_t akind = element_type->atomic.akind;
1677 switch (expression->kind) {
1678 case EXPR_STRING_LITERAL:
1679 if (akind == ATOMIC_TYPE_CHAR
1680 || akind == ATOMIC_TYPE_SCHAR
1681 || akind == ATOMIC_TYPE_UCHAR) {
1682 return initializer_from_string(array_type,
1683 &expression->string.value);
1686 case EXPR_WIDE_STRING_LITERAL: {
1687 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1688 if (get_unqualified_type(element_type) == bare_wchar_type) {
1689 return initializer_from_wide_string(array_type,
1690 &expression->wide_string.value);
1700 type_t *const res_type = semantic_assign(type, expression, "initializer",
1701 &expression->base.source_position);
1702 if (res_type == NULL)
1705 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1706 result->value.value = create_implicit_cast(expression, res_type);
1712 * Checks if a given expression can be used as an constant initializer.
1714 static bool is_initializer_constant(const expression_t *expression)
1716 return is_constant_expression(expression)
1717 || is_address_constant(expression);
1721 * Parses an scalar initializer.
1723 * § 6.7.8.11; eat {} without warning
1725 static initializer_t *parse_scalar_initializer(type_t *type,
1726 bool must_be_constant)
1728 /* there might be extra {} hierarchies */
1730 while(token.type == '{') {
1733 warningf(HERE, "extra curly braces around scalar initializer");
1738 expression_t *expression = parse_assignment_expression();
1739 if(must_be_constant && !is_initializer_constant(expression)) {
1740 errorf(&expression->base.source_position,
1741 "Initialisation expression '%E' is not constant\n",
1745 initializer_t *initializer = initializer_from_expression(type, expression);
1747 if(initializer == NULL) {
1748 errorf(&expression->base.source_position,
1749 "expression '%E' (type '%T') doesn't match expected type '%T'",
1750 expression, expression->base.type, type);
1755 bool additional_warning_displayed = false;
1757 if(token.type == ',') {
1760 if(token.type != '}') {
1761 if(!additional_warning_displayed) {
1762 warningf(HERE, "additional elements in scalar initializer");
1763 additional_warning_displayed = true;
1774 * An entry in the type path.
1776 typedef struct type_path_entry_t type_path_entry_t;
1777 struct type_path_entry_t {
1778 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1780 size_t index; /**< For array types: the current index. */
1781 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1786 * A type path expression a position inside compound or array types.
1788 typedef struct type_path_t type_path_t;
1789 struct type_path_t {
1790 type_path_entry_t *path; /**< An flexible array containing the current path. */
1791 type_t *top_type; /**< type of the element the path points */
1792 size_t max_index; /**< largest index in outermost array */
1796 * Prints a type path for debugging.
1798 static __attribute__((unused)) void debug_print_type_path(
1799 const type_path_t *path)
1801 size_t len = ARR_LEN(path->path);
1803 for(size_t i = 0; i < len; ++i) {
1804 const type_path_entry_t *entry = & path->path[i];
1806 type_t *type = skip_typeref(entry->type);
1807 if(is_type_compound(type)) {
1808 /* in gcc mode structs can have no members */
1809 if(entry->v.compound_entry == NULL) {
1813 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1814 } else if(is_type_array(type)) {
1815 fprintf(stderr, "[%zd]", entry->v.index);
1817 fprintf(stderr, "-INVALID-");
1820 if(path->top_type != NULL) {
1821 fprintf(stderr, " (");
1822 print_type(path->top_type);
1823 fprintf(stderr, ")");
1828 * Return the top type path entry, ie. in a path
1829 * (type).a.b returns the b.
1831 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1833 size_t len = ARR_LEN(path->path);
1835 return &path->path[len-1];
1839 * Enlarge the type path by an (empty) element.
1841 static type_path_entry_t *append_to_type_path(type_path_t *path)
1843 size_t len = ARR_LEN(path->path);
1844 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1846 type_path_entry_t *result = & path->path[len];
1847 memset(result, 0, sizeof(result[0]));
1852 * Descending into a sub-type. Enter the scope of the current
1855 static void descend_into_subtype(type_path_t *path)
1857 type_t *orig_top_type = path->top_type;
1858 type_t *top_type = skip_typeref(orig_top_type);
1860 assert(is_type_compound(top_type) || is_type_array(top_type));
1862 type_path_entry_t *top = append_to_type_path(path);
1863 top->type = top_type;
1865 if(is_type_compound(top_type)) {
1866 declaration_t *declaration = top_type->compound.declaration;
1867 declaration_t *entry = declaration->scope.declarations;
1868 top->v.compound_entry = entry;
1871 path->top_type = entry->type;
1873 path->top_type = NULL;
1876 assert(is_type_array(top_type));
1879 path->top_type = top_type->array.element_type;
1884 * Pop an entry from the given type path, ie. returning from
1885 * (type).a.b to (type).a
1887 static void ascend_from_subtype(type_path_t *path)
1889 type_path_entry_t *top = get_type_path_top(path);
1891 path->top_type = top->type;
1893 size_t len = ARR_LEN(path->path);
1894 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1898 * Pop entries from the given type path until the given
1899 * path level is reached.
1901 static void ascend_to(type_path_t *path, size_t top_path_level)
1903 size_t len = ARR_LEN(path->path);
1905 while(len > top_path_level) {
1906 ascend_from_subtype(path);
1907 len = ARR_LEN(path->path);
1911 static bool walk_designator(type_path_t *path, const designator_t *designator,
1912 bool used_in_offsetof)
1914 for( ; designator != NULL; designator = designator->next) {
1915 type_path_entry_t *top = get_type_path_top(path);
1916 type_t *orig_type = top->type;
1918 type_t *type = skip_typeref(orig_type);
1920 if(designator->symbol != NULL) {
1921 symbol_t *symbol = designator->symbol;
1922 if(!is_type_compound(type)) {
1923 if(is_type_valid(type)) {
1924 errorf(&designator->source_position,
1925 "'.%Y' designator used for non-compound type '%T'",
1931 declaration_t *declaration = type->compound.declaration;
1932 declaration_t *iter = declaration->scope.declarations;
1933 for( ; iter != NULL; iter = iter->next) {
1934 if(iter->symbol == symbol) {
1939 errorf(&designator->source_position,
1940 "'%T' has no member named '%Y'", orig_type, symbol);
1943 if(used_in_offsetof) {
1944 type_t *real_type = skip_typeref(iter->type);
1945 if(real_type->kind == TYPE_BITFIELD) {
1946 errorf(&designator->source_position,
1947 "offsetof designator '%Y' may not specify bitfield",
1953 top->type = orig_type;
1954 top->v.compound_entry = iter;
1955 orig_type = iter->type;
1957 expression_t *array_index = designator->array_index;
1958 assert(designator->array_index != NULL);
1960 if(!is_type_array(type)) {
1961 if(is_type_valid(type)) {
1962 errorf(&designator->source_position,
1963 "[%E] designator used for non-array type '%T'",
1964 array_index, orig_type);
1968 if(!is_type_valid(array_index->base.type)) {
1972 long index = fold_constant(array_index);
1973 if(!used_in_offsetof) {
1975 errorf(&designator->source_position,
1976 "array index [%E] must be positive", array_index);
1979 if(type->array.size_constant == true) {
1980 long array_size = type->array.size;
1981 if(index >= array_size) {
1982 errorf(&designator->source_position,
1983 "designator [%E] (%d) exceeds array size %d",
1984 array_index, index, array_size);
1990 top->type = orig_type;
1991 top->v.index = (size_t) index;
1992 orig_type = type->array.element_type;
1994 path->top_type = orig_type;
1996 if(designator->next != NULL) {
1997 descend_into_subtype(path);
2006 static void advance_current_object(type_path_t *path, size_t top_path_level)
2008 type_path_entry_t *top = get_type_path_top(path);
2010 type_t *type = skip_typeref(top->type);
2011 if(is_type_union(type)) {
2012 /* in unions only the first element is initialized */
2013 top->v.compound_entry = NULL;
2014 } else if(is_type_struct(type)) {
2015 declaration_t *entry = top->v.compound_entry;
2017 entry = entry->next;
2018 top->v.compound_entry = entry;
2020 path->top_type = entry->type;
2024 assert(is_type_array(type));
2028 if(!type->array.size_constant || top->v.index < type->array.size) {
2033 /* we're past the last member of the current sub-aggregate, try if we
2034 * can ascend in the type hierarchy and continue with another subobject */
2035 size_t len = ARR_LEN(path->path);
2037 if(len > top_path_level) {
2038 ascend_from_subtype(path);
2039 advance_current_object(path, top_path_level);
2041 path->top_type = NULL;
2046 * skip until token is found.
2048 static void skip_until(int type) {
2049 while(token.type != type) {
2050 if(token.type == T_EOF)
2057 * skip any {...} blocks until a closing braket is reached.
2059 static void skip_initializers(void)
2061 if(token.type == '{')
2064 while(token.type != '}') {
2065 if(token.type == T_EOF)
2067 if(token.type == '{') {
2075 static initializer_t *create_empty_initializer(void)
2077 static initializer_t empty_initializer
2078 = { .list = { { INITIALIZER_LIST }, 0 } };
2079 return &empty_initializer;
2083 * Parse a part of an initialiser for a struct or union,
2085 static initializer_t *parse_sub_initializer(type_path_t *path,
2086 type_t *outer_type, size_t top_path_level,
2087 parse_initializer_env_t *env)
2089 if(token.type == '}') {
2090 /* empty initializer */
2091 return create_empty_initializer();
2094 type_t *orig_type = path->top_type;
2095 type_t *type = NULL;
2097 if (orig_type == NULL) {
2098 /* We are initializing an empty compound. */
2100 type = skip_typeref(orig_type);
2102 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2103 * initializers in this case. */
2104 if(!is_type_valid(type)) {
2105 skip_initializers();
2106 return create_empty_initializer();
2110 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2113 designator_t *designator = NULL;
2114 if(token.type == '.' || token.type == '[') {
2115 designator = parse_designation();
2117 /* reset path to toplevel, evaluate designator from there */
2118 ascend_to(path, top_path_level);
2119 if(!walk_designator(path, designator, false)) {
2120 /* can't continue after designation error */
2124 initializer_t *designator_initializer
2125 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2126 designator_initializer->designator.designator = designator;
2127 ARR_APP1(initializer_t*, initializers, designator_initializer);
2132 if(token.type == '{') {
2133 if(type != NULL && is_type_scalar(type)) {
2134 sub = parse_scalar_initializer(type, env->must_be_constant);
2138 if (env->declaration != NULL)
2139 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2140 env->declaration->symbol);
2142 errorf(HERE, "extra brace group at end of initializer");
2144 descend_into_subtype(path);
2146 add_anchor_token('}');
2147 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2149 rem_anchor_token('}');
2152 ascend_from_subtype(path);
2156 goto error_parse_next;
2160 /* must be an expression */
2161 expression_t *expression = parse_assignment_expression();
2163 if(env->must_be_constant && !is_initializer_constant(expression)) {
2164 errorf(&expression->base.source_position,
2165 "Initialisation expression '%E' is not constant\n",
2170 /* we are already outside, ... */
2174 /* handle { "string" } special case */
2175 if((expression->kind == EXPR_STRING_LITERAL
2176 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2177 && outer_type != NULL) {
2178 sub = initializer_from_expression(outer_type, expression);
2180 if(token.type == ',') {
2183 if(token.type != '}') {
2184 warningf(HERE, "excessive elements in initializer for type '%T'",
2187 /* TODO: eat , ... */
2192 /* descend into subtypes until expression matches type */
2194 orig_type = path->top_type;
2195 type = skip_typeref(orig_type);
2197 sub = initializer_from_expression(orig_type, expression);
2201 if(!is_type_valid(type)) {
2204 if(is_type_scalar(type)) {
2205 errorf(&expression->base.source_position,
2206 "expression '%E' doesn't match expected type '%T'",
2207 expression, orig_type);
2211 descend_into_subtype(path);
2215 /* update largest index of top array */
2216 const type_path_entry_t *first = &path->path[0];
2217 type_t *first_type = first->type;
2218 first_type = skip_typeref(first_type);
2219 if(is_type_array(first_type)) {
2220 size_t index = first->v.index;
2221 if(index > path->max_index)
2222 path->max_index = index;
2226 /* append to initializers list */
2227 ARR_APP1(initializer_t*, initializers, sub);
2230 if(env->declaration != NULL)
2231 warningf(HERE, "excess elements in struct initializer for '%Y'",
2232 env->declaration->symbol);
2234 warningf(HERE, "excess elements in struct initializer");
2238 if(token.type == '}') {
2242 if(token.type == '}') {
2247 /* advance to the next declaration if we are not at the end */
2248 advance_current_object(path, top_path_level);
2249 orig_type = path->top_type;
2250 if(orig_type != NULL)
2251 type = skip_typeref(orig_type);
2257 size_t len = ARR_LEN(initializers);
2258 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2259 initializer_t *result = allocate_ast_zero(size);
2260 result->kind = INITIALIZER_LIST;
2261 result->list.len = len;
2262 memcpy(&result->list.initializers, initializers,
2263 len * sizeof(initializers[0]));
2265 DEL_ARR_F(initializers);
2266 ascend_to(path, top_path_level);
2271 skip_initializers();
2272 DEL_ARR_F(initializers);
2273 ascend_to(path, top_path_level);
2278 * Parses an initializer. Parsers either a compound literal
2279 * (env->declaration == NULL) or an initializer of a declaration.
2281 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2283 type_t *type = skip_typeref(env->type);
2284 initializer_t *result = NULL;
2287 if(is_type_scalar(type)) {
2288 result = parse_scalar_initializer(type, env->must_be_constant);
2289 } else if(token.type == '{') {
2293 memset(&path, 0, sizeof(path));
2294 path.top_type = env->type;
2295 path.path = NEW_ARR_F(type_path_entry_t, 0);
2297 descend_into_subtype(&path);
2299 add_anchor_token('}');
2300 result = parse_sub_initializer(&path, env->type, 1, env);
2301 rem_anchor_token('}');
2303 max_index = path.max_index;
2304 DEL_ARR_F(path.path);
2308 /* parse_scalar_initializer() also works in this case: we simply
2309 * have an expression without {} around it */
2310 result = parse_scalar_initializer(type, env->must_be_constant);
2313 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2314 * the array type size */
2315 if(is_type_array(type) && type->array.size_expression == NULL
2316 && result != NULL) {
2318 switch (result->kind) {
2319 case INITIALIZER_LIST:
2320 size = max_index + 1;
2323 case INITIALIZER_STRING:
2324 size = result->string.string.size;
2327 case INITIALIZER_WIDE_STRING:
2328 size = result->wide_string.string.size;
2332 internal_errorf(HERE, "invalid initializer type");
2335 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2336 cnst->base.type = type_size_t;
2337 cnst->conste.v.int_value = size;
2339 type_t *new_type = duplicate_type(type);
2341 new_type->array.size_expression = cnst;
2342 new_type->array.size_constant = true;
2343 new_type->array.size = size;
2344 env->type = new_type;
2352 static declaration_t *append_declaration(declaration_t *declaration);
2354 static declaration_t *parse_compound_type_specifier(bool is_struct)
2356 gnu_attribute_t *attributes = NULL;
2363 symbol_t *symbol = NULL;
2364 declaration_t *declaration = NULL;
2366 if (token.type == T___attribute__) {
2367 parse_attributes(&attributes);
2370 if(token.type == T_IDENTIFIER) {
2371 symbol = token.v.symbol;
2375 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2377 declaration = get_declaration(symbol, NAMESPACE_UNION);
2379 } else if(token.type != '{') {
2381 parse_error_expected("while parsing struct type specifier",
2382 T_IDENTIFIER, '{', 0);
2384 parse_error_expected("while parsing union type specifier",
2385 T_IDENTIFIER, '{', 0);
2391 if(declaration == NULL) {
2392 declaration = allocate_declaration_zero();
2393 declaration->namespc =
2394 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2395 declaration->source_position = token.source_position;
2396 declaration->symbol = symbol;
2397 declaration->parent_scope = scope;
2398 if (symbol != NULL) {
2399 environment_push(declaration);
2401 append_declaration(declaration);
2404 if(token.type == '{') {
2405 if(declaration->init.is_defined) {
2406 assert(symbol != NULL);
2407 errorf(HERE, "multiple definitions of '%s %Y'",
2408 is_struct ? "struct" : "union", symbol);
2409 declaration->scope.declarations = NULL;
2411 declaration->init.is_defined = true;
2413 parse_compound_type_entries(declaration);
2414 parse_attributes(&attributes);
2420 static void parse_enum_entries(type_t *const enum_type)
2424 if(token.type == '}') {
2426 errorf(HERE, "empty enum not allowed");
2430 add_anchor_token('}');
2432 if(token.type != T_IDENTIFIER) {
2433 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2435 rem_anchor_token('}');
2439 declaration_t *const entry = allocate_declaration_zero();
2440 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2441 entry->type = enum_type;
2442 entry->symbol = token.v.symbol;
2443 entry->source_position = token.source_position;
2446 if(token.type == '=') {
2448 expression_t *value = parse_constant_expression();
2450 value = create_implicit_cast(value, enum_type);
2451 entry->init.enum_value = value;
2456 record_declaration(entry);
2458 if(token.type != ',')
2461 } while(token.type != '}');
2462 rem_anchor_token('}');
2470 static type_t *parse_enum_specifier(void)
2472 gnu_attribute_t *attributes = NULL;
2473 declaration_t *declaration;
2477 if(token.type == T_IDENTIFIER) {
2478 symbol = token.v.symbol;
2481 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2482 } else if(token.type != '{') {
2483 parse_error_expected("while parsing enum type specifier",
2484 T_IDENTIFIER, '{', 0);
2491 if(declaration == NULL) {
2492 declaration = allocate_declaration_zero();
2493 declaration->namespc = NAMESPACE_ENUM;
2494 declaration->source_position = token.source_position;
2495 declaration->symbol = symbol;
2496 declaration->parent_scope = scope;
2499 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2500 type->enumt.declaration = declaration;
2502 if(token.type == '{') {
2503 if(declaration->init.is_defined) {
2504 errorf(HERE, "multiple definitions of enum %Y", symbol);
2506 if (symbol != NULL) {
2507 environment_push(declaration);
2509 append_declaration(declaration);
2510 declaration->init.is_defined = 1;
2512 parse_enum_entries(type);
2513 parse_attributes(&attributes);
2520 * if a symbol is a typedef to another type, return true
2522 static bool is_typedef_symbol(symbol_t *symbol)
2524 const declaration_t *const declaration =
2525 get_declaration(symbol, NAMESPACE_NORMAL);
2527 declaration != NULL &&
2528 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2531 static type_t *parse_typeof(void)
2538 add_anchor_token(')');
2540 expression_t *expression = NULL;
2543 switch(token.type) {
2544 case T___extension__:
2545 /* this can be a prefix to a typename or an expression */
2546 /* we simply eat it now. */
2549 } while(token.type == T___extension__);
2553 if(is_typedef_symbol(token.v.symbol)) {
2554 type = parse_typename();
2556 expression = parse_expression();
2557 type = expression->base.type;
2562 type = parse_typename();
2566 expression = parse_expression();
2567 type = expression->base.type;
2571 rem_anchor_token(')');
2574 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2575 typeof_type->typeoft.expression = expression;
2576 typeof_type->typeoft.typeof_type = type;
2584 SPECIFIER_SIGNED = 1 << 0,
2585 SPECIFIER_UNSIGNED = 1 << 1,
2586 SPECIFIER_LONG = 1 << 2,
2587 SPECIFIER_INT = 1 << 3,
2588 SPECIFIER_DOUBLE = 1 << 4,
2589 SPECIFIER_CHAR = 1 << 5,
2590 SPECIFIER_SHORT = 1 << 6,
2591 SPECIFIER_LONG_LONG = 1 << 7,
2592 SPECIFIER_FLOAT = 1 << 8,
2593 SPECIFIER_BOOL = 1 << 9,
2594 SPECIFIER_VOID = 1 << 10,
2595 SPECIFIER_INT8 = 1 << 11,
2596 SPECIFIER_INT16 = 1 << 12,
2597 SPECIFIER_INT32 = 1 << 13,
2598 SPECIFIER_INT64 = 1 << 14,
2599 SPECIFIER_INT128 = 1 << 15,
2600 #ifdef PROVIDE_COMPLEX
2601 SPECIFIER_COMPLEX = 1 << 16,
2602 SPECIFIER_IMAGINARY = 1 << 17,
2606 static type_t *create_builtin_type(symbol_t *const symbol,
2607 type_t *const real_type)
2609 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2610 type->builtin.symbol = symbol;
2611 type->builtin.real_type = real_type;
2613 type_t *result = typehash_insert(type);
2614 if (type != result) {
2621 static type_t *get_typedef_type(symbol_t *symbol)
2623 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2624 if(declaration == NULL
2625 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2628 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2629 type->typedeft.declaration = declaration;
2635 * check for the allowed MS alignment values.
2637 static bool check_elignment_value(long long intvalue) {
2638 if(intvalue < 1 || intvalue > 8192) {
2639 errorf(HERE, "illegal alignment value");
2642 unsigned v = (unsigned)intvalue;
2643 for(unsigned i = 1; i <= 8192; i += i) {
2647 errorf(HERE, "alignment must be power of two");
2651 #define DET_MOD(name, tag) do { \
2652 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2653 *modifiers |= tag; \
2656 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2658 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2661 if(token.type == T_restrict) {
2663 DET_MOD(restrict, DM_RESTRICT);
2665 } else if(token.type != T_IDENTIFIER)
2667 symbol_t *symbol = token.v.symbol;
2668 if(symbol == sym_align) {
2671 if(token.type != T_INTEGER)
2673 if(check_elignment_value(token.v.intvalue)) {
2674 if(specifiers->alignment != 0)
2675 warningf(HERE, "align used more than once");
2676 specifiers->alignment = (unsigned char)token.v.intvalue;
2680 } else if(symbol == sym_allocate) {
2683 if(token.type != T_IDENTIFIER)
2685 (void)token.v.symbol;
2687 } else if(symbol == sym_dllimport) {
2689 DET_MOD(dllimport, DM_DLLIMPORT);
2690 } else if(symbol == sym_dllexport) {
2692 DET_MOD(dllexport, DM_DLLEXPORT);
2693 } else if(symbol == sym_thread) {
2695 DET_MOD(thread, DM_THREAD);
2696 } else if(symbol == sym_naked) {
2698 DET_MOD(naked, DM_NAKED);
2699 } else if(symbol == sym_noinline) {
2701 DET_MOD(noinline, DM_NOINLINE);
2702 } else if(symbol == sym_noreturn) {
2704 DET_MOD(noreturn, DM_NORETURN);
2705 } else if(symbol == sym_nothrow) {
2707 DET_MOD(nothrow, DM_NOTHROW);
2708 } else if(symbol == sym_novtable) {
2710 DET_MOD(novtable, DM_NOVTABLE);
2711 } else if(symbol == sym_property) {
2715 bool is_get = false;
2716 if(token.type != T_IDENTIFIER)
2718 if(token.v.symbol == sym_get) {
2720 } else if(token.v.symbol == sym_put) {
2722 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2727 if(token.type != T_IDENTIFIER)
2730 if(specifiers->get_property_sym != NULL) {
2731 errorf(HERE, "get property name already specified");
2733 specifiers->get_property_sym = token.v.symbol;
2736 if(specifiers->put_property_sym != NULL) {
2737 errorf(HERE, "put property name already specified");
2739 specifiers->put_property_sym = token.v.symbol;
2743 if(token.type == ',') {
2750 } else if(symbol == sym_selectany) {
2752 DET_MOD(selectany, DM_SELECTANY);
2753 } else if(symbol == sym_uuid) {
2756 if(token.type != T_STRING_LITERAL)
2760 } else if(symbol == sym_deprecated) {
2762 if(specifiers->deprecated != 0)
2763 warningf(HERE, "deprecated used more than once");
2764 specifiers->deprecated = 1;
2765 if(token.type == '(') {
2767 if(token.type == T_STRING_LITERAL) {
2768 specifiers->deprecated_string = token.v.string.begin;
2771 errorf(HERE, "string literal expected");
2775 } else if(symbol == sym_noalias) {
2777 DET_MOD(noalias, DM_NOALIAS);
2779 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2781 if(token.type == '(')
2785 if (token.type == ',')
2792 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2794 type_t *type = NULL;
2795 unsigned type_qualifiers = 0;
2796 unsigned type_specifiers = 0;
2799 specifiers->source_position = token.source_position;
2802 switch(token.type) {
2805 #define MATCH_STORAGE_CLASS(token, class) \
2807 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2808 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2810 specifiers->declared_storage_class = class; \
2814 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2815 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2816 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2817 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2818 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2823 add_anchor_token(')');
2824 parse_microsoft_extended_decl_modifier(specifiers);
2825 rem_anchor_token(')');
2830 switch (specifiers->declared_storage_class) {
2831 case STORAGE_CLASS_NONE:
2832 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2835 case STORAGE_CLASS_EXTERN:
2836 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2839 case STORAGE_CLASS_STATIC:
2840 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2844 errorf(HERE, "multiple storage classes in declaration specifiers");
2850 /* type qualifiers */
2851 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2853 type_qualifiers |= qualifier; \
2857 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2858 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2859 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2860 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2861 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2862 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2863 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2864 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2866 case T___extension__:
2871 /* type specifiers */
2872 #define MATCH_SPECIFIER(token, specifier, name) \
2875 if(type_specifiers & specifier) { \
2876 errorf(HERE, "multiple " name " type specifiers given"); \
2878 type_specifiers |= specifier; \
2882 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2883 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2884 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2885 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2886 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2887 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2888 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2889 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2890 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2891 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2892 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2893 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2894 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2895 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2896 #ifdef PROVIDE_COMPLEX
2897 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2898 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2900 case T__forceinline:
2901 /* only in microsoft mode */
2902 specifiers->decl_modifiers |= DM_FORCEINLINE;
2906 specifiers->is_inline = true;
2911 if(type_specifiers & SPECIFIER_LONG_LONG) {
2912 errorf(HERE, "multiple type specifiers given");
2913 } else if(type_specifiers & SPECIFIER_LONG) {
2914 type_specifiers |= SPECIFIER_LONG_LONG;
2916 type_specifiers |= SPECIFIER_LONG;
2921 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2923 type->compound.declaration = parse_compound_type_specifier(true);
2927 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2929 type->compound.declaration = parse_compound_type_specifier(false);
2933 type = parse_enum_specifier();
2936 type = parse_typeof();
2938 case T___builtin_va_list:
2939 type = duplicate_type(type_valist);
2943 case T___attribute__:
2944 parse_attributes(&specifiers->gnu_attributes);
2947 case T_IDENTIFIER: {
2948 /* only parse identifier if we haven't found a type yet */
2949 if(type != NULL || type_specifiers != 0)
2950 goto finish_specifiers;
2952 type_t *typedef_type = get_typedef_type(token.v.symbol);
2954 if(typedef_type == NULL)
2955 goto finish_specifiers;
2958 type = typedef_type;
2962 /* function specifier */
2964 goto finish_specifiers;
2971 atomic_type_kind_t atomic_type;
2973 /* match valid basic types */
2974 switch(type_specifiers) {
2975 case SPECIFIER_VOID:
2976 atomic_type = ATOMIC_TYPE_VOID;
2978 case SPECIFIER_CHAR:
2979 atomic_type = ATOMIC_TYPE_CHAR;
2981 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2982 atomic_type = ATOMIC_TYPE_SCHAR;
2984 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2985 atomic_type = ATOMIC_TYPE_UCHAR;
2987 case SPECIFIER_SHORT:
2988 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2989 case SPECIFIER_SHORT | SPECIFIER_INT:
2990 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2991 atomic_type = ATOMIC_TYPE_SHORT;
2993 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2994 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2995 atomic_type = ATOMIC_TYPE_USHORT;
2998 case SPECIFIER_SIGNED:
2999 case SPECIFIER_SIGNED | SPECIFIER_INT:
3000 atomic_type = ATOMIC_TYPE_INT;
3002 case SPECIFIER_UNSIGNED:
3003 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3004 atomic_type = ATOMIC_TYPE_UINT;
3006 case SPECIFIER_LONG:
3007 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3008 case SPECIFIER_LONG | SPECIFIER_INT:
3009 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3010 atomic_type = ATOMIC_TYPE_LONG;
3012 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3013 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3014 atomic_type = ATOMIC_TYPE_ULONG;
3016 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3017 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3018 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3019 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3021 atomic_type = ATOMIC_TYPE_LONGLONG;
3023 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3024 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3026 atomic_type = ATOMIC_TYPE_ULONGLONG;
3029 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3030 atomic_type = unsigned_int8_type_kind;
3033 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3034 atomic_type = unsigned_int16_type_kind;
3037 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3038 atomic_type = unsigned_int32_type_kind;
3041 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3042 atomic_type = unsigned_int64_type_kind;
3045 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3046 atomic_type = unsigned_int128_type_kind;
3049 case SPECIFIER_INT8:
3050 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3051 atomic_type = int8_type_kind;
3054 case SPECIFIER_INT16:
3055 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3056 atomic_type = int16_type_kind;
3059 case SPECIFIER_INT32:
3060 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3061 atomic_type = int32_type_kind;
3064 case SPECIFIER_INT64:
3065 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3066 atomic_type = int64_type_kind;
3069 case SPECIFIER_INT128:
3070 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3071 atomic_type = int128_type_kind;
3074 case SPECIFIER_FLOAT:
3075 atomic_type = ATOMIC_TYPE_FLOAT;
3077 case SPECIFIER_DOUBLE:
3078 atomic_type = ATOMIC_TYPE_DOUBLE;
3080 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3081 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3083 case SPECIFIER_BOOL:
3084 atomic_type = ATOMIC_TYPE_BOOL;
3086 #ifdef PROVIDE_COMPLEX
3087 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3088 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
3090 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3091 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
3093 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3094 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
3096 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3097 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
3099 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3100 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
3102 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3103 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
3107 /* invalid specifier combination, give an error message */
3108 if(type_specifiers == 0) {
3109 if (! strict_mode) {
3110 if (warning.implicit_int) {
3111 warningf(HERE, "no type specifiers in declaration, using 'int'");
3113 atomic_type = ATOMIC_TYPE_INT;
3116 errorf(HERE, "no type specifiers given in declaration");
3118 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3119 (type_specifiers & SPECIFIER_UNSIGNED)) {
3120 errorf(HERE, "signed and unsigned specifiers gives");
3121 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3122 errorf(HERE, "only integer types can be signed or unsigned");
3124 errorf(HERE, "multiple datatypes in declaration");
3126 atomic_type = ATOMIC_TYPE_INVALID;
3129 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3130 type->atomic.akind = atomic_type;
3133 if(type_specifiers != 0) {
3134 errorf(HERE, "multiple datatypes in declaration");
3138 type->base.qualifiers = type_qualifiers;
3139 /* FIXME: check type qualifiers here */
3141 type_t *result = typehash_insert(type);
3142 if(newtype && result != type) {
3146 specifiers->type = result;
3151 static type_qualifiers_t parse_type_qualifiers(void)
3153 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3156 switch(token.type) {
3157 /* type qualifiers */
3158 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3159 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3160 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3161 /* microsoft extended type modifiers */
3162 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3163 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3164 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3165 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3166 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3169 return type_qualifiers;
3174 static declaration_t *parse_identifier_list(void)
3176 declaration_t *declarations = NULL;
3177 declaration_t *last_declaration = NULL;
3179 declaration_t *const declaration = allocate_declaration_zero();
3180 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3181 declaration->source_position = token.source_position;
3182 declaration->symbol = token.v.symbol;
3185 if(last_declaration != NULL) {
3186 last_declaration->next = declaration;
3188 declarations = declaration;
3190 last_declaration = declaration;
3192 if(token.type != ',')
3195 } while(token.type == T_IDENTIFIER);
3197 return declarations;
3200 static void semantic_parameter(declaration_t *declaration)
3202 /* TODO: improve error messages */
3204 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3205 errorf(HERE, "typedef not allowed in parameter list");
3206 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3207 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3208 errorf(HERE, "parameter may only have none or register storage class");
3211 type_t *const orig_type = declaration->type;
3212 type_t * type = skip_typeref(orig_type);
3214 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3215 * into a pointer. § 6.7.5.3 (7) */
3216 if (is_type_array(type)) {
3217 type_t *const element_type = type->array.element_type;
3219 type = make_pointer_type(element_type, type->base.qualifiers);
3221 declaration->type = type;
3224 if(is_type_incomplete(type)) {
3225 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3226 orig_type, declaration->symbol);
3230 static declaration_t *parse_parameter(void)
3232 declaration_specifiers_t specifiers;
3233 memset(&specifiers, 0, sizeof(specifiers));
3235 parse_declaration_specifiers(&specifiers);
3237 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3239 semantic_parameter(declaration);
3244 static declaration_t *parse_parameters(function_type_t *type)
3246 if(token.type == T_IDENTIFIER) {
3247 symbol_t *symbol = token.v.symbol;
3248 if(!is_typedef_symbol(symbol)) {
3249 type->kr_style_parameters = true;
3250 return parse_identifier_list();
3254 if(token.type == ')') {
3255 type->unspecified_parameters = 1;
3258 if(token.type == T_void && look_ahead(1)->type == ')') {
3263 declaration_t *declarations = NULL;
3264 declaration_t *declaration;
3265 declaration_t *last_declaration = NULL;
3266 function_parameter_t *parameter;
3267 function_parameter_t *last_parameter = NULL;
3270 switch(token.type) {
3274 return declarations;
3277 case T___extension__:
3279 declaration = parse_parameter();
3281 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3282 memset(parameter, 0, sizeof(parameter[0]));
3283 parameter->type = declaration->type;
3285 if(last_parameter != NULL) {
3286 last_declaration->next = declaration;
3287 last_parameter->next = parameter;
3289 type->parameters = parameter;
3290 declarations = declaration;
3292 last_parameter = parameter;
3293 last_declaration = declaration;
3297 return declarations;
3299 if(token.type != ',')
3300 return declarations;
3310 } construct_type_kind_t;
3312 typedef struct construct_type_t construct_type_t;
3313 struct construct_type_t {
3314 construct_type_kind_t kind;
3315 construct_type_t *next;
3318 typedef struct parsed_pointer_t parsed_pointer_t;
3319 struct parsed_pointer_t {
3320 construct_type_t construct_type;
3321 type_qualifiers_t type_qualifiers;
3324 typedef struct construct_function_type_t construct_function_type_t;
3325 struct construct_function_type_t {
3326 construct_type_t construct_type;
3327 type_t *function_type;
3330 typedef struct parsed_array_t parsed_array_t;
3331 struct parsed_array_t {
3332 construct_type_t construct_type;
3333 type_qualifiers_t type_qualifiers;
3339 typedef struct construct_base_type_t construct_base_type_t;
3340 struct construct_base_type_t {
3341 construct_type_t construct_type;
3345 static construct_type_t *parse_pointer_declarator(void)
3349 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3350 memset(pointer, 0, sizeof(pointer[0]));
3351 pointer->construct_type.kind = CONSTRUCT_POINTER;
3352 pointer->type_qualifiers = parse_type_qualifiers();
3354 return (construct_type_t*) pointer;
3357 static construct_type_t *parse_array_declarator(void)
3360 add_anchor_token(']');
3362 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3363 memset(array, 0, sizeof(array[0]));
3364 array->construct_type.kind = CONSTRUCT_ARRAY;
3366 if(token.type == T_static) {
3367 array->is_static = true;
3371 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3372 if(type_qualifiers != 0) {
3373 if(token.type == T_static) {
3374 array->is_static = true;
3378 array->type_qualifiers = type_qualifiers;
3380 if(token.type == '*' && look_ahead(1)->type == ']') {
3381 array->is_variable = true;
3383 } else if(token.type != ']') {
3384 array->size = parse_assignment_expression();
3387 rem_anchor_token(']');
3390 return (construct_type_t*) array;
3395 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3398 add_anchor_token(')');
3401 if(declaration != NULL) {
3402 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3404 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3407 declaration_t *parameters = parse_parameters(&type->function);
3408 if(declaration != NULL) {
3409 declaration->scope.declarations = parameters;
3412 construct_function_type_t *construct_function_type =
3413 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3414 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3415 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3416 construct_function_type->function_type = type;
3418 rem_anchor_token(')');
3422 return (construct_type_t*) construct_function_type;
3425 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3426 bool may_be_abstract)
3428 /* construct a single linked list of construct_type_t's which describe
3429 * how to construct the final declarator type */
3430 construct_type_t *first = NULL;
3431 construct_type_t *last = NULL;
3432 gnu_attribute_t *attributes = NULL;
3435 while(token.type == '*') {
3436 construct_type_t *type = parse_pointer_declarator();
3447 /* TODO: find out if this is correct */
3448 parse_attributes(&attributes);
3450 construct_type_t *inner_types = NULL;
3452 switch(token.type) {
3454 if(declaration == NULL) {
3455 errorf(HERE, "no identifier expected in typename");
3457 declaration->symbol = token.v.symbol;
3458 declaration->source_position = token.source_position;
3464 add_anchor_token(')');
3465 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3466 rem_anchor_token(')');
3472 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3473 /* avoid a loop in the outermost scope, because eat_statement doesn't
3475 if(token.type == '}' && current_function == NULL) {
3483 construct_type_t *p = last;
3486 construct_type_t *type;
3487 switch(token.type) {
3489 type = parse_function_declarator(declaration);
3492 type = parse_array_declarator();
3495 goto declarator_finished;
3498 /* insert in the middle of the list (behind p) */
3500 type->next = p->next;
3511 declarator_finished:
3512 parse_attributes(&attributes);
3514 /* append inner_types at the end of the list, we don't to set last anymore
3515 * as it's not needed anymore */
3517 assert(first == NULL);
3518 first = inner_types;
3520 last->next = inner_types;
3528 static type_t *construct_declarator_type(construct_type_t *construct_list,
3531 construct_type_t *iter = construct_list;
3532 for( ; iter != NULL; iter = iter->next) {
3533 switch(iter->kind) {
3534 case CONSTRUCT_INVALID:
3535 internal_errorf(HERE, "invalid type construction found");
3536 case CONSTRUCT_FUNCTION: {
3537 construct_function_type_t *construct_function_type
3538 = (construct_function_type_t*) iter;
3540 type_t *function_type = construct_function_type->function_type;
3542 function_type->function.return_type = type;
3544 type_t *skipped_return_type = skip_typeref(type);
3545 if (is_type_function(skipped_return_type)) {
3546 errorf(HERE, "function returning function is not allowed");
3547 type = type_error_type;
3548 } else if (is_type_array(skipped_return_type)) {
3549 errorf(HERE, "function returning array is not allowed");
3550 type = type_error_type;
3552 type = function_type;
3557 case CONSTRUCT_POINTER: {
3558 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3559 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3560 pointer_type->pointer.points_to = type;
3561 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3563 type = pointer_type;
3567 case CONSTRUCT_ARRAY: {
3568 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3569 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3571 expression_t *size_expression = parsed_array->size;
3572 if(size_expression != NULL) {
3574 = create_implicit_cast(size_expression, type_size_t);
3577 array_type->base.qualifiers = parsed_array->type_qualifiers;
3578 array_type->array.element_type = type;
3579 array_type->array.is_static = parsed_array->is_static;
3580 array_type->array.is_variable = parsed_array->is_variable;
3581 array_type->array.size_expression = size_expression;
3583 if(size_expression != NULL) {
3584 if(is_constant_expression(size_expression)) {
3585 array_type->array.size_constant = true;
3586 array_type->array.size
3587 = fold_constant(size_expression);
3589 array_type->array.is_vla = true;
3593 type_t *skipped_type = skip_typeref(type);
3594 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3595 errorf(HERE, "array of void is not allowed");
3596 type = type_error_type;
3604 type_t *hashed_type = typehash_insert(type);
3605 if(hashed_type != type) {
3606 /* the function type was constructed earlier freeing it here will
3607 * destroy other types... */
3608 if(iter->kind != CONSTRUCT_FUNCTION) {
3618 static declaration_t *parse_declarator(
3619 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3621 declaration_t *const declaration = allocate_declaration_zero();
3622 declaration->declared_storage_class = specifiers->declared_storage_class;
3623 declaration->modifiers = specifiers->decl_modifiers;
3624 declaration->deprecated = specifiers->deprecated;
3625 declaration->deprecated_string = specifiers->deprecated_string;
3626 declaration->get_property_sym = specifiers->get_property_sym;
3627 declaration->put_property_sym = specifiers->put_property_sym;
3628 declaration->is_inline = specifiers->is_inline;
3630 declaration->storage_class = specifiers->declared_storage_class;
3631 if(declaration->storage_class == STORAGE_CLASS_NONE
3632 && scope != global_scope) {
3633 declaration->storage_class = STORAGE_CLASS_AUTO;
3636 if(specifiers->alignment != 0) {
3637 /* TODO: add checks here */
3638 declaration->alignment = specifiers->alignment;
3641 construct_type_t *construct_type
3642 = parse_inner_declarator(declaration, may_be_abstract);
3643 type_t *const type = specifiers->type;
3644 declaration->type = construct_declarator_type(construct_type, type);
3646 if(construct_type != NULL) {
3647 obstack_free(&temp_obst, construct_type);
3653 static type_t *parse_abstract_declarator(type_t *base_type)
3655 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3657 type_t *result = construct_declarator_type(construct_type, base_type);
3658 if(construct_type != NULL) {
3659 obstack_free(&temp_obst, construct_type);
3665 static declaration_t *append_declaration(declaration_t* const declaration)
3667 if (last_declaration != NULL) {
3668 last_declaration->next = declaration;
3670 scope->declarations = declaration;
3672 last_declaration = declaration;
3677 * Check if the declaration of main is suspicious. main should be a
3678 * function with external linkage, returning int, taking either zero
3679 * arguments, two, or three arguments of appropriate types, ie.
3681 * int main([ int argc, char **argv [, char **env ] ]).
3683 * @param decl the declaration to check
3684 * @param type the function type of the declaration
3686 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3688 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3689 warningf(&decl->source_position,
3690 "'main' is normally a non-static function");
3692 if (skip_typeref(func_type->return_type) != type_int) {
3693 warningf(&decl->source_position,
3694 "return type of 'main' should be 'int', but is '%T'",
3695 func_type->return_type);
3697 const function_parameter_t *parm = func_type->parameters;
3699 type_t *const first_type = parm->type;
3700 if (!types_compatible(skip_typeref(first_type), type_int)) {
3701 warningf(&decl->source_position,
3702 "first argument of 'main' should be 'int', but is '%T'", first_type);
3706 type_t *const second_type = parm->type;
3707 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3708 warningf(&decl->source_position,
3709 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3713 type_t *const third_type = parm->type;
3714 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3715 warningf(&decl->source_position,
3716 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3720 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3724 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3730 * Check if a symbol is the equal to "main".
3732 static bool is_sym_main(const symbol_t *const sym)
3734 return strcmp(sym->string, "main") == 0;
3737 static declaration_t *internal_record_declaration(
3738 declaration_t *const declaration,
3739 const bool is_function_definition)
3741 const symbol_t *const symbol = declaration->symbol;
3742 const namespace_t namespc = (namespace_t)declaration->namespc;
3744 type_t *const orig_type = declaration->type;
3745 type_t *const type = skip_typeref(orig_type);
3746 if (is_type_function(type) &&
3747 type->function.unspecified_parameters &&
3748 warning.strict_prototypes) {
3749 warningf(&declaration->source_position,
3750 "function declaration '%#T' is not a prototype",
3751 orig_type, declaration->symbol);
3754 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3755 check_type_of_main(declaration, &type->function);
3758 assert(declaration->symbol != NULL);
3759 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3761 assert(declaration != previous_declaration);
3762 if (previous_declaration != NULL) {
3763 if (previous_declaration->parent_scope == scope) {
3764 /* can happen for K&R style declarations */
3765 if(previous_declaration->type == NULL) {
3766 previous_declaration->type = declaration->type;
3769 const type_t *prev_type = skip_typeref(previous_declaration->type);
3770 if (!types_compatible(type, prev_type)) {
3771 errorf(&declaration->source_position,
3772 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3773 orig_type, symbol, previous_declaration->type, symbol,
3774 &previous_declaration->source_position);
3776 unsigned old_storage_class = previous_declaration->storage_class;
3777 if(old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3778 errorf(&declaration->source_position,
3779 "redeclaration of enum entry '%Y' (declared %P)",
3780 symbol, &previous_declaration->source_position);
3781 return previous_declaration;
3784 unsigned new_storage_class = declaration->storage_class;
3786 if(is_type_incomplete(prev_type)) {
3787 previous_declaration->type = type;
3791 /* pretend no storage class means extern for function
3792 * declarations (except if the previous declaration is neither
3793 * none nor extern) */
3794 if (is_type_function(type)) {
3795 switch (old_storage_class) {
3796 case STORAGE_CLASS_NONE:
3797 old_storage_class = STORAGE_CLASS_EXTERN;
3799 case STORAGE_CLASS_EXTERN:
3800 if (is_function_definition) {
3801 if (warning.missing_prototypes &&
3802 prev_type->function.unspecified_parameters &&
3803 !is_sym_main(symbol)) {
3804 warningf(&declaration->source_position,
3805 "no previous prototype for '%#T'",
3808 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3809 new_storage_class = STORAGE_CLASS_EXTERN;
3817 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3818 new_storage_class == STORAGE_CLASS_EXTERN) {
3819 warn_redundant_declaration:
3820 if (warning.redundant_decls) {
3821 warningf(&declaration->source_position,
3822 "redundant declaration for '%Y' (declared %P)",
3823 symbol, &previous_declaration->source_position);
3825 } else if (current_function == NULL) {
3826 if (old_storage_class != STORAGE_CLASS_STATIC &&
3827 new_storage_class == STORAGE_CLASS_STATIC) {
3828 errorf(&declaration->source_position,
3829 "static declaration of '%Y' follows non-static declaration (declared %P)",
3830 symbol, &previous_declaration->source_position);
3832 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3833 goto warn_redundant_declaration;
3835 if (new_storage_class == STORAGE_CLASS_NONE) {
3836 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3837 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3841 if (old_storage_class == new_storage_class) {
3842 errorf(&declaration->source_position,
3843 "redeclaration of '%Y' (declared %P)",
3844 symbol, &previous_declaration->source_position);
3846 errorf(&declaration->source_position,
3847 "redeclaration of '%Y' with different linkage (declared %P)",
3848 symbol, &previous_declaration->source_position);
3852 return previous_declaration;
3854 } else if (is_function_definition) {
3855 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3856 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3857 warningf(&declaration->source_position,
3858 "no previous prototype for '%#T'", orig_type, symbol);
3859 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3860 warningf(&declaration->source_position,
3861 "no previous declaration for '%#T'", orig_type,
3865 } else if (warning.missing_declarations &&
3866 scope == global_scope &&
3867 !is_type_function(type) && (
3868 declaration->storage_class == STORAGE_CLASS_NONE ||
3869 declaration->storage_class == STORAGE_CLASS_THREAD
3871 warningf(&declaration->source_position,
3872 "no previous declaration for '%#T'", orig_type, symbol);
3875 assert(declaration->parent_scope == NULL);
3876 assert(scope != NULL);
3878 declaration->parent_scope = scope;
3880 environment_push(declaration);
3881 return append_declaration(declaration);
3884 static declaration_t *record_declaration(declaration_t *declaration)
3886 return internal_record_declaration(declaration, false);
3889 static declaration_t *record_function_definition(declaration_t *declaration)
3891 return internal_record_declaration(declaration, true);
3894 static void parser_error_multiple_definition(declaration_t *declaration,
3895 const source_position_t *source_position)
3897 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
3898 declaration->symbol, &declaration->source_position);
3901 static bool is_declaration_specifier(const token_t *token,
3902 bool only_type_specifiers)
3904 switch(token->type) {
3908 return is_typedef_symbol(token->v.symbol);
3910 case T___extension__:
3913 return !only_type_specifiers;
3920 static void parse_init_declarator_rest(declaration_t *declaration)
3924 type_t *orig_type = declaration->type;
3925 type_t *type = skip_typeref(orig_type);
3927 if(declaration->init.initializer != NULL) {
3928 parser_error_multiple_definition(declaration, HERE);
3931 bool must_be_constant = false;
3932 if(declaration->storage_class == STORAGE_CLASS_STATIC
3933 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3934 || declaration->parent_scope == global_scope) {
3935 must_be_constant = true;
3938 parse_initializer_env_t env;
3939 env.type = orig_type;
3940 env.must_be_constant = must_be_constant;
3941 env.declaration = declaration;
3943 initializer_t *initializer = parse_initializer(&env);
3945 if(env.type != orig_type) {
3946 orig_type = env.type;
3947 type = skip_typeref(orig_type);
3948 declaration->type = env.type;
3951 if(is_type_function(type)) {
3952 errorf(&declaration->source_position,
3953 "initializers not allowed for function types at declator '%Y' (type '%T')",
3954 declaration->symbol, orig_type);
3956 declaration->init.initializer = initializer;
3960 /* parse rest of a declaration without any declarator */
3961 static void parse_anonymous_declaration_rest(
3962 const declaration_specifiers_t *specifiers,
3963 parsed_declaration_func finished_declaration)
3967 declaration_t *const declaration = allocate_declaration_zero();
3968 declaration->type = specifiers->type;
3969 declaration->declared_storage_class = specifiers->declared_storage_class;
3970 declaration->source_position = specifiers->source_position;
3971 declaration->modifiers = specifiers->decl_modifiers;
3973 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3974 warningf(&declaration->source_position,
3975 "useless storage class in empty declaration");
3977 declaration->storage_class = STORAGE_CLASS_NONE;
3979 type_t *type = declaration->type;
3980 switch (type->kind) {
3981 case TYPE_COMPOUND_STRUCT:
3982 case TYPE_COMPOUND_UNION: {
3983 if (type->compound.declaration->symbol == NULL) {
3984 warningf(&declaration->source_position,
3985 "unnamed struct/union that defines no instances");
3994 warningf(&declaration->source_position, "empty declaration");
3998 finished_declaration(declaration);
4001 static void parse_declaration_rest(declaration_t *ndeclaration,
4002 const declaration_specifiers_t *specifiers,
4003 parsed_declaration_func finished_declaration)
4005 add_anchor_token(';');
4006 add_anchor_token('=');
4007 add_anchor_token(',');
4009 declaration_t *declaration = finished_declaration(ndeclaration);
4011 type_t *orig_type = declaration->type;
4012 type_t *type = skip_typeref(orig_type);
4014 if (type->kind != TYPE_FUNCTION &&
4015 declaration->is_inline &&
4016 is_type_valid(type)) {
4017 warningf(&declaration->source_position,
4018 "variable '%Y' declared 'inline'\n", declaration->symbol);
4021 if(token.type == '=') {
4022 parse_init_declarator_rest(declaration);
4025 if(token.type != ',')
4029 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4034 rem_anchor_token(';');
4035 rem_anchor_token('=');
4036 rem_anchor_token(',');
4039 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4041 symbol_t *symbol = declaration->symbol;
4042 if(symbol == NULL) {
4043 errorf(HERE, "anonymous declaration not valid as function parameter");
4046 namespace_t namespc = (namespace_t) declaration->namespc;
4047 if(namespc != NAMESPACE_NORMAL) {
4048 return record_declaration(declaration);
4051 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4052 if(previous_declaration == NULL ||
4053 previous_declaration->parent_scope != scope) {
4054 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4059 if(previous_declaration->type == NULL) {
4060 previous_declaration->type = declaration->type;
4061 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4062 previous_declaration->storage_class = declaration->storage_class;
4063 previous_declaration->parent_scope = scope;
4064 return previous_declaration;
4066 return record_declaration(declaration);
4070 static void parse_declaration(parsed_declaration_func finished_declaration)
4072 declaration_specifiers_t specifiers;
4073 memset(&specifiers, 0, sizeof(specifiers));
4074 parse_declaration_specifiers(&specifiers);
4076 if(token.type == ';') {
4077 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4079 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4080 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4084 static void parse_kr_declaration_list(declaration_t *declaration)
4086 type_t *type = skip_typeref(declaration->type);
4087 if(!is_type_function(type))
4090 if(!type->function.kr_style_parameters)
4093 /* push function parameters */
4094 int top = environment_top();
4095 scope_t *last_scope = scope;
4096 set_scope(&declaration->scope);
4098 declaration_t *parameter = declaration->scope.declarations;
4099 for( ; parameter != NULL; parameter = parameter->next) {
4100 assert(parameter->parent_scope == NULL);
4101 parameter->parent_scope = scope;
4102 environment_push(parameter);
4105 /* parse declaration list */
4106 while(is_declaration_specifier(&token, false)) {
4107 parse_declaration(finished_kr_declaration);
4110 /* pop function parameters */
4111 assert(scope == &declaration->scope);
4112 set_scope(last_scope);
4113 environment_pop_to(top);
4115 /* update function type */
4116 type_t *new_type = duplicate_type(type);
4117 new_type->function.kr_style_parameters = false;
4119 function_parameter_t *parameters = NULL;
4120 function_parameter_t *last_parameter = NULL;
4122 declaration_t *parameter_declaration = declaration->scope.declarations;
4123 for( ; parameter_declaration != NULL;
4124 parameter_declaration = parameter_declaration->next) {
4125 type_t *parameter_type = parameter_declaration->type;
4126 if(parameter_type == NULL) {
4128 errorf(HERE, "no type specified for function parameter '%Y'",
4129 parameter_declaration->symbol);
4131 if (warning.implicit_int) {
4132 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4133 parameter_declaration->symbol);
4135 parameter_type = type_int;
4136 parameter_declaration->type = parameter_type;
4140 semantic_parameter(parameter_declaration);
4141 parameter_type = parameter_declaration->type;
4143 function_parameter_t *function_parameter
4144 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4145 memset(function_parameter, 0, sizeof(function_parameter[0]));
4147 function_parameter->type = parameter_type;
4148 if(last_parameter != NULL) {
4149 last_parameter->next = function_parameter;
4151 parameters = function_parameter;
4153 last_parameter = function_parameter;
4155 new_type->function.parameters = parameters;
4157 type = typehash_insert(new_type);
4158 if(type != new_type) {
4159 obstack_free(type_obst, new_type);
4162 declaration->type = type;
4165 static bool first_err = true;
4168 * When called with first_err set, prints the name of the current function,
4171 static void print_in_function(void) {
4174 diagnosticf("%s: In function '%Y':\n",
4175 current_function->source_position.input_name,
4176 current_function->symbol);
4181 * Check if all labels are defined in the current function.
4182 * Check if all labels are used in the current function.
4184 static void check_labels(void)
4186 for (const goto_statement_t *goto_statement = goto_first;
4187 goto_statement != NULL;
4188 goto_statement = goto_statement->next) {
4189 declaration_t *label = goto_statement->label;
4192 if (label->source_position.input_name == NULL) {
4193 print_in_function();
4194 errorf(&goto_statement->base.source_position,
4195 "label '%Y' used but not defined", label->symbol);
4198 goto_first = goto_last = NULL;
4200 if (warning.unused_label) {
4201 for (const label_statement_t *label_statement = label_first;
4202 label_statement != NULL;
4203 label_statement = label_statement->next) {
4204 const declaration_t *label = label_statement->label;
4206 if (! label->used) {
4207 print_in_function();
4208 warningf(&label_statement->base.source_position,
4209 "label '%Y' defined but not used", label->symbol);
4213 label_first = label_last = NULL;
4217 * Check declarations of current_function for unused entities.
4219 static void check_declarations(void)
4221 if (warning.unused_parameter) {
4222 const scope_t *scope = ¤t_function->scope;
4224 const declaration_t *parameter = scope->declarations;
4225 for (; parameter != NULL; parameter = parameter->next) {
4226 if (! parameter->used) {
4227 print_in_function();
4228 warningf(¶meter->source_position,
4229 "unused parameter '%Y'", parameter->symbol);
4233 if (warning.unused_variable) {
4237 static void parse_external_declaration(void)
4239 /* function-definitions and declarations both start with declaration
4241 declaration_specifiers_t specifiers;
4242 memset(&specifiers, 0, sizeof(specifiers));
4244 add_anchor_token(';');
4245 parse_declaration_specifiers(&specifiers);
4246 rem_anchor_token(';');
4248 /* must be a declaration */
4249 if(token.type == ';') {
4250 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4254 add_anchor_token(',');
4255 add_anchor_token('=');
4256 rem_anchor_token(';');
4258 /* declarator is common to both function-definitions and declarations */
4259 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4261 rem_anchor_token(',');
4262 rem_anchor_token('=');
4263 rem_anchor_token(';');
4265 /* must be a declaration */
4266 if(token.type == ',' || token.type == '=' || token.type == ';') {
4267 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4271 /* must be a function definition */
4272 parse_kr_declaration_list(ndeclaration);
4274 if(token.type != '{') {
4275 parse_error_expected("while parsing function definition", '{', 0);
4276 eat_until_matching_token(';');
4280 type_t *type = ndeclaration->type;
4282 /* note that we don't skip typerefs: the standard doesn't allow them here
4283 * (so we can't use is_type_function here) */
4284 if(type->kind != TYPE_FUNCTION) {
4285 if (is_type_valid(type)) {
4286 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4287 type, ndeclaration->symbol);
4293 /* § 6.7.5.3 (14) a function definition with () means no
4294 * parameters (and not unspecified parameters) */
4295 if(type->function.unspecified_parameters) {
4296 type_t *duplicate = duplicate_type(type);
4297 duplicate->function.unspecified_parameters = false;
4299 type = typehash_insert(duplicate);
4300 if(type != duplicate) {
4301 obstack_free(type_obst, duplicate);
4303 ndeclaration->type = type;
4306 declaration_t *const declaration = record_function_definition(ndeclaration);
4307 if(ndeclaration != declaration) {
4308 declaration->scope = ndeclaration->scope;
4310 type = skip_typeref(declaration->type);
4312 /* push function parameters and switch scope */
4313 int top = environment_top();
4314 scope_t *last_scope = scope;
4315 set_scope(&declaration->scope);
4317 declaration_t *parameter = declaration->scope.declarations;
4318 for( ; parameter != NULL; parameter = parameter->next) {
4319 if(parameter->parent_scope == &ndeclaration->scope) {
4320 parameter->parent_scope = scope;
4322 assert(parameter->parent_scope == NULL
4323 || parameter->parent_scope == scope);
4324 parameter->parent_scope = scope;
4325 environment_push(parameter);
4328 if(declaration->init.statement != NULL) {
4329 parser_error_multiple_definition(declaration, HERE);
4331 goto end_of_parse_external_declaration;
4333 /* parse function body */
4334 int label_stack_top = label_top();
4335 declaration_t *old_current_function = current_function;
4336 current_function = declaration;
4338 declaration->init.statement = parse_compound_statement();
4341 check_declarations();
4343 assert(current_function == declaration);
4344 current_function = old_current_function;
4345 label_pop_to(label_stack_top);
4348 end_of_parse_external_declaration:
4349 assert(scope == &declaration->scope);
4350 set_scope(last_scope);
4351 environment_pop_to(top);
4354 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4355 source_position_t *source_position)
4357 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4358 type->bitfield.base = base;
4359 type->bitfield.size = size;
4364 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4367 declaration_t *iter = compound_declaration->scope.declarations;
4368 for( ; iter != NULL; iter = iter->next) {
4369 if(iter->namespc != NAMESPACE_NORMAL)
4372 if(iter->symbol == NULL) {
4373 type_t *type = skip_typeref(iter->type);
4374 if(is_type_compound(type)) {
4375 declaration_t *result
4376 = find_compound_entry(type->compound.declaration, symbol);
4383 if(iter->symbol == symbol) {
4391 static void parse_compound_declarators(declaration_t *struct_declaration,
4392 const declaration_specifiers_t *specifiers)
4394 declaration_t *last_declaration = struct_declaration->scope.declarations;
4395 if(last_declaration != NULL) {
4396 while(last_declaration->next != NULL) {
4397 last_declaration = last_declaration->next;
4402 declaration_t *declaration;
4404 if(token.type == ':') {
4405 source_position_t source_position = *HERE;
4408 type_t *base_type = specifiers->type;
4409 expression_t *size = parse_constant_expression();
4411 if(!is_type_integer(skip_typeref(base_type))) {
4412 errorf(HERE, "bitfield base type '%T' is not an integer type",
4416 type_t *type = make_bitfield_type(base_type, size, &source_position);
4418 declaration = allocate_declaration_zero();
4419 declaration->namespc = NAMESPACE_NORMAL;
4420 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4421 declaration->storage_class = STORAGE_CLASS_NONE;
4422 declaration->source_position = source_position;
4423 declaration->modifiers = specifiers->decl_modifiers;
4424 declaration->type = type;
4426 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4428 type_t *orig_type = declaration->type;
4429 type_t *type = skip_typeref(orig_type);
4431 if(token.type == ':') {
4432 source_position_t source_position = *HERE;
4434 expression_t *size = parse_constant_expression();
4436 if(!is_type_integer(type)) {
4437 errorf(HERE, "bitfield base type '%T' is not an "
4438 "integer type", orig_type);
4441 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4442 declaration->type = bitfield_type;
4444 /* TODO we ignore arrays for now... what is missing is a check
4445 * that they're at the end of the struct */
4446 if(is_type_incomplete(type) && !is_type_array(type)) {
4448 "compound member '%Y' has incomplete type '%T'",
4449 declaration->symbol, orig_type);
4450 } else if(is_type_function(type)) {
4451 errorf(HERE, "compound member '%Y' must not have function "
4452 "type '%T'", declaration->symbol, orig_type);
4457 /* make sure we don't define a symbol multiple times */
4458 symbol_t *symbol = declaration->symbol;
4459 if(symbol != NULL) {
4460 declaration_t *prev_decl
4461 = find_compound_entry(struct_declaration, symbol);
4463 if(prev_decl != NULL) {
4464 assert(prev_decl->symbol == symbol);
4465 errorf(&declaration->source_position,
4466 "multiple declarations of symbol '%Y' (declared %P)",
4467 symbol, &prev_decl->source_position);
4471 /* append declaration */
4472 if(last_declaration != NULL) {
4473 last_declaration->next = declaration;
4475 struct_declaration->scope.declarations = declaration;
4477 last_declaration = declaration;
4479 if(token.type != ',')
4489 static void parse_compound_type_entries(declaration_t *compound_declaration)
4492 add_anchor_token('}');
4494 while(token.type != '}' && token.type != T_EOF) {
4495 declaration_specifiers_t specifiers;
4496 memset(&specifiers, 0, sizeof(specifiers));
4497 parse_declaration_specifiers(&specifiers);
4499 parse_compound_declarators(compound_declaration, &specifiers);
4501 rem_anchor_token('}');
4503 if(token.type == T_EOF) {
4504 errorf(HERE, "EOF while parsing struct");
4509 static type_t *parse_typename(void)
4511 declaration_specifiers_t specifiers;
4512 memset(&specifiers, 0, sizeof(specifiers));
4513 parse_declaration_specifiers(&specifiers);
4514 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4515 /* TODO: improve error message, user does probably not know what a
4516 * storage class is...
4518 errorf(HERE, "typename may not have a storage class");
4521 type_t *result = parse_abstract_declarator(specifiers.type);
4529 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4530 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4531 expression_t *left);
4533 typedef struct expression_parser_function_t expression_parser_function_t;
4534 struct expression_parser_function_t {
4535 unsigned precedence;
4536 parse_expression_function parser;
4537 unsigned infix_precedence;
4538 parse_expression_infix_function infix_parser;
4541 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4544 * Prints an error message if an expression was expected but not read
4546 static expression_t *expected_expression_error(void)
4548 /* skip the error message if the error token was read */
4549 if (token.type != T_ERROR) {
4550 errorf(HERE, "expected expression, got token '%K'", &token);
4554 return create_invalid_expression();
4558 * Parse a string constant.
4560 static expression_t *parse_string_const(void)
4563 if (token.type == T_STRING_LITERAL) {
4564 string_t res = token.v.string;
4566 while (token.type == T_STRING_LITERAL) {
4567 res = concat_strings(&res, &token.v.string);
4570 if (token.type != T_WIDE_STRING_LITERAL) {
4571 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4572 /* note: that we use type_char_ptr here, which is already the
4573 * automatic converted type. revert_automatic_type_conversion
4574 * will construct the array type */
4575 cnst->base.type = type_char_ptr;
4576 cnst->string.value = res;
4580 wres = concat_string_wide_string(&res, &token.v.wide_string);
4582 wres = token.v.wide_string;
4587 switch (token.type) {
4588 case T_WIDE_STRING_LITERAL:
4589 wres = concat_wide_strings(&wres, &token.v.wide_string);
4592 case T_STRING_LITERAL:
4593 wres = concat_wide_string_string(&wres, &token.v.string);
4597 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4598 cnst->base.type = type_wchar_t_ptr;
4599 cnst->wide_string.value = wres;
4608 * Parse an integer constant.
4610 static expression_t *parse_int_const(void)
4612 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4613 cnst->base.source_position = *HERE;
4614 cnst->base.type = token.datatype;
4615 cnst->conste.v.int_value = token.v.intvalue;
4623 * Parse a character constant.
4625 static expression_t *parse_character_constant(void)
4627 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4629 cnst->base.source_position = *HERE;
4630 cnst->base.type = token.datatype;
4631 cnst->conste.v.character = token.v.string;
4633 if (cnst->conste.v.character.size != 1) {
4634 if (warning.multichar && (c_mode & _GNUC)) {
4636 warningf(HERE, "multi-character character constant");
4638 errorf(HERE, "more than 1 characters in character constant");
4647 * Parse a wide character constant.
4649 static expression_t *parse_wide_character_constant(void)
4651 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4653 cnst->base.source_position = *HERE;
4654 cnst->base.type = token.datatype;
4655 cnst->conste.v.wide_character = token.v.wide_string;
4657 if (cnst->conste.v.wide_character.size != 1) {
4658 if (warning.multichar && (c_mode & _GNUC)) {
4660 warningf(HERE, "multi-character character constant");
4662 errorf(HERE, "more than 1 characters in character constant");
4671 * Parse a float constant.
4673 static expression_t *parse_float_const(void)
4675 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4676 cnst->base.type = token.datatype;
4677 cnst->conste.v.float_value = token.v.floatvalue;
4684 static declaration_t *create_implicit_function(symbol_t *symbol,
4685 const source_position_t *source_position)
4687 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4688 ntype->function.return_type = type_int;
4689 ntype->function.unspecified_parameters = true;
4691 type_t *type = typehash_insert(ntype);
4696 declaration_t *const declaration = allocate_declaration_zero();
4697 declaration->storage_class = STORAGE_CLASS_EXTERN;
4698 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4699 declaration->type = type;
4700 declaration->symbol = symbol;
4701 declaration->source_position = *source_position;
4702 declaration->parent_scope = global_scope;
4704 scope_t *old_scope = scope;
4705 set_scope(global_scope);
4707 environment_push(declaration);
4708 /* prepends the declaration to the global declarations list */
4709 declaration->next = scope->declarations;
4710 scope->declarations = declaration;
4712 assert(scope == global_scope);
4713 set_scope(old_scope);
4719 * Creates a return_type (func)(argument_type) function type if not
4722 * @param return_type the return type
4723 * @param argument_type the argument type
4725 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4727 function_parameter_t *parameter
4728 = obstack_alloc(type_obst, sizeof(parameter[0]));
4729 memset(parameter, 0, sizeof(parameter[0]));
4730 parameter->type = argument_type;
4732 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4733 type->function.return_type = return_type;
4734 type->function.parameters = parameter;
4736 type_t *result = typehash_insert(type);
4737 if(result != type) {
4745 * Creates a function type for some function like builtins.
4747 * @param symbol the symbol describing the builtin
4749 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4751 switch(symbol->ID) {
4752 case T___builtin_alloca:
4753 return make_function_1_type(type_void_ptr, type_size_t);
4754 case T___builtin_nan:
4755 return make_function_1_type(type_double, type_char_ptr);
4756 case T___builtin_nanf:
4757 return make_function_1_type(type_float, type_char_ptr);
4758 case T___builtin_nand:
4759 return make_function_1_type(type_long_double, type_char_ptr);
4760 case T___builtin_va_end:
4761 return make_function_1_type(type_void, type_valist);
4763 internal_errorf(HERE, "not implemented builtin symbol found");
4768 * Performs automatic type cast as described in § 6.3.2.1.
4770 * @param orig_type the original type
4772 static type_t *automatic_type_conversion(type_t *orig_type)
4774 type_t *type = skip_typeref(orig_type);
4775 if(is_type_array(type)) {
4776 array_type_t *array_type = &type->array;
4777 type_t *element_type = array_type->element_type;
4778 unsigned qualifiers = array_type->type.qualifiers;
4780 return make_pointer_type(element_type, qualifiers);
4783 if(is_type_function(type)) {
4784 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4791 * reverts the automatic casts of array to pointer types and function
4792 * to function-pointer types as defined § 6.3.2.1
4794 type_t *revert_automatic_type_conversion(const expression_t *expression)
4796 switch (expression->kind) {
4797 case EXPR_REFERENCE: return expression->reference.declaration->type;
4798 case EXPR_SELECT: return expression->select.compound_entry->type;
4800 case EXPR_UNARY_DEREFERENCE: {
4801 const expression_t *const value = expression->unary.value;
4802 type_t *const type = skip_typeref(value->base.type);
4803 assert(is_type_pointer(type));
4804 return type->pointer.points_to;
4807 case EXPR_BUILTIN_SYMBOL:
4808 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4810 case EXPR_ARRAY_ACCESS: {
4811 const expression_t *array_ref = expression->array_access.array_ref;
4812 type_t *type_left = skip_typeref(array_ref->base.type);
4813 if (!is_type_valid(type_left))
4815 assert(is_type_pointer(type_left));
4816 return type_left->pointer.points_to;
4819 case EXPR_STRING_LITERAL: {
4820 size_t size = expression->string.value.size;
4821 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4824 case EXPR_WIDE_STRING_LITERAL: {
4825 size_t size = expression->wide_string.value.size;
4826 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4829 case EXPR_COMPOUND_LITERAL:
4830 return expression->compound_literal.type;
4835 return expression->base.type;
4838 static expression_t *parse_reference(void)
4840 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4842 reference_expression_t *ref = &expression->reference;
4843 ref->symbol = token.v.symbol;
4845 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4847 source_position_t source_position = token.source_position;
4850 if(declaration == NULL) {
4851 if (! strict_mode && token.type == '(') {
4852 /* an implicitly defined function */
4853 if (warning.implicit_function_declaration) {
4854 warningf(HERE, "implicit declaration of function '%Y'",
4858 declaration = create_implicit_function(ref->symbol,
4861 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4862 return create_invalid_expression();
4866 type_t *type = declaration->type;
4868 /* we always do the auto-type conversions; the & and sizeof parser contains
4869 * code to revert this! */
4870 type = automatic_type_conversion(type);
4872 ref->declaration = declaration;
4873 ref->base.type = type;
4875 /* this declaration is used */
4876 declaration->used = true;
4878 /* check for deprecated functions */
4879 if(declaration->deprecated != 0) {
4880 const char *prefix = "";
4881 if (is_type_function(declaration->type))
4882 prefix = "function ";
4884 if (declaration->deprecated_string != NULL) {
4885 warningf(&source_position,
4886 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4887 declaration->deprecated_string);
4889 warningf(&source_position,
4890 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4897 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4901 /* TODO check if explicit cast is allowed and issue warnings/errors */
4904 static expression_t *parse_compound_literal(type_t *type)
4906 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4908 parse_initializer_env_t env;
4910 env.declaration = NULL;
4911 env.must_be_constant = false;
4912 initializer_t *initializer = parse_initializer(&env);
4915 expression->compound_literal.initializer = initializer;
4916 expression->compound_literal.type = type;
4917 expression->base.type = automatic_type_conversion(type);
4923 * Parse a cast expression.
4925 static expression_t *parse_cast(void)
4927 source_position_t source_position = token.source_position;
4929 type_t *type = parse_typename();
4931 /* matching add_anchor_token() is at call site */
4932 rem_anchor_token(')');
4935 if(token.type == '{') {
4936 return parse_compound_literal(type);
4939 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4940 cast->base.source_position = source_position;
4942 expression_t *value = parse_sub_expression(20);
4944 check_cast_allowed(value, type);
4946 cast->base.type = type;
4947 cast->unary.value = value;
4951 return create_invalid_expression();
4955 * Parse a statement expression.
4957 static expression_t *parse_statement_expression(void)
4959 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4961 statement_t *statement = parse_compound_statement();
4962 expression->statement.statement = statement;
4963 expression->base.source_position = statement->base.source_position;
4965 /* find last statement and use its type */
4966 type_t *type = type_void;
4967 const statement_t *stmt = statement->compound.statements;
4969 while (stmt->base.next != NULL)
4970 stmt = stmt->base.next;
4972 if (stmt->kind == STATEMENT_EXPRESSION) {
4973 type = stmt->expression.expression->base.type;
4976 warningf(&expression->base.source_position, "empty statement expression ({})");
4978 expression->base.type = type;
4984 return create_invalid_expression();
4988 * Parse a braced expression.
4990 static expression_t *parse_brace_expression(void)
4993 add_anchor_token(')');
4995 switch(token.type) {
4997 /* gcc extension: a statement expression */
4998 return parse_statement_expression();
5002 return parse_cast();
5004 if(is_typedef_symbol(token.v.symbol)) {
5005 return parse_cast();
5009 expression_t *result = parse_expression();
5010 rem_anchor_token(')');
5015 return create_invalid_expression();
5018 static expression_t *parse_function_keyword(void)
5023 if (current_function == NULL) {
5024 errorf(HERE, "'__func__' used outside of a function");
5027 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5028 expression->base.type = type_char_ptr;
5029 expression->funcname.kind = FUNCNAME_FUNCTION;
5034 static expression_t *parse_pretty_function_keyword(void)
5036 eat(T___PRETTY_FUNCTION__);
5038 if (current_function == NULL) {
5039 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5042 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5043 expression->base.type = type_char_ptr;
5044 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5049 static expression_t *parse_funcsig_keyword(void)
5053 if (current_function == NULL) {
5054 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5057 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5058 expression->base.type = type_char_ptr;
5059 expression->funcname.kind = FUNCNAME_FUNCSIG;
5064 static expression_t *parse_funcdname_keyword(void)
5066 eat(T___FUNCDNAME__);
5068 if (current_function == NULL) {
5069 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5072 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5073 expression->base.type = type_char_ptr;
5074 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5079 static designator_t *parse_designator(void)
5081 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5082 result->source_position = *HERE;
5084 if(token.type != T_IDENTIFIER) {
5085 parse_error_expected("while parsing member designator",
5089 result->symbol = token.v.symbol;
5092 designator_t *last_designator = result;
5094 if(token.type == '.') {
5096 if(token.type != T_IDENTIFIER) {
5097 parse_error_expected("while parsing member designator",
5101 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5102 designator->source_position = *HERE;
5103 designator->symbol = token.v.symbol;
5106 last_designator->next = designator;
5107 last_designator = designator;
5110 if(token.type == '[') {
5112 add_anchor_token(']');
5113 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5114 designator->source_position = *HERE;
5115 designator->array_index = parse_expression();
5116 rem_anchor_token(']');
5118 if(designator->array_index == NULL) {
5122 last_designator->next = designator;
5123 last_designator = designator;
5135 * Parse the __builtin_offsetof() expression.
5137 static expression_t *parse_offsetof(void)
5139 eat(T___builtin_offsetof);
5141 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5142 expression->base.type = type_size_t;
5145 add_anchor_token(',');
5146 type_t *type = parse_typename();
5147 rem_anchor_token(',');
5149 add_anchor_token(')');
5150 designator_t *designator = parse_designator();
5151 rem_anchor_token(')');
5154 expression->offsetofe.type = type;
5155 expression->offsetofe.designator = designator;
5158 memset(&path, 0, sizeof(path));
5159 path.top_type = type;
5160 path.path = NEW_ARR_F(type_path_entry_t, 0);
5162 descend_into_subtype(&path);
5164 if(!walk_designator(&path, designator, true)) {
5165 return create_invalid_expression();
5168 DEL_ARR_F(path.path);
5172 return create_invalid_expression();
5176 * Parses a _builtin_va_start() expression.
5178 static expression_t *parse_va_start(void)
5180 eat(T___builtin_va_start);
5182 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5185 add_anchor_token(',');
5186 expression->va_starte.ap = parse_assignment_expression();
5187 rem_anchor_token(',');
5189 expression_t *const expr = parse_assignment_expression();
5190 if (expr->kind == EXPR_REFERENCE) {
5191 declaration_t *const decl = expr->reference.declaration;
5193 return create_invalid_expression();
5194 if (decl->parent_scope == ¤t_function->scope &&
5195 decl->next == NULL) {
5196 expression->va_starte.parameter = decl;
5201 errorf(&expr->base.source_position,
5202 "second argument of 'va_start' must be last parameter of the current function");
5204 return create_invalid_expression();
5208 * Parses a _builtin_va_arg() expression.
5210 static expression_t *parse_va_arg(void)
5212 eat(T___builtin_va_arg);
5214 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5217 expression->va_arge.ap = parse_assignment_expression();
5219 expression->base.type = parse_typename();
5224 return create_invalid_expression();
5227 static expression_t *parse_builtin_symbol(void)
5229 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5231 symbol_t *symbol = token.v.symbol;
5233 expression->builtin_symbol.symbol = symbol;
5236 type_t *type = get_builtin_symbol_type(symbol);
5237 type = automatic_type_conversion(type);
5239 expression->base.type = type;
5244 * Parses a __builtin_constant() expression.
5246 static expression_t *parse_builtin_constant(void)
5248 eat(T___builtin_constant_p);
5250 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5253 add_anchor_token(')');
5254 expression->builtin_constant.value = parse_assignment_expression();
5255 rem_anchor_token(')');
5257 expression->base.type = type_int;
5261 return create_invalid_expression();
5265 * Parses a __builtin_prefetch() expression.
5267 static expression_t *parse_builtin_prefetch(void)
5269 eat(T___builtin_prefetch);
5271 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5274 add_anchor_token(')');
5275 expression->builtin_prefetch.adr = parse_assignment_expression();
5276 if (token.type == ',') {
5278 expression->builtin_prefetch.rw = parse_assignment_expression();
5280 if (token.type == ',') {
5282 expression->builtin_prefetch.locality = parse_assignment_expression();
5284 rem_anchor_token(')');
5286 expression->base.type = type_void;
5290 return create_invalid_expression();
5294 * Parses a __builtin_is_*() compare expression.
5296 static expression_t *parse_compare_builtin(void)
5298 expression_t *expression;
5300 switch(token.type) {
5301 case T___builtin_isgreater:
5302 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5304 case T___builtin_isgreaterequal:
5305 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5307 case T___builtin_isless:
5308 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5310 case T___builtin_islessequal:
5311 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5313 case T___builtin_islessgreater:
5314 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5316 case T___builtin_isunordered:
5317 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5320 internal_errorf(HERE, "invalid compare builtin found");
5323 expression->base.source_position = *HERE;
5327 expression->binary.left = parse_assignment_expression();
5329 expression->binary.right = parse_assignment_expression();
5332 type_t *const orig_type_left = expression->binary.left->base.type;
5333 type_t *const orig_type_right = expression->binary.right->base.type;
5335 type_t *const type_left = skip_typeref(orig_type_left);
5336 type_t *const type_right = skip_typeref(orig_type_right);
5337 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5338 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5339 type_error_incompatible("invalid operands in comparison",
5340 &expression->base.source_position, orig_type_left, orig_type_right);
5343 semantic_comparison(&expression->binary);
5348 return create_invalid_expression();
5352 * Parses a __builtin_expect() expression.
5354 static expression_t *parse_builtin_expect(void)
5356 eat(T___builtin_expect);
5358 expression_t *expression
5359 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5362 expression->binary.left = parse_assignment_expression();
5364 expression->binary.right = parse_constant_expression();
5367 expression->base.type = expression->binary.left->base.type;
5371 return create_invalid_expression();
5375 * Parses a MS assume() expression.
5377 static expression_t *parse_assume(void) {
5380 expression_t *expression
5381 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5384 add_anchor_token(')');
5385 expression->unary.value = parse_assignment_expression();
5386 rem_anchor_token(')');
5389 expression->base.type = type_void;
5392 return create_invalid_expression();
5396 * Parse a microsoft __noop expression.
5398 static expression_t *parse_noop_expression(void) {
5399 source_position_t source_position = *HERE;
5402 if (token.type == '(') {
5403 /* parse arguments */
5405 add_anchor_token(')');
5406 add_anchor_token(',');
5408 if(token.type != ')') {
5410 (void)parse_assignment_expression();
5411 if(token.type != ',')
5417 rem_anchor_token(',');
5418 rem_anchor_token(')');
5421 /* the result is a (int)0 */
5422 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5423 cnst->base.source_position = source_position;
5424 cnst->base.type = type_int;
5425 cnst->conste.v.int_value = 0;
5426 cnst->conste.is_ms_noop = true;
5431 return create_invalid_expression();
5435 * Parses a primary expression.
5437 static expression_t *parse_primary_expression(void)
5439 switch (token.type) {
5440 case T_INTEGER: return parse_int_const();
5441 case T_CHARACTER_CONSTANT: return parse_character_constant();
5442 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5443 case T_FLOATINGPOINT: return parse_float_const();
5444 case T_STRING_LITERAL:
5445 case T_WIDE_STRING_LITERAL: return parse_string_const();
5446 case T_IDENTIFIER: return parse_reference();
5447 case T___FUNCTION__:
5448 case T___func__: return parse_function_keyword();
5449 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5450 case T___FUNCSIG__: return parse_funcsig_keyword();
5451 case T___FUNCDNAME__: return parse_funcdname_keyword();
5452 case T___builtin_offsetof: return parse_offsetof();
5453 case T___builtin_va_start: return parse_va_start();
5454 case T___builtin_va_arg: return parse_va_arg();
5455 case T___builtin_expect: return parse_builtin_expect();
5456 case T___builtin_alloca:
5457 case T___builtin_nan:
5458 case T___builtin_nand:
5459 case T___builtin_nanf:
5460 case T___builtin_va_end: return parse_builtin_symbol();
5461 case T___builtin_isgreater:
5462 case T___builtin_isgreaterequal:
5463 case T___builtin_isless:
5464 case T___builtin_islessequal:
5465 case T___builtin_islessgreater:
5466 case T___builtin_isunordered: return parse_compare_builtin();
5467 case T___builtin_constant_p: return parse_builtin_constant();
5468 case T___builtin_prefetch: return parse_builtin_prefetch();
5469 case T__assume: return parse_assume();
5471 case '(': return parse_brace_expression();
5472 case T___noop: return parse_noop_expression();
5475 errorf(HERE, "unexpected token %K, expected an expression", &token);
5476 return create_invalid_expression();
5480 * Check if the expression has the character type and issue a warning then.
5482 static void check_for_char_index_type(const expression_t *expression) {
5483 type_t *const type = expression->base.type;
5484 const type_t *const base_type = skip_typeref(type);
5486 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5487 warning.char_subscripts) {
5488 warningf(&expression->base.source_position,
5489 "array subscript has type '%T'", type);
5493 static expression_t *parse_array_expression(unsigned precedence,
5499 add_anchor_token(']');
5501 expression_t *inside = parse_expression();
5503 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5505 array_access_expression_t *array_access = &expression->array_access;
5507 type_t *const orig_type_left = left->base.type;
5508 type_t *const orig_type_inside = inside->base.type;
5510 type_t *const type_left = skip_typeref(orig_type_left);
5511 type_t *const type_inside = skip_typeref(orig_type_inside);
5513 type_t *return_type;
5514 if (is_type_pointer(type_left)) {
5515 return_type = type_left->pointer.points_to;
5516 array_access->array_ref = left;
5517 array_access->index = inside;
5518 check_for_char_index_type(inside);
5519 } else if (is_type_pointer(type_inside)) {
5520 return_type = type_inside->pointer.points_to;
5521 array_access->array_ref = inside;
5522 array_access->index = left;
5523 array_access->flipped = true;
5524 check_for_char_index_type(left);
5526 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5528 "array access on object with non-pointer types '%T', '%T'",
5529 orig_type_left, orig_type_inside);
5531 return_type = type_error_type;
5532 array_access->array_ref = create_invalid_expression();
5535 rem_anchor_token(']');
5536 if(token.type != ']') {
5537 parse_error_expected("Problem while parsing array access", ']', 0);
5542 return_type = automatic_type_conversion(return_type);
5543 expression->base.type = return_type;
5548 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5550 expression_t *tp_expression = allocate_expression_zero(kind);
5551 tp_expression->base.type = type_size_t;
5553 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5555 add_anchor_token(')');
5556 tp_expression->typeprop.type = parse_typename();
5557 rem_anchor_token(')');
5560 expression_t *expression = parse_sub_expression(precedence);
5561 expression->base.type = revert_automatic_type_conversion(expression);
5563 tp_expression->typeprop.type = expression->base.type;
5564 tp_expression->typeprop.tp_expression = expression;
5567 return tp_expression;
5569 return create_invalid_expression();
5572 static expression_t *parse_sizeof(unsigned precedence)
5575 return parse_typeprop(EXPR_SIZEOF, precedence);
5578 static expression_t *parse_alignof(unsigned precedence)
5581 return parse_typeprop(EXPR_SIZEOF, precedence);
5584 static expression_t *parse_select_expression(unsigned precedence,
5585 expression_t *compound)
5588 assert(token.type == '.' || token.type == T_MINUSGREATER);
5590 bool is_pointer = (token.type == T_MINUSGREATER);
5593 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5594 select->select.compound = compound;
5596 if(token.type != T_IDENTIFIER) {
5597 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5600 symbol_t *symbol = token.v.symbol;
5601 select->select.symbol = symbol;
5604 type_t *const orig_type = compound->base.type;
5605 type_t *const type = skip_typeref(orig_type);
5607 type_t *type_left = type;
5609 if (!is_type_pointer(type)) {
5610 if (is_type_valid(type)) {
5611 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5613 return create_invalid_expression();
5615 type_left = type->pointer.points_to;
5617 type_left = skip_typeref(type_left);
5619 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5620 type_left->kind != TYPE_COMPOUND_UNION) {
5621 if (is_type_valid(type_left)) {
5622 errorf(HERE, "request for member '%Y' in something not a struct or "
5623 "union, but '%T'", symbol, type_left);
5625 return create_invalid_expression();
5628 declaration_t *const declaration = type_left->compound.declaration;
5630 if(!declaration->init.is_defined) {
5631 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5633 return create_invalid_expression();
5636 declaration_t *iter = find_compound_entry(declaration, symbol);
5638 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5639 return create_invalid_expression();
5642 /* we always do the auto-type conversions; the & and sizeof parser contains
5643 * code to revert this! */
5644 type_t *expression_type = automatic_type_conversion(iter->type);
5646 select->select.compound_entry = iter;
5647 select->base.type = expression_type;
5649 if(expression_type->kind == TYPE_BITFIELD) {
5650 expression_t *extract
5651 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5652 extract->unary.value = select;
5653 extract->base.type = expression_type->bitfield.base;
5662 * Parse a call expression, ie. expression '( ... )'.
5664 * @param expression the function address
5666 static expression_t *parse_call_expression(unsigned precedence,
5667 expression_t *expression)
5670 expression_t *result = allocate_expression_zero(EXPR_CALL);
5671 result->base.source_position = expression->base.source_position;
5673 call_expression_t *call = &result->call;
5674 call->function = expression;
5676 type_t *const orig_type = expression->base.type;
5677 type_t *const type = skip_typeref(orig_type);
5679 function_type_t *function_type = NULL;
5680 if (is_type_pointer(type)) {
5681 type_t *const to_type = skip_typeref(type->pointer.points_to);
5683 if (is_type_function(to_type)) {
5684 function_type = &to_type->function;
5685 call->base.type = function_type->return_type;
5689 if (function_type == NULL && is_type_valid(type)) {
5690 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5693 /* parse arguments */
5695 add_anchor_token(')');
5696 add_anchor_token(',');
5698 if(token.type != ')') {
5699 call_argument_t *last_argument = NULL;
5702 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5704 argument->expression = parse_assignment_expression();
5705 if(last_argument == NULL) {
5706 call->arguments = argument;
5708 last_argument->next = argument;
5710 last_argument = argument;
5712 if(token.type != ',')
5717 rem_anchor_token(',');
5718 rem_anchor_token(')');
5721 if(function_type != NULL) {
5722 function_parameter_t *parameter = function_type->parameters;
5723 call_argument_t *argument = call->arguments;
5724 for( ; parameter != NULL && argument != NULL;
5725 parameter = parameter->next, argument = argument->next) {
5726 type_t *expected_type = parameter->type;
5727 /* TODO report scope in error messages */
5728 expression_t *const arg_expr = argument->expression;
5729 type_t *const res_type = semantic_assign(expected_type, arg_expr,
5731 &arg_expr->base.source_position);
5732 if (res_type == NULL) {
5733 /* TODO improve error message */
5734 errorf(&arg_expr->base.source_position,
5735 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5736 arg_expr, arg_expr->base.type, expected_type);
5738 argument->expression = create_implicit_cast(argument->expression, expected_type);
5741 /* too few parameters */
5742 if(parameter != NULL) {
5743 errorf(HERE, "too few arguments to function '%E'", expression);
5744 } else if(argument != NULL) {
5745 /* too many parameters */
5746 if(!function_type->variadic
5747 && !function_type->unspecified_parameters) {
5748 errorf(HERE, "too many arguments to function '%E'", expression);
5750 /* do default promotion */
5751 for( ; argument != NULL; argument = argument->next) {
5752 type_t *type = argument->expression->base.type;
5754 type = skip_typeref(type);
5755 if(is_type_integer(type)) {
5756 type = promote_integer(type);
5757 } else if(type == type_float) {
5761 argument->expression
5762 = create_implicit_cast(argument->expression, type);
5765 check_format(&result->call);
5768 check_format(&result->call);
5774 return create_invalid_expression();
5777 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5779 static bool same_compound_type(const type_t *type1, const type_t *type2)
5782 is_type_compound(type1) &&
5783 type1->kind == type2->kind &&
5784 type1->compound.declaration == type2->compound.declaration;
5788 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5790 * @param expression the conditional expression
5792 static expression_t *parse_conditional_expression(unsigned precedence,
5793 expression_t *expression)
5796 add_anchor_token(':');
5798 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5800 conditional_expression_t *conditional = &result->conditional;
5801 conditional->condition = expression;
5804 type_t *const condition_type_orig = expression->base.type;
5805 type_t *const condition_type = skip_typeref(condition_type_orig);
5806 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5807 type_error("expected a scalar type in conditional condition",
5808 &expression->base.source_position, condition_type_orig);
5811 expression_t *true_expression = parse_expression();
5812 rem_anchor_token(':');
5814 expression_t *false_expression = parse_sub_expression(precedence);
5816 type_t *const orig_true_type = true_expression->base.type;
5817 type_t *const orig_false_type = false_expression->base.type;
5818 type_t *const true_type = skip_typeref(orig_true_type);
5819 type_t *const false_type = skip_typeref(orig_false_type);
5822 type_t *result_type;
5823 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5824 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5825 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5826 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5827 warningf(&expression->base.source_position,
5828 "ISO C forbids conditional expression with only one void side");
5830 result_type = type_void;
5831 } else if (is_type_arithmetic(true_type)
5832 && is_type_arithmetic(false_type)) {
5833 result_type = semantic_arithmetic(true_type, false_type);
5835 true_expression = create_implicit_cast(true_expression, result_type);
5836 false_expression = create_implicit_cast(false_expression, result_type);
5838 conditional->true_expression = true_expression;
5839 conditional->false_expression = false_expression;
5840 conditional->base.type = result_type;
5841 } else if (same_compound_type(true_type, false_type)) {
5842 /* just take 1 of the 2 types */
5843 result_type = true_type;
5844 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5845 type_t *pointer_type;
5847 expression_t *other_expression;
5848 if (is_type_pointer(true_type)) {
5849 pointer_type = true_type;
5850 other_type = false_type;
5851 other_expression = false_expression;
5853 pointer_type = false_type;
5854 other_type = true_type;
5855 other_expression = true_expression;
5858 if(is_type_pointer(other_type)) {
5859 if(!pointers_compatible(true_type, false_type)) {
5860 warningf(&expression->base.source_position,
5861 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5863 result_type = true_type;
5864 } else if(is_null_pointer_constant(other_expression)) {
5865 result_type = pointer_type;
5866 } else if(is_type_integer(other_type)) {
5867 warningf(&expression->base.source_position,
5868 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5869 result_type = pointer_type;
5871 type_error_incompatible("while parsing conditional",
5872 &expression->base.source_position, true_type, false_type);
5873 result_type = type_error_type;
5876 /* TODO: one pointer to void*, other some pointer */
5878 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5879 type_error_incompatible("while parsing conditional",
5880 &expression->base.source_position, true_type,
5883 result_type = type_error_type;
5886 conditional->true_expression
5887 = create_implicit_cast(true_expression, result_type);
5888 conditional->false_expression
5889 = create_implicit_cast(false_expression, result_type);
5890 conditional->base.type = result_type;
5893 return create_invalid_expression();
5897 * Parse an extension expression.
5899 static expression_t *parse_extension(unsigned precedence)
5901 eat(T___extension__);
5903 /* TODO enable extensions */
5904 expression_t *expression = parse_sub_expression(precedence);
5905 /* TODO disable extensions */
5910 * Parse a __builtin_classify_type() expression.
5912 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5914 eat(T___builtin_classify_type);
5916 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5917 result->base.type = type_int;
5920 add_anchor_token(')');
5921 expression_t *expression = parse_sub_expression(precedence);
5922 rem_anchor_token(')');
5924 result->classify_type.type_expression = expression;
5928 return create_invalid_expression();
5931 static void semantic_incdec(unary_expression_t *expression)
5933 type_t *const orig_type = expression->value->base.type;
5934 type_t *const type = skip_typeref(orig_type);
5935 /* TODO !is_type_real && !is_type_pointer */
5936 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5937 if (is_type_valid(type)) {
5938 /* TODO: improve error message */
5939 errorf(HERE, "operation needs an arithmetic or pointer type");
5944 expression->base.type = orig_type;
5947 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5949 type_t *const orig_type = expression->value->base.type;
5950 type_t *const type = skip_typeref(orig_type);
5951 if(!is_type_arithmetic(type)) {
5952 if (is_type_valid(type)) {
5953 /* TODO: improve error message */
5954 errorf(HERE, "operation needs an arithmetic type");
5959 expression->base.type = orig_type;
5962 static void semantic_unexpr_scalar(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_scalar(type)) {
5967 if (is_type_valid(type)) {
5968 errorf(HERE, "operand of ! must be of scalar type");
5973 expression->base.type = orig_type;
5976 static void semantic_unexpr_integer(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_integer(type)) {
5981 if (is_type_valid(type)) {
5982 errorf(HERE, "operand of ~ must be of integer type");
5987 expression->base.type = orig_type;
5990 static void semantic_dereference(unary_expression_t *expression)
5992 type_t *const orig_type = expression->value->base.type;
5993 type_t *const type = skip_typeref(orig_type);
5994 if(!is_type_pointer(type)) {
5995 if (is_type_valid(type)) {
5996 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6001 type_t *result_type = type->pointer.points_to;
6002 result_type = automatic_type_conversion(result_type);
6003 expression->base.type = result_type;
6007 * Check the semantic of the address taken expression.
6009 static void semantic_take_addr(unary_expression_t *expression)
6011 expression_t *value = expression->value;
6012 value->base.type = revert_automatic_type_conversion(value);
6014 type_t *orig_type = value->base.type;
6015 if(!is_type_valid(orig_type))
6018 if(value->kind == EXPR_REFERENCE) {
6019 declaration_t *const declaration = value->reference.declaration;
6020 if(declaration != NULL) {
6021 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6022 errorf(&expression->base.source_position,
6023 "address of register variable '%Y' requested",
6024 declaration->symbol);
6026 declaration->address_taken = 1;
6030 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6033 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6034 static expression_t *parse_##unexpression_type(unsigned precedence) \
6038 expression_t *unary_expression \
6039 = allocate_expression_zero(unexpression_type); \
6040 unary_expression->base.source_position = *HERE; \
6041 unary_expression->unary.value = parse_sub_expression(precedence); \
6043 sfunc(&unary_expression->unary); \
6045 return unary_expression; \
6048 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6049 semantic_unexpr_arithmetic)
6050 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6051 semantic_unexpr_arithmetic)
6052 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6053 semantic_unexpr_scalar)
6054 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6055 semantic_dereference)
6056 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6058 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6059 semantic_unexpr_integer)
6060 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6062 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6065 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6067 static expression_t *parse_##unexpression_type(unsigned precedence, \
6068 expression_t *left) \
6070 (void) precedence; \
6073 expression_t *unary_expression \
6074 = allocate_expression_zero(unexpression_type); \
6075 unary_expression->unary.value = left; \
6077 sfunc(&unary_expression->unary); \
6079 return unary_expression; \
6082 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6083 EXPR_UNARY_POSTFIX_INCREMENT,
6085 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6086 EXPR_UNARY_POSTFIX_DECREMENT,
6089 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6091 /* TODO: handle complex + imaginary types */
6093 /* § 6.3.1.8 Usual arithmetic conversions */
6094 if(type_left == type_long_double || type_right == type_long_double) {
6095 return type_long_double;
6096 } else if(type_left == type_double || type_right == type_double) {
6098 } else if(type_left == type_float || type_right == type_float) {
6102 type_right = promote_integer(type_right);
6103 type_left = promote_integer(type_left);
6105 if(type_left == type_right)
6108 bool signed_left = is_type_signed(type_left);
6109 bool signed_right = is_type_signed(type_right);
6110 int rank_left = get_rank(type_left);
6111 int rank_right = get_rank(type_right);
6112 if(rank_left < rank_right) {
6113 if(signed_left == signed_right || !signed_right) {
6119 if(signed_left == signed_right || !signed_left) {
6128 * Check the semantic restrictions for a binary expression.
6130 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6132 expression_t *const left = expression->left;
6133 expression_t *const right = expression->right;
6134 type_t *const orig_type_left = left->base.type;
6135 type_t *const orig_type_right = right->base.type;
6136 type_t *const type_left = skip_typeref(orig_type_left);
6137 type_t *const type_right = skip_typeref(orig_type_right);
6139 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6140 /* TODO: improve error message */
6141 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6142 errorf(HERE, "operation needs arithmetic types");
6147 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6148 expression->left = create_implicit_cast(left, arithmetic_type);
6149 expression->right = create_implicit_cast(right, arithmetic_type);
6150 expression->base.type = arithmetic_type;
6153 static void semantic_shift_op(binary_expression_t *expression)
6155 expression_t *const left = expression->left;
6156 expression_t *const right = expression->right;
6157 type_t *const orig_type_left = left->base.type;
6158 type_t *const orig_type_right = right->base.type;
6159 type_t * type_left = skip_typeref(orig_type_left);
6160 type_t * type_right = skip_typeref(orig_type_right);
6162 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6163 /* TODO: improve error message */
6164 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6165 errorf(HERE, "operation needs integer types");
6170 type_left = promote_integer(type_left);
6171 type_right = promote_integer(type_right);
6173 expression->left = create_implicit_cast(left, type_left);
6174 expression->right = create_implicit_cast(right, type_right);
6175 expression->base.type = type_left;
6178 static void semantic_add(binary_expression_t *expression)
6180 expression_t *const left = expression->left;
6181 expression_t *const right = expression->right;
6182 type_t *const orig_type_left = left->base.type;
6183 type_t *const orig_type_right = right->base.type;
6184 type_t *const type_left = skip_typeref(orig_type_left);
6185 type_t *const type_right = skip_typeref(orig_type_right);
6188 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6189 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6190 expression->left = create_implicit_cast(left, arithmetic_type);
6191 expression->right = create_implicit_cast(right, arithmetic_type);
6192 expression->base.type = arithmetic_type;
6194 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6195 expression->base.type = type_left;
6196 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
6197 expression->base.type = type_right;
6198 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6199 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
6203 static void semantic_sub(binary_expression_t *expression)
6205 expression_t *const left = expression->left;
6206 expression_t *const right = expression->right;
6207 type_t *const orig_type_left = left->base.type;
6208 type_t *const orig_type_right = right->base.type;
6209 type_t *const type_left = skip_typeref(orig_type_left);
6210 type_t *const type_right = skip_typeref(orig_type_right);
6213 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6214 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6215 expression->left = create_implicit_cast(left, arithmetic_type);
6216 expression->right = create_implicit_cast(right, arithmetic_type);
6217 expression->base.type = arithmetic_type;
6219 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6220 expression->base.type = type_left;
6221 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6222 if(!pointers_compatible(type_left, type_right)) {
6224 "pointers to incompatible objects to binary '-' ('%T', '%T')",
6225 orig_type_left, orig_type_right);
6227 expression->base.type = type_ptrdiff_t;
6229 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6230 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6231 orig_type_left, orig_type_right);
6236 * Check the semantics of comparison expressions.
6238 * @param expression The expression to check.
6240 static void semantic_comparison(binary_expression_t *expression)
6242 expression_t *left = expression->left;
6243 expression_t *right = expression->right;
6244 type_t *orig_type_left = left->base.type;
6245 type_t *orig_type_right = right->base.type;
6247 type_t *type_left = skip_typeref(orig_type_left);
6248 type_t *type_right = skip_typeref(orig_type_right);
6250 /* TODO non-arithmetic types */
6251 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6252 if (warning.sign_compare &&
6253 (expression->base.kind != EXPR_BINARY_EQUAL &&
6254 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6255 (is_type_signed(type_left) != is_type_signed(type_right))) {
6256 warningf(&expression->base.source_position,
6257 "comparison between signed and unsigned");
6259 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6260 expression->left = create_implicit_cast(left, arithmetic_type);
6261 expression->right = create_implicit_cast(right, arithmetic_type);
6262 expression->base.type = arithmetic_type;
6263 if (warning.float_equal &&
6264 (expression->base.kind == EXPR_BINARY_EQUAL ||
6265 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6266 is_type_float(arithmetic_type)) {
6267 warningf(&expression->base.source_position,
6268 "comparing floating point with == or != is unsafe");
6270 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6271 /* TODO check compatibility */
6272 } else if (is_type_pointer(type_left)) {
6273 expression->right = create_implicit_cast(right, type_left);
6274 } else if (is_type_pointer(type_right)) {
6275 expression->left = create_implicit_cast(left, type_right);
6276 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6277 type_error_incompatible("invalid operands in comparison",
6278 &expression->base.source_position,
6279 type_left, type_right);
6281 expression->base.type = type_int;
6284 static void semantic_arithmetic_assign(binary_expression_t *expression)
6286 expression_t *left = expression->left;
6287 expression_t *right = expression->right;
6288 type_t *orig_type_left = left->base.type;
6289 type_t *orig_type_right = right->base.type;
6291 type_t *type_left = skip_typeref(orig_type_left);
6292 type_t *type_right = skip_typeref(orig_type_right);
6294 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6295 /* TODO: improve error message */
6296 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6297 errorf(HERE, "operation needs arithmetic types");
6302 /* combined instructions are tricky. We can't create an implicit cast on
6303 * the left side, because we need the uncasted form for the store.
6304 * The ast2firm pass has to know that left_type must be right_type
6305 * for the arithmetic operation and create a cast by itself */
6306 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6307 expression->right = create_implicit_cast(right, arithmetic_type);
6308 expression->base.type = type_left;
6311 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6313 expression_t *const left = expression->left;
6314 expression_t *const right = expression->right;
6315 type_t *const orig_type_left = left->base.type;
6316 type_t *const orig_type_right = right->base.type;
6317 type_t *const type_left = skip_typeref(orig_type_left);
6318 type_t *const type_right = skip_typeref(orig_type_right);
6320 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6321 /* combined instructions are tricky. We can't create an implicit cast on
6322 * the left side, because we need the uncasted form for the store.
6323 * The ast2firm pass has to know that left_type must be right_type
6324 * for the arithmetic operation and create a cast by itself */
6325 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6326 expression->right = create_implicit_cast(right, arithmetic_type);
6327 expression->base.type = type_left;
6328 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6329 expression->base.type = type_left;
6330 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6331 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6336 * Check the semantic restrictions of a logical expression.
6338 static void semantic_logical_op(binary_expression_t *expression)
6340 expression_t *const left = expression->left;
6341 expression_t *const right = expression->right;
6342 type_t *const orig_type_left = left->base.type;
6343 type_t *const orig_type_right = right->base.type;
6344 type_t *const type_left = skip_typeref(orig_type_left);
6345 type_t *const type_right = skip_typeref(orig_type_right);
6347 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6348 /* TODO: improve error message */
6349 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6350 errorf(HERE, "operation needs scalar types");
6355 expression->base.type = type_int;
6359 * Checks if a compound type has constant fields.
6361 static bool has_const_fields(const compound_type_t *type)
6363 const scope_t *scope = &type->declaration->scope;
6364 const declaration_t *declaration = scope->declarations;
6366 for (; declaration != NULL; declaration = declaration->next) {
6367 if (declaration->namespc != NAMESPACE_NORMAL)
6370 const type_t *decl_type = skip_typeref(declaration->type);
6371 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6379 * Check the semantic restrictions of a binary assign expression.
6381 static void semantic_binexpr_assign(binary_expression_t *expression)
6383 expression_t *left = expression->left;
6384 type_t *orig_type_left = left->base.type;
6386 type_t *type_left = revert_automatic_type_conversion(left);
6387 type_left = skip_typeref(orig_type_left);
6389 /* must be a modifiable lvalue */
6390 if (is_type_array(type_left)) {
6391 errorf(HERE, "cannot assign to arrays ('%E')", left);
6394 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6395 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6399 if(is_type_incomplete(type_left)) {
6401 "left-hand side of assignment '%E' has incomplete type '%T'",
6402 left, orig_type_left);
6405 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6406 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6407 left, orig_type_left);
6411 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6412 "assignment", &left->base.source_position);
6413 if (res_type == NULL) {
6414 errorf(&expression->base.source_position,
6415 "cannot assign to '%T' from '%T'",
6416 orig_type_left, expression->right->base.type);
6418 expression->right = create_implicit_cast(expression->right, res_type);
6421 expression->base.type = orig_type_left;
6425 * Determine if the outermost operation (or parts thereof) of the given
6426 * expression has no effect in order to generate a warning about this fact.
6427 * Therefore in some cases this only examines some of the operands of the
6428 * expression (see comments in the function and examples below).
6430 * f() + 23; // warning, because + has no effect
6431 * x || f(); // no warning, because x controls execution of f()
6432 * x ? y : f(); // warning, because y has no effect
6433 * (void)x; // no warning to be able to suppress the warning
6434 * This function can NOT be used for an "expression has definitely no effect"-
6436 static bool expression_has_effect(const expression_t *const expr)
6438 switch (expr->kind) {
6439 case EXPR_UNKNOWN: break;
6440 case EXPR_INVALID: return true; /* do NOT warn */
6441 case EXPR_REFERENCE: return false;
6442 /* suppress the warning for microsoft __noop operations */
6443 case EXPR_CONST: return expr->conste.is_ms_noop;
6444 case EXPR_CHARACTER_CONSTANT: return false;
6445 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6446 case EXPR_STRING_LITERAL: return false;
6447 case EXPR_WIDE_STRING_LITERAL: return false;
6450 const call_expression_t *const call = &expr->call;
6451 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6454 switch (call->function->builtin_symbol.symbol->ID) {
6455 case T___builtin_va_end: return true;
6456 default: return false;
6460 /* Generate the warning if either the left or right hand side of a
6461 * conditional expression has no effect */
6462 case EXPR_CONDITIONAL: {
6463 const conditional_expression_t *const cond = &expr->conditional;
6465 expression_has_effect(cond->true_expression) &&
6466 expression_has_effect(cond->false_expression);
6469 case EXPR_SELECT: return false;
6470 case EXPR_ARRAY_ACCESS: return false;
6471 case EXPR_SIZEOF: return false;
6472 case EXPR_CLASSIFY_TYPE: return false;
6473 case EXPR_ALIGNOF: return false;
6475 case EXPR_FUNCNAME: return false;
6476 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6477 case EXPR_BUILTIN_CONSTANT_P: return false;
6478 case EXPR_BUILTIN_PREFETCH: return true;
6479 case EXPR_OFFSETOF: return false;
6480 case EXPR_VA_START: return true;
6481 case EXPR_VA_ARG: return true;
6482 case EXPR_STATEMENT: return true; // TODO
6483 case EXPR_COMPOUND_LITERAL: return false;
6485 case EXPR_UNARY_NEGATE: return false;
6486 case EXPR_UNARY_PLUS: return false;
6487 case EXPR_UNARY_BITWISE_NEGATE: return false;
6488 case EXPR_UNARY_NOT: return false;
6489 case EXPR_UNARY_DEREFERENCE: return false;
6490 case EXPR_UNARY_TAKE_ADDRESS: return false;
6491 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6492 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6493 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6494 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6496 /* Treat void casts as if they have an effect in order to being able to
6497 * suppress the warning */
6498 case EXPR_UNARY_CAST: {
6499 type_t *const type = skip_typeref(expr->base.type);
6500 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6503 case EXPR_UNARY_CAST_IMPLICIT: return true;
6504 case EXPR_UNARY_ASSUME: return true;
6505 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6507 case EXPR_BINARY_ADD: return false;
6508 case EXPR_BINARY_SUB: return false;
6509 case EXPR_BINARY_MUL: return false;
6510 case EXPR_BINARY_DIV: return false;
6511 case EXPR_BINARY_MOD: return false;
6512 case EXPR_BINARY_EQUAL: return false;
6513 case EXPR_BINARY_NOTEQUAL: return false;
6514 case EXPR_BINARY_LESS: return false;
6515 case EXPR_BINARY_LESSEQUAL: return false;
6516 case EXPR_BINARY_GREATER: return false;
6517 case EXPR_BINARY_GREATEREQUAL: return false;
6518 case EXPR_BINARY_BITWISE_AND: return false;
6519 case EXPR_BINARY_BITWISE_OR: return false;
6520 case EXPR_BINARY_BITWISE_XOR: return false;
6521 case EXPR_BINARY_SHIFTLEFT: return false;
6522 case EXPR_BINARY_SHIFTRIGHT: return false;
6523 case EXPR_BINARY_ASSIGN: return true;
6524 case EXPR_BINARY_MUL_ASSIGN: return true;
6525 case EXPR_BINARY_DIV_ASSIGN: return true;
6526 case EXPR_BINARY_MOD_ASSIGN: return true;
6527 case EXPR_BINARY_ADD_ASSIGN: return true;
6528 case EXPR_BINARY_SUB_ASSIGN: return true;
6529 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6530 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6531 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6532 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6533 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6535 /* Only examine the right hand side of && and ||, because the left hand
6536 * side already has the effect of controlling the execution of the right
6538 case EXPR_BINARY_LOGICAL_AND:
6539 case EXPR_BINARY_LOGICAL_OR:
6540 /* Only examine the right hand side of a comma expression, because the left
6541 * hand side has a separate warning */
6542 case EXPR_BINARY_COMMA:
6543 return expression_has_effect(expr->binary.right);
6545 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6546 case EXPR_BINARY_ISGREATER: return false;
6547 case EXPR_BINARY_ISGREATEREQUAL: return false;
6548 case EXPR_BINARY_ISLESS: return false;
6549 case EXPR_BINARY_ISLESSEQUAL: return false;
6550 case EXPR_BINARY_ISLESSGREATER: return false;
6551 case EXPR_BINARY_ISUNORDERED: return false;
6554 internal_errorf(HERE, "unexpected expression");
6557 static void semantic_comma(binary_expression_t *expression)
6559 if (warning.unused_value) {
6560 const expression_t *const left = expression->left;
6561 if (!expression_has_effect(left)) {
6562 warningf(&left->base.source_position,
6563 "left-hand operand of comma expression has no effect");
6566 expression->base.type = expression->right->base.type;
6569 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6570 static expression_t *parse_##binexpression_type(unsigned precedence, \
6571 expression_t *left) \
6574 source_position_t pos = *HERE; \
6576 expression_t *right = parse_sub_expression(precedence + lr); \
6578 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6579 binexpr->base.source_position = pos; \
6580 binexpr->binary.left = left; \
6581 binexpr->binary.right = right; \
6582 sfunc(&binexpr->binary); \
6587 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6588 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6589 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6590 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6591 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6592 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6593 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6594 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6595 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6597 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6598 semantic_comparison, 1)
6599 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6600 semantic_comparison, 1)
6601 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6602 semantic_comparison, 1)
6603 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6604 semantic_comparison, 1)
6606 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6607 semantic_binexpr_arithmetic, 1)
6608 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6609 semantic_binexpr_arithmetic, 1)
6610 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6611 semantic_binexpr_arithmetic, 1)
6612 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6613 semantic_logical_op, 1)
6614 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6615 semantic_logical_op, 1)
6616 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6617 semantic_shift_op, 1)
6618 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6619 semantic_shift_op, 1)
6620 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6621 semantic_arithmetic_addsubb_assign, 0)
6622 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6623 semantic_arithmetic_addsubb_assign, 0)
6624 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6625 semantic_arithmetic_assign, 0)
6626 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6627 semantic_arithmetic_assign, 0)
6628 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6629 semantic_arithmetic_assign, 0)
6630 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6631 semantic_arithmetic_assign, 0)
6632 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6633 semantic_arithmetic_assign, 0)
6634 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6635 semantic_arithmetic_assign, 0)
6636 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6637 semantic_arithmetic_assign, 0)
6638 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6639 semantic_arithmetic_assign, 0)
6641 static expression_t *parse_sub_expression(unsigned precedence)
6643 if(token.type < 0) {
6644 return expected_expression_error();
6647 expression_parser_function_t *parser
6648 = &expression_parsers[token.type];
6649 source_position_t source_position = token.source_position;
6652 if(parser->parser != NULL) {
6653 left = parser->parser(parser->precedence);
6655 left = parse_primary_expression();
6657 assert(left != NULL);
6658 left->base.source_position = source_position;
6661 if(token.type < 0) {
6662 return expected_expression_error();
6665 parser = &expression_parsers[token.type];
6666 if(parser->infix_parser == NULL)
6668 if(parser->infix_precedence < precedence)
6671 left = parser->infix_parser(parser->infix_precedence, left);
6673 assert(left != NULL);
6674 assert(left->kind != EXPR_UNKNOWN);
6675 left->base.source_position = source_position;
6682 * Parse an expression.
6684 static expression_t *parse_expression(void)
6686 return parse_sub_expression(1);
6690 * Register a parser for a prefix-like operator with given precedence.
6692 * @param parser the parser function
6693 * @param token_type the token type of the prefix token
6694 * @param precedence the precedence of the operator
6696 static void register_expression_parser(parse_expression_function parser,
6697 int token_type, unsigned precedence)
6699 expression_parser_function_t *entry = &expression_parsers[token_type];
6701 if(entry->parser != NULL) {
6702 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6703 panic("trying to register multiple expression parsers for a token");
6705 entry->parser = parser;
6706 entry->precedence = precedence;
6710 * Register a parser for an infix operator with given precedence.
6712 * @param parser the parser function
6713 * @param token_type the token type of the infix operator
6714 * @param precedence the precedence of the operator
6716 static void register_infix_parser(parse_expression_infix_function parser,
6717 int token_type, unsigned precedence)
6719 expression_parser_function_t *entry = &expression_parsers[token_type];
6721 if(entry->infix_parser != NULL) {
6722 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6723 panic("trying to register multiple infix expression parsers for a "
6726 entry->infix_parser = parser;
6727 entry->infix_precedence = precedence;
6731 * Initialize the expression parsers.
6733 static void init_expression_parsers(void)
6735 memset(&expression_parsers, 0, sizeof(expression_parsers));
6737 register_infix_parser(parse_array_expression, '[', 30);
6738 register_infix_parser(parse_call_expression, '(', 30);
6739 register_infix_parser(parse_select_expression, '.', 30);
6740 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6741 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6743 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6746 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6747 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6748 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6749 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6750 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6751 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6752 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6753 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6754 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6755 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6756 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6757 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6758 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6759 T_EXCLAMATIONMARKEQUAL, 13);
6760 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6761 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6762 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6763 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6764 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6765 register_infix_parser(parse_conditional_expression, '?', 7);
6766 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6767 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6768 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6769 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6770 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6771 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6772 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6773 T_LESSLESSEQUAL, 2);
6774 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6775 T_GREATERGREATEREQUAL, 2);
6776 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6778 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6780 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6783 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6785 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6786 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6787 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6788 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6789 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6790 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6791 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6793 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6795 register_expression_parser(parse_sizeof, T_sizeof, 25);
6796 register_expression_parser(parse_alignof, T___alignof__, 25);
6797 register_expression_parser(parse_extension, T___extension__, 25);
6798 register_expression_parser(parse_builtin_classify_type,
6799 T___builtin_classify_type, 25);
6803 * Parse a asm statement constraints specification.
6805 static asm_constraint_t *parse_asm_constraints(void)
6807 asm_constraint_t *result = NULL;
6808 asm_constraint_t *last = NULL;
6810 while(token.type == T_STRING_LITERAL || token.type == '[') {
6811 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6812 memset(constraint, 0, sizeof(constraint[0]));
6814 if(token.type == '[') {
6816 if(token.type != T_IDENTIFIER) {
6817 parse_error_expected("while parsing asm constraint",
6821 constraint->symbol = token.v.symbol;
6826 constraint->constraints = parse_string_literals();
6828 constraint->expression = parse_expression();
6832 last->next = constraint;
6834 result = constraint;
6838 if(token.type != ',')
6849 * Parse a asm statement clobber specification.
6851 static asm_clobber_t *parse_asm_clobbers(void)
6853 asm_clobber_t *result = NULL;
6854 asm_clobber_t *last = NULL;
6856 while(token.type == T_STRING_LITERAL) {
6857 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6858 clobber->clobber = parse_string_literals();
6861 last->next = clobber;
6867 if(token.type != ',')
6876 * Parse an asm statement.
6878 static statement_t *parse_asm_statement(void)
6882 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6883 statement->base.source_position = token.source_position;
6885 asm_statement_t *asm_statement = &statement->asms;
6887 if(token.type == T_volatile) {
6889 asm_statement->is_volatile = true;
6893 add_anchor_token(')');
6894 add_anchor_token(':');
6895 asm_statement->asm_text = parse_string_literals();
6897 if(token.type != ':') {
6898 rem_anchor_token(':');
6903 asm_statement->inputs = parse_asm_constraints();
6904 if(token.type != ':') {
6905 rem_anchor_token(':');
6910 asm_statement->outputs = parse_asm_constraints();
6911 if(token.type != ':') {
6912 rem_anchor_token(':');
6915 rem_anchor_token(':');
6918 asm_statement->clobbers = parse_asm_clobbers();
6921 rem_anchor_token(')');
6926 return create_invalid_statement();
6930 * Parse a case statement.
6932 static statement_t *parse_case_statement(void)
6936 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6938 statement->base.source_position = token.source_position;
6939 statement->case_label.expression = parse_expression();
6941 if (c_mode & _GNUC) {
6942 if (token.type == T_DOTDOTDOT) {
6944 statement->case_label.end_range = parse_expression();
6950 if (! is_constant_expression(statement->case_label.expression)) {
6951 errorf(&statement->base.source_position,
6952 "case label does not reduce to an integer constant");
6954 /* TODO: check if the case label is already known */
6955 if (current_switch != NULL) {
6956 /* link all cases into the switch statement */
6957 if (current_switch->last_case == NULL) {
6958 current_switch->first_case =
6959 current_switch->last_case = &statement->case_label;
6961 current_switch->last_case->next = &statement->case_label;
6964 errorf(&statement->base.source_position,
6965 "case label not within a switch statement");
6968 statement->case_label.statement = parse_statement();
6972 return create_invalid_statement();
6976 * Finds an existing default label of a switch statement.
6978 static case_label_statement_t *
6979 find_default_label(const switch_statement_t *statement)
6981 case_label_statement_t *label = statement->first_case;
6982 for ( ; label != NULL; label = label->next) {
6983 if (label->expression == NULL)
6990 * Parse a default statement.
6992 static statement_t *parse_default_statement(void)
6996 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6998 statement->base.source_position = token.source_position;
7001 if (current_switch != NULL) {
7002 const case_label_statement_t *def_label = find_default_label(current_switch);
7003 if (def_label != NULL) {
7004 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7005 &def_label->base.source_position);
7007 /* link all cases into the switch statement */
7008 if (current_switch->last_case == NULL) {
7009 current_switch->first_case =
7010 current_switch->last_case = &statement->case_label;
7012 current_switch->last_case->next = &statement->case_label;
7016 errorf(&statement->base.source_position,
7017 "'default' label not within a switch statement");
7019 statement->case_label.statement = parse_statement();
7023 return create_invalid_statement();
7027 * Return the declaration for a given label symbol or create a new one.
7029 static declaration_t *get_label(symbol_t *symbol)
7031 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7032 assert(current_function != NULL);
7033 /* if we found a label in the same function, then we already created the
7035 if(candidate != NULL
7036 && candidate->parent_scope == ¤t_function->scope) {
7040 /* otherwise we need to create a new one */
7041 declaration_t *const declaration = allocate_declaration_zero();
7042 declaration->namespc = NAMESPACE_LABEL;
7043 declaration->symbol = symbol;
7045 label_push(declaration);
7051 * Parse a label statement.
7053 static statement_t *parse_label_statement(void)
7055 assert(token.type == T_IDENTIFIER);
7056 symbol_t *symbol = token.v.symbol;
7059 declaration_t *label = get_label(symbol);
7061 /* if source position is already set then the label is defined twice,
7062 * otherwise it was just mentioned in a goto so far */
7063 if(label->source_position.input_name != NULL) {
7064 errorf(HERE, "duplicate label '%Y' (declared %P)",
7065 symbol, &label->source_position);
7067 label->source_position = token.source_position;
7070 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7072 statement->base.source_position = token.source_position;
7073 statement->label.label = label;
7077 if(token.type == '}') {
7078 /* TODO only warn? */
7080 warningf(HERE, "label at end of compound statement");
7081 statement->label.statement = create_empty_statement();
7083 errorf(HERE, "label at end of compound statement");
7084 statement->label.statement = create_invalid_statement();
7088 if (token.type == ';') {
7089 /* eat an empty statement here, to avoid the warning about an empty
7090 * after a label. label:; is commonly used to have a label before
7092 statement->label.statement = create_empty_statement();
7095 statement->label.statement = parse_statement();
7099 /* remember the labels's in a list for later checking */
7100 if (label_last == NULL) {
7101 label_first = &statement->label;
7103 label_last->next = &statement->label;
7105 label_last = &statement->label;
7111 * Parse an if statement.
7113 static statement_t *parse_if(void)
7117 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7118 statement->base.source_position = token.source_position;
7121 add_anchor_token(')');
7122 statement->ifs.condition = parse_expression();
7123 rem_anchor_token(')');
7126 add_anchor_token(T_else);
7127 statement->ifs.true_statement = parse_statement();
7128 rem_anchor_token(T_else);
7130 if(token.type == T_else) {
7132 statement->ifs.false_statement = parse_statement();
7137 return create_invalid_statement();
7141 * Parse a switch statement.
7143 static statement_t *parse_switch(void)
7147 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7148 statement->base.source_position = token.source_position;
7151 expression_t *const expr = parse_expression();
7152 type_t * type = skip_typeref(expr->base.type);
7153 if (is_type_integer(type)) {
7154 type = promote_integer(type);
7155 } else if (is_type_valid(type)) {
7156 errorf(&expr->base.source_position,
7157 "switch quantity is not an integer, but '%T'", type);
7158 type = type_error_type;
7160 statement->switchs.expression = create_implicit_cast(expr, type);
7163 switch_statement_t *rem = current_switch;
7164 current_switch = &statement->switchs;
7165 statement->switchs.body = parse_statement();
7166 current_switch = rem;
7168 if(warning.switch_default &&
7169 find_default_label(&statement->switchs) == NULL) {
7170 warningf(&statement->base.source_position, "switch has no default case");
7175 return create_invalid_statement();
7178 static statement_t *parse_loop_body(statement_t *const loop)
7180 statement_t *const rem = current_loop;
7181 current_loop = loop;
7183 statement_t *const body = parse_statement();
7190 * Parse a while statement.
7192 static statement_t *parse_while(void)
7196 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7197 statement->base.source_position = token.source_position;
7200 add_anchor_token(')');
7201 statement->whiles.condition = parse_expression();
7202 rem_anchor_token(')');
7205 statement->whiles.body = parse_loop_body(statement);
7209 return create_invalid_statement();
7213 * Parse a do statement.
7215 static statement_t *parse_do(void)
7219 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7221 statement->base.source_position = token.source_position;
7223 add_anchor_token(T_while);
7224 statement->do_while.body = parse_loop_body(statement);
7225 rem_anchor_token(T_while);
7229 add_anchor_token(')');
7230 statement->do_while.condition = parse_expression();
7231 rem_anchor_token(')');
7237 return create_invalid_statement();
7241 * Parse a for statement.
7243 static statement_t *parse_for(void)
7247 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7248 statement->base.source_position = token.source_position;
7250 int top = environment_top();
7251 scope_t *last_scope = scope;
7252 set_scope(&statement->fors.scope);
7255 add_anchor_token(')');
7257 if(token.type != ';') {
7258 if(is_declaration_specifier(&token, false)) {
7259 parse_declaration(record_declaration);
7261 add_anchor_token(';');
7262 expression_t *const init = parse_expression();
7263 statement->fors.initialisation = init;
7264 if (warning.unused_value && !expression_has_effect(init)) {
7265 warningf(&init->base.source_position,
7266 "initialisation of 'for'-statement has no effect");
7268 rem_anchor_token(';');
7275 if(token.type != ';') {
7276 add_anchor_token(';');
7277 statement->fors.condition = parse_expression();
7278 rem_anchor_token(';');
7281 if(token.type != ')') {
7282 expression_t *const step = parse_expression();
7283 statement->fors.step = step;
7284 if (warning.unused_value && !expression_has_effect(step)) {
7285 warningf(&step->base.source_position,
7286 "step of 'for'-statement has no effect");
7289 rem_anchor_token(')');
7291 statement->fors.body = parse_loop_body(statement);
7293 assert(scope == &statement->fors.scope);
7294 set_scope(last_scope);
7295 environment_pop_to(top);
7300 rem_anchor_token(')');
7301 assert(scope == &statement->fors.scope);
7302 set_scope(last_scope);
7303 environment_pop_to(top);
7305 return create_invalid_statement();
7309 * Parse a goto statement.
7311 static statement_t *parse_goto(void)
7315 if(token.type != T_IDENTIFIER) {
7316 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
7320 symbol_t *symbol = token.v.symbol;
7323 declaration_t *label = get_label(symbol);
7325 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7326 statement->base.source_position = token.source_position;
7328 statement->gotos.label = label;
7330 /* remember the goto's in a list for later checking */
7331 if (goto_last == NULL) {
7332 goto_first = &statement->gotos;
7334 goto_last->next = &statement->gotos;
7336 goto_last = &statement->gotos;
7342 return create_invalid_statement();
7346 * Parse a continue statement.
7348 static statement_t *parse_continue(void)
7350 statement_t *statement;
7351 if (current_loop == NULL) {
7352 errorf(HERE, "continue statement not within loop");
7355 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7357 statement->base.source_position = token.source_position;
7365 return create_invalid_statement();
7369 * Parse a break statement.
7371 static statement_t *parse_break(void)
7373 statement_t *statement;
7374 if (current_switch == NULL && current_loop == NULL) {
7375 errorf(HERE, "break statement not within loop or switch");
7378 statement = allocate_statement_zero(STATEMENT_BREAK);
7380 statement->base.source_position = token.source_position;
7388 return create_invalid_statement();
7392 * Check if a given declaration represents a local variable.
7394 static bool is_local_var_declaration(const declaration_t *declaration) {
7395 switch ((storage_class_tag_t) declaration->storage_class) {
7396 case STORAGE_CLASS_AUTO:
7397 case STORAGE_CLASS_REGISTER: {
7398 const type_t *type = skip_typeref(declaration->type);
7399 if(is_type_function(type)) {
7411 * Check if a given declaration represents a variable.
7413 static bool is_var_declaration(const declaration_t *declaration) {
7414 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7417 const type_t *type = skip_typeref(declaration->type);
7418 return !is_type_function(type);
7422 * Check if a given expression represents a local variable.
7424 static bool is_local_variable(const expression_t *expression)
7426 if (expression->base.kind != EXPR_REFERENCE) {
7429 const declaration_t *declaration = expression->reference.declaration;
7430 return is_local_var_declaration(declaration);
7434 * Check if a given expression represents a local variable and
7435 * return its declaration then, else return NULL.
7437 declaration_t *expr_is_variable(const expression_t *expression)
7439 if (expression->base.kind != EXPR_REFERENCE) {
7442 declaration_t *declaration = expression->reference.declaration;
7443 if (is_var_declaration(declaration))
7449 * Parse a return statement.
7451 static statement_t *parse_return(void)
7453 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7454 statement->base.source_position = token.source_position;
7458 expression_t *return_value = NULL;
7459 if(token.type != ';') {
7460 return_value = parse_expression();
7464 const type_t *const func_type = current_function->type;
7465 assert(is_type_function(func_type));
7466 type_t *const return_type = skip_typeref(func_type->function.return_type);
7468 if(return_value != NULL) {
7469 type_t *return_value_type = skip_typeref(return_value->base.type);
7471 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7472 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7473 warningf(&statement->base.source_position,
7474 "'return' with a value, in function returning void");
7475 return_value = NULL;
7477 type_t *const res_type = semantic_assign(return_type,
7478 return_value, "'return'", &statement->base.source_position);
7479 if (res_type == NULL) {
7480 errorf(&statement->base.source_position,
7481 "cannot return something of type '%T' in function returning '%T'",
7482 return_value->base.type, return_type);
7484 return_value = create_implicit_cast(return_value, res_type);
7487 /* check for returning address of a local var */
7488 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7489 const expression_t *expression = return_value->unary.value;
7490 if (is_local_variable(expression)) {
7491 warningf(&statement->base.source_position,
7492 "function returns address of local variable");
7496 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7497 warningf(&statement->base.source_position,
7498 "'return' without value, in function returning non-void");
7501 statement->returns.value = return_value;
7505 return create_invalid_statement();
7509 * Parse a declaration statement.
7511 static statement_t *parse_declaration_statement(void)
7513 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7515 statement->base.source_position = token.source_position;
7517 declaration_t *before = last_declaration;
7518 parse_declaration(record_declaration);
7520 if(before == NULL) {
7521 statement->declaration.declarations_begin = scope->declarations;
7523 statement->declaration.declarations_begin = before->next;
7525 statement->declaration.declarations_end = last_declaration;
7531 * Parse an expression statement, ie. expr ';'.
7533 static statement_t *parse_expression_statement(void)
7535 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7537 statement->base.source_position = token.source_position;
7538 expression_t *const expr = parse_expression();
7539 statement->expression.expression = expr;
7541 if (warning.unused_value && !expression_has_effect(expr)) {
7542 warningf(&expr->base.source_position, "statement has no effect");
7549 return create_invalid_statement();
7553 * Parse a statement.
7555 static statement_t *parse_statement(void)
7557 statement_t *statement = NULL;
7559 /* declaration or statement */
7560 add_anchor_token(';');
7561 switch(token.type) {
7563 statement = parse_asm_statement();
7567 statement = parse_case_statement();
7571 statement = parse_default_statement();
7575 statement = parse_compound_statement();
7579 statement = parse_if();
7583 statement = parse_switch();
7587 statement = parse_while();
7591 statement = parse_do();
7595 statement = parse_for();
7599 statement = parse_goto();
7603 statement = parse_continue();
7607 statement = parse_break();
7611 statement = parse_return();
7615 if(warning.empty_statement) {
7616 warningf(HERE, "statement is empty");
7618 statement = create_empty_statement();
7623 if(look_ahead(1)->type == ':') {
7624 statement = parse_label_statement();
7628 if(is_typedef_symbol(token.v.symbol)) {
7629 statement = parse_declaration_statement();
7633 statement = parse_expression_statement();
7636 case T___extension__:
7637 /* this can be a prefix to a declaration or an expression statement */
7638 /* we simply eat it now and parse the rest with tail recursion */
7641 } while(token.type == T___extension__);
7642 statement = parse_statement();
7646 statement = parse_declaration_statement();
7650 statement = parse_expression_statement();
7653 rem_anchor_token(';');
7655 assert(statement != NULL
7656 && statement->base.source_position.input_name != NULL);
7662 * Parse a compound statement.
7664 static statement_t *parse_compound_statement(void)
7666 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7668 statement->base.source_position = token.source_position;
7671 add_anchor_token('}');
7673 int top = environment_top();
7674 scope_t *last_scope = scope;
7675 set_scope(&statement->compound.scope);
7677 statement_t *last_statement = NULL;
7679 while(token.type != '}' && token.type != T_EOF) {
7680 statement_t *sub_statement = parse_statement();
7681 if(is_invalid_statement(sub_statement)) {
7682 /* an error occurred. if we are at an anchor, return */
7688 if(last_statement != NULL) {
7689 last_statement->base.next = sub_statement;
7691 statement->compound.statements = sub_statement;
7694 while(sub_statement->base.next != NULL)
7695 sub_statement = sub_statement->base.next;
7697 last_statement = sub_statement;
7700 if(token.type == '}') {
7703 errorf(&statement->base.source_position,
7704 "end of file while looking for closing '}'");
7708 rem_anchor_token('}');
7709 assert(scope == &statement->compound.scope);
7710 set_scope(last_scope);
7711 environment_pop_to(top);
7717 * Initialize builtin types.
7719 static void initialize_builtin_types(void)
7721 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7722 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7723 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7724 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7725 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7726 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7727 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7728 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7730 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7731 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7732 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7733 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7737 * Check for unused global static functions and variables
7739 static void check_unused_globals(void)
7741 if (!warning.unused_function && !warning.unused_variable)
7744 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7745 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7748 type_t *const type = decl->type;
7750 if (is_type_function(skip_typeref(type))) {
7751 if (!warning.unused_function || decl->is_inline)
7754 s = (decl->init.statement != NULL ? "defined" : "declared");
7756 if (!warning.unused_variable)
7762 warningf(&decl->source_position, "'%#T' %s but not used",
7763 type, decl->symbol, s);
7768 * Parse a translation unit.
7770 static translation_unit_t *parse_translation_unit(void)
7772 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7774 assert(global_scope == NULL);
7775 global_scope = &unit->scope;
7777 assert(scope == NULL);
7778 set_scope(&unit->scope);
7780 initialize_builtin_types();
7782 while(token.type != T_EOF) {
7783 if (token.type == ';') {
7784 /* TODO error in strict mode */
7785 warningf(HERE, "stray ';' outside of function");
7788 parse_external_declaration();
7792 assert(scope == &unit->scope);
7794 last_declaration = NULL;
7796 assert(global_scope == &unit->scope);
7797 check_unused_globals();
7798 global_scope = NULL;
7806 * @return the translation unit or NULL if errors occurred.
7808 translation_unit_t *parse(void)
7810 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7811 label_stack = NEW_ARR_F(stack_entry_t, 0);
7812 diagnostic_count = 0;
7816 type_set_output(stderr);
7817 ast_set_output(stderr);
7819 lookahead_bufpos = 0;
7820 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7823 translation_unit_t *unit = parse_translation_unit();
7825 DEL_ARR_F(environment_stack);
7826 DEL_ARR_F(label_stack);
7832 * Initialize the parser.
7834 void init_parser(void)
7837 /* add predefined symbols for extended-decl-modifier */
7838 sym_align = symbol_table_insert("align");
7839 sym_allocate = symbol_table_insert("allocate");
7840 sym_dllimport = symbol_table_insert("dllimport");
7841 sym_dllexport = symbol_table_insert("dllexport");
7842 sym_naked = symbol_table_insert("naked");
7843 sym_noinline = symbol_table_insert("noinline");
7844 sym_noreturn = symbol_table_insert("noreturn");
7845 sym_nothrow = symbol_table_insert("nothrow");
7846 sym_novtable = symbol_table_insert("novtable");
7847 sym_property = symbol_table_insert("property");
7848 sym_get = symbol_table_insert("get");
7849 sym_put = symbol_table_insert("put");
7850 sym_selectany = symbol_table_insert("selectany");
7851 sym_thread = symbol_table_insert("thread");
7852 sym_uuid = symbol_table_insert("uuid");
7853 sym_deprecated = symbol_table_insert("deprecated");
7854 sym_restrict = symbol_table_insert("restrict");
7855 sym_noalias = symbol_table_insert("noalias");
7857 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7859 init_expression_parsers();
7860 obstack_init(&temp_obst);
7862 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7863 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7867 * Terminate the parser.
7869 void exit_parser(void)
7871 obstack_free(&temp_obst, NULL);