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 ms_try_statement_t *current_try = NULL;
103 static goto_statement_t *goto_first = NULL;
104 static goto_statement_t *goto_last = NULL;
105 static label_statement_t *label_first = NULL;
106 static label_statement_t *label_last = NULL;
107 static struct obstack temp_obst;
109 static source_position_t null_position = { NULL, 0 };
111 /* symbols for Microsoft extended-decl-modifier */
112 static const symbol_t *sym_align = NULL;
113 static const symbol_t *sym_allocate = NULL;
114 static const symbol_t *sym_dllimport = NULL;
115 static const symbol_t *sym_dllexport = NULL;
116 static const symbol_t *sym_naked = NULL;
117 static const symbol_t *sym_noinline = NULL;
118 static const symbol_t *sym_noreturn = NULL;
119 static const symbol_t *sym_nothrow = NULL;
120 static const symbol_t *sym_novtable = NULL;
121 static const symbol_t *sym_property = NULL;
122 static const symbol_t *sym_get = NULL;
123 static const symbol_t *sym_put = NULL;
124 static const symbol_t *sym_selectany = NULL;
125 static const symbol_t *sym_thread = NULL;
126 static const symbol_t *sym_uuid = NULL;
127 static const symbol_t *sym_deprecated = NULL;
128 static const symbol_t *sym_restrict = NULL;
129 static const symbol_t *sym_noalias = NULL;
131 /** The token anchor set */
132 static unsigned char token_anchor_set[T_LAST_TOKEN];
134 /** The current source position. */
135 #define HERE &token.source_position
137 static type_t *type_valist;
139 static statement_t *parse_compound_statement(bool inside_expression_statement);
140 static statement_t *parse_statement(void);
142 static expression_t *parse_sub_expression(unsigned precedence);
143 static expression_t *parse_expression(void);
144 static type_t *parse_typename(void);
146 static void parse_compound_type_entries(declaration_t *compound_declaration);
147 static declaration_t *parse_declarator(
148 const declaration_specifiers_t *specifiers, bool may_be_abstract);
149 static declaration_t *record_declaration(declaration_t *declaration);
151 static void semantic_comparison(binary_expression_t *expression);
153 #define STORAGE_CLASSES \
160 #define TYPE_QUALIFIERS \
167 #ifdef PROVIDE_COMPLEX
168 #define COMPLEX_SPECIFIERS \
170 #define IMAGINARY_SPECIFIERS \
173 #define COMPLEX_SPECIFIERS
174 #define IMAGINARY_SPECIFIERS
177 #define TYPE_SPECIFIERS \
192 case T___builtin_va_list: \
197 #define DECLARATION_START \
202 #define TYPENAME_START \
207 * Allocate an AST node with given size and
208 * initialize all fields with zero.
210 static void *allocate_ast_zero(size_t size)
212 void *res = allocate_ast(size);
213 memset(res, 0, size);
217 static declaration_t *allocate_declaration_zero(void)
219 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
220 declaration->type = type_error_type;
221 declaration->alignment = 0;
226 * Returns the size of a statement node.
228 * @param kind the statement kind
230 static size_t get_statement_struct_size(statement_kind_t kind)
232 static const size_t sizes[] = {
233 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
234 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
235 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
236 [STATEMENT_RETURN] = sizeof(return_statement_t),
237 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
238 [STATEMENT_IF] = sizeof(if_statement_t),
239 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
240 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
241 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
242 [STATEMENT_BREAK] = sizeof(statement_base_t),
243 [STATEMENT_GOTO] = sizeof(goto_statement_t),
244 [STATEMENT_LABEL] = sizeof(label_statement_t),
245 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
246 [STATEMENT_WHILE] = sizeof(while_statement_t),
247 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
248 [STATEMENT_FOR] = sizeof(for_statement_t),
249 [STATEMENT_ASM] = sizeof(asm_statement_t),
250 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
251 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
253 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
254 assert(sizes[kind] != 0);
259 * Returns the size of an expression node.
261 * @param kind the expression kind
263 static size_t get_expression_struct_size(expression_kind_t kind)
265 static const size_t sizes[] = {
266 [EXPR_INVALID] = sizeof(expression_base_t),
267 [EXPR_REFERENCE] = sizeof(reference_expression_t),
268 [EXPR_CONST] = sizeof(const_expression_t),
269 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
270 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
271 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
272 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
273 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
274 [EXPR_CALL] = sizeof(call_expression_t),
275 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
276 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
277 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
278 [EXPR_SELECT] = sizeof(select_expression_t),
279 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
280 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
281 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
282 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
283 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
284 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
285 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
286 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
287 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
288 [EXPR_VA_START] = sizeof(va_start_expression_t),
289 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
290 [EXPR_STATEMENT] = sizeof(statement_expression_t),
292 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
293 return sizes[EXPR_UNARY_FIRST];
295 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
296 return sizes[EXPR_BINARY_FIRST];
298 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
299 assert(sizes[kind] != 0);
304 * Allocate a statement node of given kind and initialize all
307 static statement_t *allocate_statement_zero(statement_kind_t kind)
309 size_t size = get_statement_struct_size(kind);
310 statement_t *res = allocate_ast_zero(size);
312 res->base.kind = kind;
317 * Allocate an expression node of given kind and initialize all
320 static expression_t *allocate_expression_zero(expression_kind_t kind)
322 size_t size = get_expression_struct_size(kind);
323 expression_t *res = allocate_ast_zero(size);
325 res->base.kind = kind;
326 res->base.type = type_error_type;
331 * Creates a new invalid expression.
333 static expression_t *create_invalid_expression(void)
335 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
336 expression->base.source_position = token.source_position;
341 * Creates a new invalid statement.
343 static statement_t *create_invalid_statement(void)
345 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
346 statement->base.source_position = token.source_position;
351 * Allocate a new empty statement.
353 static statement_t *create_empty_statement(void)
355 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
356 statement->base.source_position = token.source_position;
361 * Returns the size of a type node.
363 * @param kind the type kind
365 static size_t get_type_struct_size(type_kind_t kind)
367 static const size_t sizes[] = {
368 [TYPE_ATOMIC] = sizeof(atomic_type_t),
369 [TYPE_COMPLEX] = sizeof(complex_type_t),
370 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
371 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
372 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
373 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
374 [TYPE_ENUM] = sizeof(enum_type_t),
375 [TYPE_FUNCTION] = sizeof(function_type_t),
376 [TYPE_POINTER] = sizeof(pointer_type_t),
377 [TYPE_ARRAY] = sizeof(array_type_t),
378 [TYPE_BUILTIN] = sizeof(builtin_type_t),
379 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
380 [TYPE_TYPEOF] = sizeof(typeof_type_t),
382 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
383 assert(kind <= TYPE_TYPEOF);
384 assert(sizes[kind] != 0);
389 * Allocate a type node of given kind and initialize all
392 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
394 size_t size = get_type_struct_size(kind);
395 type_t *res = obstack_alloc(type_obst, size);
396 memset(res, 0, size);
398 res->base.kind = kind;
399 res->base.source_position = *source_position;
404 * Returns the size of an initializer node.
406 * @param kind the initializer kind
408 static size_t get_initializer_size(initializer_kind_t kind)
410 static const size_t sizes[] = {
411 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
412 [INITIALIZER_STRING] = sizeof(initializer_string_t),
413 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
414 [INITIALIZER_LIST] = sizeof(initializer_list_t),
415 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
417 assert(kind < sizeof(sizes) / sizeof(*sizes));
418 assert(sizes[kind] != 0);
423 * Allocate an initializer node of given kind and initialize all
426 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
428 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
435 * Free a type from the type obstack.
437 static void free_type(void *type)
439 obstack_free(type_obst, type);
443 * Returns the index of the top element of the environment stack.
445 static size_t environment_top(void)
447 return ARR_LEN(environment_stack);
451 * Returns the index of the top element of the label stack.
453 static size_t label_top(void)
455 return ARR_LEN(label_stack);
459 * Return the next token.
461 static inline void next_token(void)
463 token = lookahead_buffer[lookahead_bufpos];
464 lookahead_buffer[lookahead_bufpos] = lexer_token;
467 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
470 print_token(stderr, &token);
471 fprintf(stderr, "\n");
476 * Return the next token with a given lookahead.
478 static inline const token_t *look_ahead(int num)
480 assert(num > 0 && num <= MAX_LOOKAHEAD);
481 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
482 return &lookahead_buffer[pos];
486 * Adds a token to the token anchor set (a multi-set).
488 static void add_anchor_token(int token_type) {
489 assert(0 <= token_type && token_type < T_LAST_TOKEN);
490 ++token_anchor_set[token_type];
494 * Remove a token from the token anchor set (a multi-set).
496 static void rem_anchor_token(int token_type) {
497 assert(0 <= token_type && token_type < T_LAST_TOKEN);
498 --token_anchor_set[token_type];
501 static bool at_anchor(void) {
504 return token_anchor_set[token.type];
508 * Eat tokens until a matching token is found.
510 static void eat_until_matching_token(int type) {
511 unsigned parenthesis_count = 0;
512 unsigned brace_count = 0;
513 unsigned bracket_count = 0;
514 int end_token = type;
523 while(token.type != end_token ||
524 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
528 case '(': ++parenthesis_count; break;
529 case '{': ++brace_count; break;
530 case '[': ++bracket_count; break;
532 if(parenthesis_count > 0)
540 if(bracket_count > 0)
551 * Eat input tokens until an anchor is found.
553 static void eat_until_anchor(void) {
554 if(token.type == T_EOF)
556 while(token_anchor_set[token.type] == 0) {
557 if(token.type == '(' || token.type == '{' || token.type == '[')
558 eat_until_matching_token(token.type);
559 if(token.type == T_EOF)
565 static void eat_block(void) {
566 eat_until_matching_token('{');
567 if(token.type == '}')
572 * eat all token until a ';' is reached or a stop token is found.
574 static void eat_statement(void) {
575 eat_until_matching_token(';');
576 if(token.type == ';')
580 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
583 * Report a parse error because an expected token was not found.
586 #if defined __GNUC__ && __GNUC__ >= 4
587 __attribute__((sentinel))
589 void parse_error_expected(const char *message, ...)
591 if(message != NULL) {
592 errorf(HERE, "%s", message);
595 va_start(ap, message);
596 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
601 * Report a type error.
603 static void type_error(const char *msg, const source_position_t *source_position,
606 errorf(source_position, "%s, but found type '%T'", msg, type);
610 * Report an incompatible type.
612 static void type_error_incompatible(const char *msg,
613 const source_position_t *source_position, type_t *type1, type_t *type2)
615 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
620 * Expect the the current token is the expected token.
621 * If not, generate an error, eat the current statement,
622 * and goto the end_error label.
624 #define expect(expected) \
626 if(UNLIKELY(token.type != (expected))) { \
627 parse_error_expected(NULL, (expected), NULL); \
628 add_anchor_token(expected); \
629 eat_until_anchor(); \
630 rem_anchor_token(expected); \
636 static void set_scope(scope_t *new_scope)
639 scope->last_declaration = last_declaration;
643 last_declaration = new_scope->last_declaration;
647 * Search a symbol in a given namespace and returns its declaration or
648 * NULL if this symbol was not found.
650 static declaration_t *get_declaration(const symbol_t *const symbol,
651 const namespace_t namespc)
653 declaration_t *declaration = symbol->declaration;
654 for( ; declaration != NULL; declaration = declaration->symbol_next) {
655 if(declaration->namespc == namespc)
663 * pushs an environment_entry on the environment stack and links the
664 * corresponding symbol to the new entry
666 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
668 symbol_t *symbol = declaration->symbol;
669 namespace_t namespc = (namespace_t) declaration->namespc;
671 /* replace/add declaration into declaration list of the symbol */
672 declaration_t *iter = symbol->declaration;
674 symbol->declaration = declaration;
676 declaration_t *iter_last = NULL;
677 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
678 /* replace an entry? */
679 if(iter->namespc == namespc) {
680 if(iter_last == NULL) {
681 symbol->declaration = declaration;
683 iter_last->symbol_next = declaration;
685 declaration->symbol_next = iter->symbol_next;
690 assert(iter_last->symbol_next == NULL);
691 iter_last->symbol_next = declaration;
695 /* remember old declaration */
697 entry.symbol = symbol;
698 entry.old_declaration = iter;
699 entry.namespc = (unsigned short) namespc;
700 ARR_APP1(stack_entry_t, *stack_ptr, entry);
703 static void environment_push(declaration_t *declaration)
705 assert(declaration->source_position.input_name != NULL);
706 assert(declaration->parent_scope != NULL);
707 stack_push(&environment_stack, declaration);
710 static void label_push(declaration_t *declaration)
712 declaration->parent_scope = ¤t_function->scope;
713 stack_push(&label_stack, declaration);
717 * pops symbols from the environment stack until @p new_top is the top element
719 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
721 stack_entry_t *stack = *stack_ptr;
722 size_t top = ARR_LEN(stack);
725 assert(new_top <= top);
729 for(i = top; i > new_top; --i) {
730 stack_entry_t *entry = &stack[i - 1];
732 declaration_t *old_declaration = entry->old_declaration;
733 symbol_t *symbol = entry->symbol;
734 namespace_t namespc = (namespace_t)entry->namespc;
736 /* replace/remove declaration */
737 declaration_t *declaration = symbol->declaration;
738 assert(declaration != NULL);
739 if(declaration->namespc == namespc) {
740 if(old_declaration == NULL) {
741 symbol->declaration = declaration->symbol_next;
743 symbol->declaration = old_declaration;
746 declaration_t *iter_last = declaration;
747 declaration_t *iter = declaration->symbol_next;
748 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
749 /* replace an entry? */
750 if(iter->namespc == namespc) {
751 assert(iter_last != NULL);
752 iter_last->symbol_next = old_declaration;
753 if(old_declaration != NULL) {
754 old_declaration->symbol_next = iter->symbol_next;
759 assert(iter != NULL);
763 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
766 static void environment_pop_to(size_t new_top)
768 stack_pop_to(&environment_stack, new_top);
771 static void label_pop_to(size_t new_top)
773 stack_pop_to(&label_stack, new_top);
777 static int get_rank(const type_t *type)
779 assert(!is_typeref(type));
780 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
781 * and esp. footnote 108). However we can't fold constants (yet), so we
782 * can't decide whether unsigned int is possible, while int always works.
783 * (unsigned int would be preferable when possible... for stuff like
784 * struct { enum { ... } bla : 4; } ) */
785 if(type->kind == TYPE_ENUM)
786 return ATOMIC_TYPE_INT;
788 assert(type->kind == TYPE_ATOMIC);
789 return type->atomic.akind;
792 static type_t *promote_integer(type_t *type)
794 if(type->kind == TYPE_BITFIELD)
795 type = type->bitfield.base_type;
797 if(get_rank(type) < ATOMIC_TYPE_INT)
804 * Create a cast expression.
806 * @param expression the expression to cast
807 * @param dest_type the destination type
809 static expression_t *create_cast_expression(expression_t *expression,
812 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
814 cast->unary.value = expression;
815 cast->base.type = dest_type;
821 * Check if a given expression represents the 0 pointer constant.
823 static bool is_null_pointer_constant(const expression_t *expression)
825 /* skip void* cast */
826 if(expression->kind == EXPR_UNARY_CAST
827 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
828 expression = expression->unary.value;
831 /* TODO: not correct yet, should be any constant integer expression
832 * which evaluates to 0 */
833 if (expression->kind != EXPR_CONST)
836 type_t *const type = skip_typeref(expression->base.type);
837 if (!is_type_integer(type))
840 return expression->conste.v.int_value == 0;
844 * Create an implicit cast expression.
846 * @param expression the expression to cast
847 * @param dest_type the destination type
849 static expression_t *create_implicit_cast(expression_t *expression,
852 type_t *const source_type = expression->base.type;
854 if (source_type == dest_type)
857 return create_cast_expression(expression, dest_type);
860 /** Implements the rules from § 6.5.16.1 */
861 static type_t *semantic_assign(type_t *orig_type_left,
862 const expression_t *const right,
864 const source_position_t *source_position)
866 type_t *const orig_type_right = right->base.type;
867 type_t *const type_left = skip_typeref(orig_type_left);
868 type_t *const type_right = skip_typeref(orig_type_right);
870 if(is_type_pointer(type_left)) {
871 if(is_null_pointer_constant(right)) {
872 return orig_type_left;
873 } else if(is_type_pointer(type_right)) {
874 type_t *points_to_left
875 = skip_typeref(type_left->pointer.points_to);
876 type_t *points_to_right
877 = skip_typeref(type_right->pointer.points_to);
879 /* the left type has all qualifiers from the right type */
880 unsigned missing_qualifiers
881 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
882 if(missing_qualifiers != 0) {
883 errorf(source_position,
884 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
885 return orig_type_left;
888 points_to_left = get_unqualified_type(points_to_left);
889 points_to_right = get_unqualified_type(points_to_right);
891 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
892 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
893 return orig_type_left;
896 if (!types_compatible(points_to_left, points_to_right)) {
897 warningf(source_position,
898 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
899 orig_type_left, context, right, orig_type_right);
902 return orig_type_left;
903 } else if(is_type_integer(type_right)) {
904 warningf(source_position,
905 "%s makes pointer '%T' from integer '%T' without a cast",
906 context, orig_type_left, orig_type_right);
907 return orig_type_left;
909 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
910 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
911 && is_type_pointer(type_right))) {
912 return orig_type_left;
913 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
914 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
915 type_t *const unqual_type_left = get_unqualified_type(type_left);
916 type_t *const unqual_type_right = get_unqualified_type(type_right);
917 if (types_compatible(unqual_type_left, unqual_type_right)) {
918 return orig_type_left;
920 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
921 warningf(source_position,
922 "%s makes integer '%T' from pointer '%T' without a cast",
923 context, orig_type_left, orig_type_right);
924 return orig_type_left;
927 if (!is_type_valid(type_left))
930 if (!is_type_valid(type_right))
931 return orig_type_right;
936 static expression_t *parse_constant_expression(void)
938 /* start parsing at precedence 7 (conditional expression) */
939 expression_t *result = parse_sub_expression(7);
941 if(!is_constant_expression(result)) {
942 errorf(&result->base.source_position,
943 "expression '%E' is not constant\n", result);
949 static expression_t *parse_assignment_expression(void)
951 /* start parsing at precedence 2 (assignment expression) */
952 return parse_sub_expression(2);
955 static type_t *make_global_typedef(const char *name, type_t *type)
957 symbol_t *const symbol = symbol_table_insert(name);
959 declaration_t *const declaration = allocate_declaration_zero();
960 declaration->namespc = NAMESPACE_NORMAL;
961 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
962 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
963 declaration->type = type;
964 declaration->symbol = symbol;
965 declaration->source_position = builtin_source_position;
967 record_declaration(declaration);
969 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
970 typedef_type->typedeft.declaration = declaration;
975 static string_t parse_string_literals(void)
977 assert(token.type == T_STRING_LITERAL);
978 string_t result = token.v.string;
982 while (token.type == T_STRING_LITERAL) {
983 result = concat_strings(&result, &token.v.string);
990 static const char *gnu_attribute_names[GNU_AK_LAST] = {
991 [GNU_AK_CONST] = "const",
992 [GNU_AK_VOLATILE] = "volatile",
993 [GNU_AK_CDECL] = "cdecl",
994 [GNU_AK_STDCALL] = "stdcall",
995 [GNU_AK_FASTCALL] = "fastcall",
996 [GNU_AK_DEPRECATED] = "deprecated",
997 [GNU_AK_NOINLINE] = "noinline",
998 [GNU_AK_NORETURN] = "noreturn",
999 [GNU_AK_NAKED] = "naked",
1000 [GNU_AK_PURE] = "pure",
1001 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1002 [GNU_AK_MALLOC] = "malloc",
1003 [GNU_AK_WEAK] = "weak",
1004 [GNU_AK_CONSTRUCTOR] = "constructor",
1005 [GNU_AK_DESTRUCTOR] = "destructor",
1006 [GNU_AK_NOTHROW] = "nothrow",
1007 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1008 [GNU_AK_COMMON] = "coommon",
1009 [GNU_AK_NOCOMMON] = "nocommon",
1010 [GNU_AK_PACKED] = "packed",
1011 [GNU_AK_SHARED] = "shared",
1012 [GNU_AK_NOTSHARED] = "notshared",
1013 [GNU_AK_USED] = "used",
1014 [GNU_AK_UNUSED] = "unused",
1015 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1016 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1017 [GNU_AK_LONGCALL] = "longcall",
1018 [GNU_AK_SHORTCALL] = "shortcall",
1019 [GNU_AK_LONG_CALL] = "long_call",
1020 [GNU_AK_SHORT_CALL] = "short_call",
1021 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1022 [GNU_AK_INTERRUPT] = "interrupt",
1023 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1024 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1025 [GNU_AK_NESTING] = "nesting",
1026 [GNU_AK_NEAR] = "near",
1027 [GNU_AK_FAR] = "far",
1028 [GNU_AK_SIGNAL] = "signal",
1029 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1030 [GNU_AK_TINY_DATA] = "tiny_data",
1031 [GNU_AK_SAVEALL] = "saveall",
1032 [GNU_AK_FLATTEN] = "flatten",
1033 [GNU_AK_SSEREGPARM] = "sseregparm",
1034 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1035 [GNU_AK_RETURN_TWICE] = "return_twice",
1036 [GNU_AK_MAY_ALIAS] = "may_alias",
1037 [GNU_AK_MS_STRUCT] = "ms_struct",
1038 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1039 [GNU_AK_DLLIMPORT] = "dllimport",
1040 [GNU_AK_DLLEXPORT] = "dllexport",
1041 [GNU_AK_ALIGNED] = "aligned",
1042 [GNU_AK_ALIAS] = "alias",
1043 [GNU_AK_SECTION] = "section",
1044 [GNU_AK_FORMAT] = "format",
1045 [GNU_AK_FORMAT_ARG] = "format_arg",
1046 [GNU_AK_WEAKREF] = "weakref",
1047 [GNU_AK_NONNULL] = "nonnull",
1048 [GNU_AK_TLS_MODEL] = "tls_model",
1049 [GNU_AK_VISIBILITY] = "visibility",
1050 [GNU_AK_REGPARM] = "regparm",
1051 [GNU_AK_MODEL] = "model",
1052 [GNU_AK_TRAP_EXIT] = "trap_exit",
1053 [GNU_AK_SP_SWITCH] = "sp_switch",
1054 [GNU_AK_SENTINEL] = "sentinel"
1058 * compare two string, ignoring double underscores on the second.
1060 static int strcmp_underscore(const char *s1, const char *s2) {
1061 if(s2[0] == '_' && s2[1] == '_') {
1063 size_t l1 = strlen(s1);
1064 if(l1 + 2 != strlen(s2)) {
1068 return strncmp(s1, s2, l1);
1070 return strcmp(s1, s2);
1074 * Allocate a new gnu temporal attribute.
1076 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1077 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1078 attribute->kind = kind;
1079 attribute->next = NULL;
1080 attribute->invalid = false;
1081 attribute->have_arguments = false;
1088 * parse one constant expression argument.
1090 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1091 expression_t *expression;
1092 add_anchor_token(')');
1093 expression = parse_constant_expression();
1094 rem_anchor_token(')');
1099 attribute->invalid = true;
1103 * parse a list of constant expressions arguments.
1105 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1106 expression_t *expression;
1107 add_anchor_token(')');
1108 add_anchor_token(',');
1110 expression = parse_constant_expression();
1111 if(token.type != ',')
1115 rem_anchor_token(',');
1116 rem_anchor_token(')');
1121 attribute->invalid = true;
1125 * parse one string literal argument.
1127 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1130 add_anchor_token('(');
1131 if(token.type != T_STRING_LITERAL) {
1132 parse_error_expected("while parsing attribute directive",
1133 T_STRING_LITERAL, NULL);
1136 *string = parse_string_literals();
1137 rem_anchor_token('(');
1141 attribute->invalid = true;
1145 * parse one tls model.
1147 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1148 static const char *tls_models[] = {
1154 string_t string = { NULL, 0 };
1155 parse_gnu_attribute_string_arg(attribute, &string);
1156 if(string.begin != NULL) {
1157 for(size_t i = 0; i < 4; ++i) {
1158 if(strcmp(tls_models[i], string.begin) == 0) {
1159 attribute->u.value = i;
1164 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1165 attribute->invalid = true;
1169 * parse one tls model.
1171 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1172 static const char *visibilities[] = {
1178 string_t string = { NULL, 0 };
1179 parse_gnu_attribute_string_arg(attribute, &string);
1180 if(string.begin != NULL) {
1181 for(size_t i = 0; i < 4; ++i) {
1182 if(strcmp(visibilities[i], string.begin) == 0) {
1183 attribute->u.value = i;
1188 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1189 attribute->invalid = true;
1193 * parse one (code) model.
1195 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1196 static const char *visibilities[] = {
1201 string_t string = { NULL, 0 };
1202 parse_gnu_attribute_string_arg(attribute, &string);
1203 if(string.begin != NULL) {
1204 for(int i = 0; i < 3; ++i) {
1205 if(strcmp(visibilities[i], string.begin) == 0) {
1206 attribute->u.value = i;
1211 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1212 attribute->invalid = true;
1216 * parse one interrupt argument.
1218 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1219 static const char *interrupts[] = {
1226 string_t string = { NULL, 0 };
1227 parse_gnu_attribute_string_arg(attribute, &string);
1228 if(string.begin != NULL) {
1229 for(size_t i = 0; i < 5; ++i) {
1230 if(strcmp(interrupts[i], string.begin) == 0) {
1231 attribute->u.value = i;
1236 errorf(HERE, "'%s' is an interrupt", string.begin);
1237 attribute->invalid = true;
1241 * parse ( identifier, const expression, const expression )
1243 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1244 static const char *format_names[] = {
1252 if(token.type != T_IDENTIFIER) {
1253 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1256 const char *name = token.v.symbol->string;
1257 for(i = 0; i < 4; ++i) {
1258 if(strcmp_underscore(format_names[i], name) == 0)
1262 if(warning.attribute)
1263 warningf(HERE, "'%s' is an unrecognized format function type", name);
1268 add_anchor_token(')');
1269 add_anchor_token(',');
1270 parse_constant_expression();
1271 rem_anchor_token(',');
1272 rem_anchor_token('(');
1275 add_anchor_token(')');
1276 parse_constant_expression();
1277 rem_anchor_token('(');
1281 attribute->u.value = true;
1285 * Parse one GNU attribute.
1287 * Note that attribute names can be specified WITH or WITHOUT
1288 * double underscores, ie const or __const__.
1290 * The following attributes are parsed without arguments
1315 * no_instrument_function
1316 * warn_unused_result
1333 * externally_visible
1341 * The following attributes are parsed with arguments
1342 * aligned( const expression )
1343 * alias( string literal )
1344 * section( string literal )
1345 * format( identifier, const expression, const expression )
1346 * format_arg( const expression )
1347 * tls_model( string literal )
1348 * visibility( string literal )
1349 * regparm( const expression )
1350 * model( string leteral )
1351 * trap_exit( const expression )
1352 * sp_switch( string literal )
1354 * The following attributes might have arguments
1355 * weak_ref( string literal )
1356 * non_null( const expression // ',' )
1357 * interrupt( string literal )
1358 * sentinel( constant expression )
1360 static void parse_gnu_attribute(gnu_attribute_t **attributes)
1362 gnu_attribute_t *head = *attributes;
1363 gnu_attribute_t *last = *attributes;
1364 gnu_attribute_t *attribute;
1366 eat(T___attribute__);
1370 if(token.type != ')') {
1371 /* find the end of the list */
1373 while(last->next != NULL)
1377 /* non-empty attribute list */
1380 if(token.type == T_const) {
1382 } else if(token.type == T_volatile) {
1384 } else if(token.type == T_cdecl) {
1385 /* __attribute__((cdecl)), WITH ms mode */
1387 } else if(token.type != T_IDENTIFIER) {
1388 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1391 const symbol_t *sym = token.v.symbol;
1396 for(i = 0; i < GNU_AK_LAST; ++i) {
1397 if(strcmp_underscore(gnu_attribute_names[i], name) == 0)
1400 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1403 if(kind == GNU_AK_LAST) {
1404 if(warning.attribute)
1405 warningf(HERE, "'%s' attribute directive ignored", name);
1407 /* skip possible arguments */
1408 if(token.type == '(') {
1409 eat_until_matching_token(')');
1412 /* check for arguments */
1413 attribute = allocate_gnu_attribute(kind);
1414 if(token.type == '(') {
1416 if(token.type == ')') {
1417 /* empty args are allowed */
1420 attribute->have_arguments = true;
1425 case GNU_AK_VOLATILE:
1427 case GNU_AK_STDCALL:
1428 case GNU_AK_FASTCALL:
1429 case GNU_AK_DEPRECATED:
1430 case GNU_AK_NOINLINE:
1431 case GNU_AK_NORETURN:
1434 case GNU_AK_ALWAYS_INLINE:
1437 case GNU_AK_CONSTRUCTOR:
1438 case GNU_AK_DESTRUCTOR:
1439 case GNU_AK_NOTHROW:
1440 case GNU_AK_TRANSPARENT_UNION:
1442 case GNU_AK_NOCOMMON:
1445 case GNU_AK_NOTSHARED:
1448 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1449 case GNU_AK_WARN_UNUSED_RESULT:
1450 case GNU_AK_LONGCALL:
1451 case GNU_AK_SHORTCALL:
1452 case GNU_AK_LONG_CALL:
1453 case GNU_AK_SHORT_CALL:
1454 case GNU_AK_FUNCTION_VECTOR:
1455 case GNU_AK_INTERRUPT_HANDLER:
1456 case GNU_AK_NMI_HANDLER:
1457 case GNU_AK_NESTING:
1461 case GNU_AK_EIGTHBIT_DATA:
1462 case GNU_AK_TINY_DATA:
1463 case GNU_AK_SAVEALL:
1464 case GNU_AK_FLATTEN:
1465 case GNU_AK_SSEREGPARM:
1466 case GNU_AK_EXTERNALLY_VISIBLE:
1467 case GNU_AK_RETURN_TWICE:
1468 case GNU_AK_MAY_ALIAS:
1469 case GNU_AK_MS_STRUCT:
1470 case GNU_AK_GCC_STRUCT:
1471 case GNU_AK_DLLIMPORT:
1472 case GNU_AK_DLLEXPORT:
1473 if(attribute->have_arguments) {
1474 /* should have no arguments */
1475 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1476 eat_until_matching_token('(');
1477 /* we have already consumed '(', so we stop before ')', eat it */
1479 attribute->invalid = true;
1483 case GNU_AK_ALIGNED:
1484 case GNU_AK_FORMAT_ARG:
1485 case GNU_AK_REGPARM:
1486 case GNU_AK_TRAP_EXIT:
1487 if(!attribute->have_arguments) {
1488 /* should have arguments */
1489 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1490 attribute->invalid = true;
1492 parse_gnu_attribute_const_arg(attribute);
1495 case GNU_AK_SECTION:
1496 case GNU_AK_SP_SWITCH:
1497 if(!attribute->have_arguments) {
1498 /* should have arguments */
1499 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1500 attribute->invalid = true;
1502 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1505 if(!attribute->have_arguments) {
1506 /* should have arguments */
1507 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1508 attribute->invalid = true;
1510 parse_gnu_attribute_format_args(attribute);
1512 case GNU_AK_WEAKREF:
1513 /* may have one string argument */
1514 if(attribute->have_arguments)
1515 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1517 case GNU_AK_NONNULL:
1518 if(attribute->have_arguments)
1519 parse_gnu_attribute_const_arg_list(attribute);
1521 case GNU_AK_TLS_MODEL:
1522 if(!attribute->have_arguments) {
1523 /* should have arguments */
1524 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1526 parse_gnu_attribute_tls_model_arg(attribute);
1528 case GNU_AK_VISIBILITY:
1529 if(!attribute->have_arguments) {
1530 /* should have arguments */
1531 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1533 parse_gnu_attribute_visibility_arg(attribute);
1536 if(!attribute->have_arguments) {
1537 /* should have arguments */
1538 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1540 parse_gnu_attribute_model_arg(attribute);
1541 case GNU_AK_INTERRUPT:
1542 /* may have one string argument */
1543 if(attribute->have_arguments)
1544 parse_gnu_attribute_interrupt_arg(attribute);
1546 case GNU_AK_SENTINEL:
1547 /* may have one string argument */
1548 if(attribute->have_arguments)
1549 parse_gnu_attribute_const_arg(attribute);
1552 /* already handled */
1556 if(attribute != NULL) {
1558 last->next = attribute;
1561 head = last = attribute;
1565 if(token.type != ',')
1577 * Parse GNU attributes.
1579 static void parse_attributes(gnu_attribute_t **attributes)
1582 switch(token.type) {
1583 case T___attribute__: {
1584 parse_gnu_attribute(attributes);
1590 if(token.type != T_STRING_LITERAL) {
1591 parse_error_expected("while parsing assembler attribute",
1592 T_STRING_LITERAL, NULL);
1593 eat_until_matching_token('(');
1596 parse_string_literals();
1601 goto attributes_finished;
1605 attributes_finished:
1610 static designator_t *parse_designation(void)
1612 designator_t *result = NULL;
1613 designator_t *last = NULL;
1616 designator_t *designator;
1617 switch(token.type) {
1619 designator = allocate_ast_zero(sizeof(designator[0]));
1620 designator->source_position = token.source_position;
1622 add_anchor_token(']');
1623 designator->array_index = parse_constant_expression();
1624 rem_anchor_token(']');
1628 designator = allocate_ast_zero(sizeof(designator[0]));
1629 designator->source_position = token.source_position;
1631 if(token.type != T_IDENTIFIER) {
1632 parse_error_expected("while parsing designator",
1633 T_IDENTIFIER, NULL);
1636 designator->symbol = token.v.symbol;
1644 assert(designator != NULL);
1646 last->next = designator;
1648 result = designator;
1656 static initializer_t *initializer_from_string(array_type_t *type,
1657 const string_t *const string)
1659 /* TODO: check len vs. size of array type */
1662 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1663 initializer->string.string = *string;
1668 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1669 wide_string_t *const string)
1671 /* TODO: check len vs. size of array type */
1674 initializer_t *const initializer =
1675 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1676 initializer->wide_string.string = *string;
1682 * Build an initializer from a given expression.
1684 static initializer_t *initializer_from_expression(type_t *orig_type,
1685 expression_t *expression)
1687 /* TODO check that expression is a constant expression */
1689 /* § 6.7.8.14/15 char array may be initialized by string literals */
1690 type_t *type = skip_typeref(orig_type);
1691 type_t *expr_type_orig = expression->base.type;
1692 type_t *expr_type = skip_typeref(expr_type_orig);
1693 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1694 array_type_t *const array_type = &type->array;
1695 type_t *const element_type = skip_typeref(array_type->element_type);
1697 if (element_type->kind == TYPE_ATOMIC) {
1698 atomic_type_kind_t akind = element_type->atomic.akind;
1699 switch (expression->kind) {
1700 case EXPR_STRING_LITERAL:
1701 if (akind == ATOMIC_TYPE_CHAR
1702 || akind == ATOMIC_TYPE_SCHAR
1703 || akind == ATOMIC_TYPE_UCHAR) {
1704 return initializer_from_string(array_type,
1705 &expression->string.value);
1708 case EXPR_WIDE_STRING_LITERAL: {
1709 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1710 if (get_unqualified_type(element_type) == bare_wchar_type) {
1711 return initializer_from_wide_string(array_type,
1712 &expression->wide_string.value);
1722 type_t *const res_type = semantic_assign(type, expression, "initializer",
1723 &expression->base.source_position);
1724 if (res_type == NULL)
1727 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1728 result->value.value = create_implicit_cast(expression, res_type);
1734 * Checks if a given expression can be used as an constant initializer.
1736 static bool is_initializer_constant(const expression_t *expression)
1738 return is_constant_expression(expression)
1739 || is_address_constant(expression);
1743 * Parses an scalar initializer.
1745 * § 6.7.8.11; eat {} without warning
1747 static initializer_t *parse_scalar_initializer(type_t *type,
1748 bool must_be_constant)
1750 /* there might be extra {} hierarchies */
1752 while(token.type == '{') {
1755 warningf(HERE, "extra curly braces around scalar initializer");
1760 expression_t *expression = parse_assignment_expression();
1761 if(must_be_constant && !is_initializer_constant(expression)) {
1762 errorf(&expression->base.source_position,
1763 "Initialisation expression '%E' is not constant\n",
1767 initializer_t *initializer = initializer_from_expression(type, expression);
1769 if(initializer == NULL) {
1770 errorf(&expression->base.source_position,
1771 "expression '%E' (type '%T') doesn't match expected type '%T'",
1772 expression, expression->base.type, type);
1777 bool additional_warning_displayed = false;
1779 if(token.type == ',') {
1782 if(token.type != '}') {
1783 if(!additional_warning_displayed) {
1784 warningf(HERE, "additional elements in scalar initializer");
1785 additional_warning_displayed = true;
1796 * An entry in the type path.
1798 typedef struct type_path_entry_t type_path_entry_t;
1799 struct type_path_entry_t {
1800 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1802 size_t index; /**< For array types: the current index. */
1803 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1808 * A type path expression a position inside compound or array types.
1810 typedef struct type_path_t type_path_t;
1811 struct type_path_t {
1812 type_path_entry_t *path; /**< An flexible array containing the current path. */
1813 type_t *top_type; /**< type of the element the path points */
1814 size_t max_index; /**< largest index in outermost array */
1818 * Prints a type path for debugging.
1820 static __attribute__((unused)) void debug_print_type_path(
1821 const type_path_t *path)
1823 size_t len = ARR_LEN(path->path);
1825 for(size_t i = 0; i < len; ++i) {
1826 const type_path_entry_t *entry = & path->path[i];
1828 type_t *type = skip_typeref(entry->type);
1829 if(is_type_compound(type)) {
1830 /* in gcc mode structs can have no members */
1831 if(entry->v.compound_entry == NULL) {
1835 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1836 } else if(is_type_array(type)) {
1837 fprintf(stderr, "[%zd]", entry->v.index);
1839 fprintf(stderr, "-INVALID-");
1842 if(path->top_type != NULL) {
1843 fprintf(stderr, " (");
1844 print_type(path->top_type);
1845 fprintf(stderr, ")");
1850 * Return the top type path entry, ie. in a path
1851 * (type).a.b returns the b.
1853 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1855 size_t len = ARR_LEN(path->path);
1857 return &path->path[len-1];
1861 * Enlarge the type path by an (empty) element.
1863 static type_path_entry_t *append_to_type_path(type_path_t *path)
1865 size_t len = ARR_LEN(path->path);
1866 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1868 type_path_entry_t *result = & path->path[len];
1869 memset(result, 0, sizeof(result[0]));
1874 * Descending into a sub-type. Enter the scope of the current
1877 static void descend_into_subtype(type_path_t *path)
1879 type_t *orig_top_type = path->top_type;
1880 type_t *top_type = skip_typeref(orig_top_type);
1882 assert(is_type_compound(top_type) || is_type_array(top_type));
1884 type_path_entry_t *top = append_to_type_path(path);
1885 top->type = top_type;
1887 if(is_type_compound(top_type)) {
1888 declaration_t *declaration = top_type->compound.declaration;
1889 declaration_t *entry = declaration->scope.declarations;
1890 top->v.compound_entry = entry;
1893 path->top_type = entry->type;
1895 path->top_type = NULL;
1898 assert(is_type_array(top_type));
1901 path->top_type = top_type->array.element_type;
1906 * Pop an entry from the given type path, ie. returning from
1907 * (type).a.b to (type).a
1909 static void ascend_from_subtype(type_path_t *path)
1911 type_path_entry_t *top = get_type_path_top(path);
1913 path->top_type = top->type;
1915 size_t len = ARR_LEN(path->path);
1916 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1920 * Pop entries from the given type path until the given
1921 * path level is reached.
1923 static void ascend_to(type_path_t *path, size_t top_path_level)
1925 size_t len = ARR_LEN(path->path);
1927 while(len > top_path_level) {
1928 ascend_from_subtype(path);
1929 len = ARR_LEN(path->path);
1933 static bool walk_designator(type_path_t *path, const designator_t *designator,
1934 bool used_in_offsetof)
1936 for( ; designator != NULL; designator = designator->next) {
1937 type_path_entry_t *top = get_type_path_top(path);
1938 type_t *orig_type = top->type;
1940 type_t *type = skip_typeref(orig_type);
1942 if(designator->symbol != NULL) {
1943 symbol_t *symbol = designator->symbol;
1944 if(!is_type_compound(type)) {
1945 if(is_type_valid(type)) {
1946 errorf(&designator->source_position,
1947 "'.%Y' designator used for non-compound type '%T'",
1953 declaration_t *declaration = type->compound.declaration;
1954 declaration_t *iter = declaration->scope.declarations;
1955 for( ; iter != NULL; iter = iter->next) {
1956 if(iter->symbol == symbol) {
1961 errorf(&designator->source_position,
1962 "'%T' has no member named '%Y'", orig_type, symbol);
1965 if(used_in_offsetof) {
1966 type_t *real_type = skip_typeref(iter->type);
1967 if(real_type->kind == TYPE_BITFIELD) {
1968 errorf(&designator->source_position,
1969 "offsetof designator '%Y' may not specify bitfield",
1975 top->type = orig_type;
1976 top->v.compound_entry = iter;
1977 orig_type = iter->type;
1979 expression_t *array_index = designator->array_index;
1980 assert(designator->array_index != NULL);
1982 if(!is_type_array(type)) {
1983 if(is_type_valid(type)) {
1984 errorf(&designator->source_position,
1985 "[%E] designator used for non-array type '%T'",
1986 array_index, orig_type);
1990 if(!is_type_valid(array_index->base.type)) {
1994 long index = fold_constant(array_index);
1995 if(!used_in_offsetof) {
1997 errorf(&designator->source_position,
1998 "array index [%E] must be positive", array_index);
2001 if(type->array.size_constant == true) {
2002 long array_size = type->array.size;
2003 if(index >= array_size) {
2004 errorf(&designator->source_position,
2005 "designator [%E] (%d) exceeds array size %d",
2006 array_index, index, array_size);
2012 top->type = orig_type;
2013 top->v.index = (size_t) index;
2014 orig_type = type->array.element_type;
2016 path->top_type = orig_type;
2018 if(designator->next != NULL) {
2019 descend_into_subtype(path);
2028 static void advance_current_object(type_path_t *path, size_t top_path_level)
2030 type_path_entry_t *top = get_type_path_top(path);
2032 type_t *type = skip_typeref(top->type);
2033 if(is_type_union(type)) {
2034 /* in unions only the first element is initialized */
2035 top->v.compound_entry = NULL;
2036 } else if(is_type_struct(type)) {
2037 declaration_t *entry = top->v.compound_entry;
2039 entry = entry->next;
2040 top->v.compound_entry = entry;
2042 path->top_type = entry->type;
2046 assert(is_type_array(type));
2050 if(!type->array.size_constant || top->v.index < type->array.size) {
2055 /* we're past the last member of the current sub-aggregate, try if we
2056 * can ascend in the type hierarchy and continue with another subobject */
2057 size_t len = ARR_LEN(path->path);
2059 if(len > top_path_level) {
2060 ascend_from_subtype(path);
2061 advance_current_object(path, top_path_level);
2063 path->top_type = NULL;
2068 * skip until token is found.
2070 static void skip_until(int type) {
2071 while(token.type != type) {
2072 if(token.type == T_EOF)
2079 * skip any {...} blocks until a closing bracket is reached.
2081 static void skip_initializers(void)
2083 if(token.type == '{')
2086 while(token.type != '}') {
2087 if(token.type == T_EOF)
2089 if(token.type == '{') {
2097 static initializer_t *create_empty_initializer(void)
2099 static initializer_t empty_initializer
2100 = { .list = { { INITIALIZER_LIST }, 0 } };
2101 return &empty_initializer;
2105 * Parse a part of an initialiser for a struct or union,
2107 static initializer_t *parse_sub_initializer(type_path_t *path,
2108 type_t *outer_type, size_t top_path_level,
2109 parse_initializer_env_t *env)
2111 if(token.type == '}') {
2112 /* empty initializer */
2113 return create_empty_initializer();
2116 type_t *orig_type = path->top_type;
2117 type_t *type = NULL;
2119 if (orig_type == NULL) {
2120 /* We are initializing an empty compound. */
2122 type = skip_typeref(orig_type);
2124 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2125 * initializers in this case. */
2126 if(!is_type_valid(type)) {
2127 skip_initializers();
2128 return create_empty_initializer();
2132 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2135 designator_t *designator = NULL;
2136 if(token.type == '.' || token.type == '[') {
2137 designator = parse_designation();
2139 /* reset path to toplevel, evaluate designator from there */
2140 ascend_to(path, top_path_level);
2141 if(!walk_designator(path, designator, false)) {
2142 /* can't continue after designation error */
2146 initializer_t *designator_initializer
2147 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2148 designator_initializer->designator.designator = designator;
2149 ARR_APP1(initializer_t*, initializers, designator_initializer);
2154 if(token.type == '{') {
2155 if(type != NULL && is_type_scalar(type)) {
2156 sub = parse_scalar_initializer(type, env->must_be_constant);
2160 if (env->declaration != NULL)
2161 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2162 env->declaration->symbol);
2164 errorf(HERE, "extra brace group at end of initializer");
2166 descend_into_subtype(path);
2168 add_anchor_token('}');
2169 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2171 rem_anchor_token('}');
2174 ascend_from_subtype(path);
2178 goto error_parse_next;
2182 /* must be an expression */
2183 expression_t *expression = parse_assignment_expression();
2185 if(env->must_be_constant && !is_initializer_constant(expression)) {
2186 errorf(&expression->base.source_position,
2187 "Initialisation expression '%E' is not constant\n",
2192 /* we are already outside, ... */
2196 /* handle { "string" } special case */
2197 if((expression->kind == EXPR_STRING_LITERAL
2198 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2199 && outer_type != NULL) {
2200 sub = initializer_from_expression(outer_type, expression);
2202 if(token.type == ',') {
2205 if(token.type != '}') {
2206 warningf(HERE, "excessive elements in initializer for type '%T'",
2209 /* TODO: eat , ... */
2214 /* descend into subtypes until expression matches type */
2216 orig_type = path->top_type;
2217 type = skip_typeref(orig_type);
2219 sub = initializer_from_expression(orig_type, expression);
2223 if(!is_type_valid(type)) {
2226 if(is_type_scalar(type)) {
2227 errorf(&expression->base.source_position,
2228 "expression '%E' doesn't match expected type '%T'",
2229 expression, orig_type);
2233 descend_into_subtype(path);
2237 /* update largest index of top array */
2238 const type_path_entry_t *first = &path->path[0];
2239 type_t *first_type = first->type;
2240 first_type = skip_typeref(first_type);
2241 if(is_type_array(first_type)) {
2242 size_t index = first->v.index;
2243 if(index > path->max_index)
2244 path->max_index = index;
2248 /* append to initializers list */
2249 ARR_APP1(initializer_t*, initializers, sub);
2252 if(env->declaration != NULL)
2253 warningf(HERE, "excess elements in struct initializer for '%Y'",
2254 env->declaration->symbol);
2256 warningf(HERE, "excess elements in struct initializer");
2260 if(token.type == '}') {
2264 if(token.type == '}') {
2269 /* advance to the next declaration if we are not at the end */
2270 advance_current_object(path, top_path_level);
2271 orig_type = path->top_type;
2272 if(orig_type != NULL)
2273 type = skip_typeref(orig_type);
2279 size_t len = ARR_LEN(initializers);
2280 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2281 initializer_t *result = allocate_ast_zero(size);
2282 result->kind = INITIALIZER_LIST;
2283 result->list.len = len;
2284 memcpy(&result->list.initializers, initializers,
2285 len * sizeof(initializers[0]));
2287 DEL_ARR_F(initializers);
2288 ascend_to(path, top_path_level);
2293 skip_initializers();
2294 DEL_ARR_F(initializers);
2295 ascend_to(path, top_path_level);
2300 * Parses an initializer. Parsers either a compound literal
2301 * (env->declaration == NULL) or an initializer of a declaration.
2303 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2305 type_t *type = skip_typeref(env->type);
2306 initializer_t *result = NULL;
2309 if(is_type_scalar(type)) {
2310 result = parse_scalar_initializer(type, env->must_be_constant);
2311 } else if(token.type == '{') {
2315 memset(&path, 0, sizeof(path));
2316 path.top_type = env->type;
2317 path.path = NEW_ARR_F(type_path_entry_t, 0);
2319 descend_into_subtype(&path);
2321 add_anchor_token('}');
2322 result = parse_sub_initializer(&path, env->type, 1, env);
2323 rem_anchor_token('}');
2325 max_index = path.max_index;
2326 DEL_ARR_F(path.path);
2330 /* parse_scalar_initializer() also works in this case: we simply
2331 * have an expression without {} around it */
2332 result = parse_scalar_initializer(type, env->must_be_constant);
2335 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2336 * the array type size */
2337 if(is_type_array(type) && type->array.size_expression == NULL
2338 && result != NULL) {
2340 switch (result->kind) {
2341 case INITIALIZER_LIST:
2342 size = max_index + 1;
2345 case INITIALIZER_STRING:
2346 size = result->string.string.size;
2349 case INITIALIZER_WIDE_STRING:
2350 size = result->wide_string.string.size;
2354 internal_errorf(HERE, "invalid initializer type");
2357 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2358 cnst->base.type = type_size_t;
2359 cnst->conste.v.int_value = size;
2361 type_t *new_type = duplicate_type(type);
2363 new_type->array.size_expression = cnst;
2364 new_type->array.size_constant = true;
2365 new_type->array.size = size;
2366 env->type = new_type;
2374 static declaration_t *append_declaration(declaration_t *declaration);
2376 static declaration_t *parse_compound_type_specifier(bool is_struct)
2378 gnu_attribute_t *attributes = NULL;
2385 symbol_t *symbol = NULL;
2386 declaration_t *declaration = NULL;
2388 if (token.type == T___attribute__) {
2389 parse_attributes(&attributes);
2392 if(token.type == T_IDENTIFIER) {
2393 symbol = token.v.symbol;
2397 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2399 declaration = get_declaration(symbol, NAMESPACE_UNION);
2401 } else if(token.type != '{') {
2403 parse_error_expected("while parsing struct type specifier",
2404 T_IDENTIFIER, '{', NULL);
2406 parse_error_expected("while parsing union type specifier",
2407 T_IDENTIFIER, '{', NULL);
2413 if(declaration == NULL) {
2414 declaration = allocate_declaration_zero();
2415 declaration->namespc =
2416 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2417 declaration->source_position = token.source_position;
2418 declaration->symbol = symbol;
2419 declaration->parent_scope = scope;
2420 if (symbol != NULL) {
2421 environment_push(declaration);
2423 append_declaration(declaration);
2426 if(token.type == '{') {
2427 if(declaration->init.is_defined) {
2428 assert(symbol != NULL);
2429 errorf(HERE, "multiple definitions of '%s %Y'",
2430 is_struct ? "struct" : "union", symbol);
2431 declaration->scope.declarations = NULL;
2433 declaration->init.is_defined = true;
2435 parse_compound_type_entries(declaration);
2436 parse_attributes(&attributes);
2442 static void parse_enum_entries(type_t *const enum_type)
2446 if(token.type == '}') {
2448 errorf(HERE, "empty enum not allowed");
2452 add_anchor_token('}');
2454 if(token.type != T_IDENTIFIER) {
2455 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2457 rem_anchor_token('}');
2461 declaration_t *const entry = allocate_declaration_zero();
2462 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2463 entry->type = enum_type;
2464 entry->symbol = token.v.symbol;
2465 entry->source_position = token.source_position;
2468 if(token.type == '=') {
2470 expression_t *value = parse_constant_expression();
2472 value = create_implicit_cast(value, enum_type);
2473 entry->init.enum_value = value;
2478 record_declaration(entry);
2480 if(token.type != ',')
2483 } while(token.type != '}');
2484 rem_anchor_token('}');
2492 static type_t *parse_enum_specifier(void)
2494 gnu_attribute_t *attributes = NULL;
2495 declaration_t *declaration;
2499 if(token.type == T_IDENTIFIER) {
2500 symbol = token.v.symbol;
2503 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2504 } else if(token.type != '{') {
2505 parse_error_expected("while parsing enum type specifier",
2506 T_IDENTIFIER, '{', NULL);
2513 if(declaration == NULL) {
2514 declaration = allocate_declaration_zero();
2515 declaration->namespc = NAMESPACE_ENUM;
2516 declaration->source_position = token.source_position;
2517 declaration->symbol = symbol;
2518 declaration->parent_scope = scope;
2521 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2522 type->enumt.declaration = declaration;
2524 if(token.type == '{') {
2525 if(declaration->init.is_defined) {
2526 errorf(HERE, "multiple definitions of enum %Y", symbol);
2528 if (symbol != NULL) {
2529 environment_push(declaration);
2531 append_declaration(declaration);
2532 declaration->init.is_defined = 1;
2534 parse_enum_entries(type);
2535 parse_attributes(&attributes);
2542 * if a symbol is a typedef to another type, return true
2544 static bool is_typedef_symbol(symbol_t *symbol)
2546 const declaration_t *const declaration =
2547 get_declaration(symbol, NAMESPACE_NORMAL);
2549 declaration != NULL &&
2550 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2553 static type_t *parse_typeof(void)
2560 add_anchor_token(')');
2562 expression_t *expression = NULL;
2565 switch(token.type) {
2566 case T___extension__:
2567 /* this can be a prefix to a typename or an expression */
2568 /* we simply eat it now. */
2571 } while(token.type == T___extension__);
2575 if(is_typedef_symbol(token.v.symbol)) {
2576 type = parse_typename();
2578 expression = parse_expression();
2579 type = expression->base.type;
2584 type = parse_typename();
2588 expression = parse_expression();
2589 type = expression->base.type;
2593 rem_anchor_token(')');
2596 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2597 typeof_type->typeoft.expression = expression;
2598 typeof_type->typeoft.typeof_type = type;
2606 SPECIFIER_SIGNED = 1 << 0,
2607 SPECIFIER_UNSIGNED = 1 << 1,
2608 SPECIFIER_LONG = 1 << 2,
2609 SPECIFIER_INT = 1 << 3,
2610 SPECIFIER_DOUBLE = 1 << 4,
2611 SPECIFIER_CHAR = 1 << 5,
2612 SPECIFIER_SHORT = 1 << 6,
2613 SPECIFIER_LONG_LONG = 1 << 7,
2614 SPECIFIER_FLOAT = 1 << 8,
2615 SPECIFIER_BOOL = 1 << 9,
2616 SPECIFIER_VOID = 1 << 10,
2617 SPECIFIER_INT8 = 1 << 11,
2618 SPECIFIER_INT16 = 1 << 12,
2619 SPECIFIER_INT32 = 1 << 13,
2620 SPECIFIER_INT64 = 1 << 14,
2621 SPECIFIER_INT128 = 1 << 15,
2622 SPECIFIER_COMPLEX = 1 << 16,
2623 SPECIFIER_IMAGINARY = 1 << 17,
2626 static type_t *create_builtin_type(symbol_t *const symbol,
2627 type_t *const real_type)
2629 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2630 type->builtin.symbol = symbol;
2631 type->builtin.real_type = real_type;
2633 type_t *result = typehash_insert(type);
2634 if(type != result) {
2641 static type_t *get_typedef_type(symbol_t *symbol)
2643 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2644 if(declaration == NULL ||
2645 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2648 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2649 type->typedeft.declaration = declaration;
2655 * check for the allowed MS alignment values.
2657 static bool check_elignment_value(long long intvalue) {
2658 if(intvalue < 1 || intvalue > 8192) {
2659 errorf(HERE, "illegal alignment value");
2662 unsigned v = (unsigned)intvalue;
2663 for(unsigned i = 1; i <= 8192; i += i) {
2667 errorf(HERE, "alignment must be power of two");
2671 #define DET_MOD(name, tag) do { \
2672 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2673 *modifiers |= tag; \
2676 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2678 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2681 if(token.type == T_restrict) {
2683 DET_MOD(restrict, DM_RESTRICT);
2685 } else if(token.type != T_IDENTIFIER)
2687 symbol_t *symbol = token.v.symbol;
2688 if(symbol == sym_align) {
2691 if(token.type != T_INTEGER)
2693 if(check_elignment_value(token.v.intvalue)) {
2694 if(specifiers->alignment != 0)
2695 warningf(HERE, "align used more than once");
2696 specifiers->alignment = (unsigned char)token.v.intvalue;
2700 } else if(symbol == sym_allocate) {
2703 if(token.type != T_IDENTIFIER)
2705 (void)token.v.symbol;
2707 } else if(symbol == sym_dllimport) {
2709 DET_MOD(dllimport, DM_DLLIMPORT);
2710 } else if(symbol == sym_dllexport) {
2712 DET_MOD(dllexport, DM_DLLEXPORT);
2713 } else if(symbol == sym_thread) {
2715 DET_MOD(thread, DM_THREAD);
2716 } else if(symbol == sym_naked) {
2718 DET_MOD(naked, DM_NAKED);
2719 } else if(symbol == sym_noinline) {
2721 DET_MOD(noinline, DM_NOINLINE);
2722 } else if(symbol == sym_noreturn) {
2724 DET_MOD(noreturn, DM_NORETURN);
2725 } else if(symbol == sym_nothrow) {
2727 DET_MOD(nothrow, DM_NOTHROW);
2728 } else if(symbol == sym_novtable) {
2730 DET_MOD(novtable, DM_NOVTABLE);
2731 } else if(symbol == sym_property) {
2735 bool is_get = false;
2736 if(token.type != T_IDENTIFIER)
2738 if(token.v.symbol == sym_get) {
2740 } else if(token.v.symbol == sym_put) {
2742 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2747 if(token.type != T_IDENTIFIER)
2750 if(specifiers->get_property_sym != NULL) {
2751 errorf(HERE, "get property name already specified");
2753 specifiers->get_property_sym = token.v.symbol;
2756 if(specifiers->put_property_sym != NULL) {
2757 errorf(HERE, "put property name already specified");
2759 specifiers->put_property_sym = token.v.symbol;
2763 if(token.type == ',') {
2770 } else if(symbol == sym_selectany) {
2772 DET_MOD(selectany, DM_SELECTANY);
2773 } else if(symbol == sym_uuid) {
2776 if(token.type != T_STRING_LITERAL)
2780 } else if(symbol == sym_deprecated) {
2782 if(specifiers->deprecated != 0)
2783 warningf(HERE, "deprecated used more than once");
2784 specifiers->deprecated = 1;
2785 if(token.type == '(') {
2787 if(token.type == T_STRING_LITERAL) {
2788 specifiers->deprecated_string = token.v.string.begin;
2791 errorf(HERE, "string literal expected");
2795 } else if(symbol == sym_noalias) {
2797 DET_MOD(noalias, DM_NOALIAS);
2799 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2801 if(token.type == '(')
2805 if (token.type == ',')
2812 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2814 type_t *type = NULL;
2815 unsigned type_qualifiers = 0;
2816 unsigned type_specifiers = 0;
2819 specifiers->source_position = token.source_position;
2822 switch(token.type) {
2825 #define MATCH_STORAGE_CLASS(token, class) \
2827 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2828 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2830 specifiers->declared_storage_class = class; \
2834 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2835 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2836 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2837 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2838 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2843 add_anchor_token(')');
2844 parse_microsoft_extended_decl_modifier(specifiers);
2845 rem_anchor_token(')');
2850 switch (specifiers->declared_storage_class) {
2851 case STORAGE_CLASS_NONE:
2852 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2855 case STORAGE_CLASS_EXTERN:
2856 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2859 case STORAGE_CLASS_STATIC:
2860 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2864 errorf(HERE, "multiple storage classes in declaration specifiers");
2870 /* type qualifiers */
2871 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2873 type_qualifiers |= qualifier; \
2877 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2878 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2879 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2880 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2881 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2882 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2883 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2884 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2886 case T___extension__:
2891 /* type specifiers */
2892 #define MATCH_SPECIFIER(token, specifier, name) \
2895 if(type_specifiers & specifier) { \
2896 errorf(HERE, "multiple " name " type specifiers given"); \
2898 type_specifiers |= specifier; \
2902 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2903 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2904 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2905 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2906 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2907 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2908 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2909 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2910 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2911 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2912 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2913 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2914 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2915 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2916 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2917 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2919 case T__forceinline:
2920 /* only in microsoft mode */
2921 specifiers->decl_modifiers |= DM_FORCEINLINE;
2925 specifiers->is_inline = true;
2930 if(type_specifiers & SPECIFIER_LONG_LONG) {
2931 errorf(HERE, "multiple type specifiers given");
2932 } else if(type_specifiers & SPECIFIER_LONG) {
2933 type_specifiers |= SPECIFIER_LONG_LONG;
2935 type_specifiers |= SPECIFIER_LONG;
2940 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2942 type->compound.declaration = parse_compound_type_specifier(true);
2946 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2948 type->compound.declaration = parse_compound_type_specifier(false);
2952 type = parse_enum_specifier();
2955 type = parse_typeof();
2957 case T___builtin_va_list:
2958 type = duplicate_type(type_valist);
2962 case T___attribute__:
2963 parse_attributes(&specifiers->gnu_attributes);
2966 case T_IDENTIFIER: {
2967 /* only parse identifier if we haven't found a type yet */
2968 if(type != NULL || type_specifiers != 0)
2969 goto finish_specifiers;
2971 type_t *typedef_type = get_typedef_type(token.v.symbol);
2973 if(typedef_type == NULL)
2974 goto finish_specifiers;
2977 type = typedef_type;
2981 /* function specifier */
2983 goto finish_specifiers;
2990 atomic_type_kind_t atomic_type;
2992 /* match valid basic types */
2993 switch(type_specifiers) {
2994 case SPECIFIER_VOID:
2995 atomic_type = ATOMIC_TYPE_VOID;
2997 case SPECIFIER_CHAR:
2998 atomic_type = ATOMIC_TYPE_CHAR;
3000 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3001 atomic_type = ATOMIC_TYPE_SCHAR;
3003 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3004 atomic_type = ATOMIC_TYPE_UCHAR;
3006 case SPECIFIER_SHORT:
3007 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3008 case SPECIFIER_SHORT | SPECIFIER_INT:
3009 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3010 atomic_type = ATOMIC_TYPE_SHORT;
3012 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3013 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3014 atomic_type = ATOMIC_TYPE_USHORT;
3017 case SPECIFIER_SIGNED:
3018 case SPECIFIER_SIGNED | SPECIFIER_INT:
3019 atomic_type = ATOMIC_TYPE_INT;
3021 case SPECIFIER_UNSIGNED:
3022 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3023 atomic_type = ATOMIC_TYPE_UINT;
3025 case SPECIFIER_LONG:
3026 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3027 case SPECIFIER_LONG | SPECIFIER_INT:
3028 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3029 atomic_type = ATOMIC_TYPE_LONG;
3031 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3032 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3033 atomic_type = ATOMIC_TYPE_ULONG;
3035 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3036 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3037 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3038 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3040 atomic_type = ATOMIC_TYPE_LONGLONG;
3042 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3043 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3045 atomic_type = ATOMIC_TYPE_ULONGLONG;
3048 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3049 atomic_type = unsigned_int8_type_kind;
3052 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3053 atomic_type = unsigned_int16_type_kind;
3056 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3057 atomic_type = unsigned_int32_type_kind;
3060 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3061 atomic_type = unsigned_int64_type_kind;
3064 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3065 atomic_type = unsigned_int128_type_kind;
3068 case SPECIFIER_INT8:
3069 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3070 atomic_type = int8_type_kind;
3073 case SPECIFIER_INT16:
3074 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3075 atomic_type = int16_type_kind;
3078 case SPECIFIER_INT32:
3079 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3080 atomic_type = int32_type_kind;
3083 case SPECIFIER_INT64:
3084 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3085 atomic_type = int64_type_kind;
3088 case SPECIFIER_INT128:
3089 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3090 atomic_type = int128_type_kind;
3093 case SPECIFIER_FLOAT:
3094 atomic_type = ATOMIC_TYPE_FLOAT;
3096 case SPECIFIER_DOUBLE:
3097 atomic_type = ATOMIC_TYPE_DOUBLE;
3099 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3100 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3102 case SPECIFIER_BOOL:
3103 atomic_type = ATOMIC_TYPE_BOOL;
3105 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3106 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3107 atomic_type = ATOMIC_TYPE_FLOAT;
3109 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3110 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3111 atomic_type = ATOMIC_TYPE_DOUBLE;
3113 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3114 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3115 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3118 /* invalid specifier combination, give an error message */
3119 if(type_specifiers == 0) {
3120 if (! strict_mode) {
3121 if (warning.implicit_int) {
3122 warningf(HERE, "no type specifiers in declaration, using 'int'");
3124 atomic_type = ATOMIC_TYPE_INT;
3127 errorf(HERE, "no type specifiers given in declaration");
3129 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3130 (type_specifiers & SPECIFIER_UNSIGNED)) {
3131 errorf(HERE, "signed and unsigned specifiers gives");
3132 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3133 errorf(HERE, "only integer types can be signed or unsigned");
3135 errorf(HERE, "multiple datatypes in declaration");
3137 atomic_type = ATOMIC_TYPE_INVALID;
3140 if(type_specifiers & SPECIFIER_COMPLEX &&
3141 atomic_type != ATOMIC_TYPE_INVALID) {
3142 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3143 type->complex.akind = atomic_type;
3144 } else if(type_specifiers & SPECIFIER_IMAGINARY &&
3145 atomic_type != ATOMIC_TYPE_INVALID) {
3146 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3147 type->imaginary.akind = atomic_type;
3149 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3150 type->atomic.akind = atomic_type;
3154 if(type_specifiers != 0) {
3155 errorf(HERE, "multiple datatypes in declaration");
3159 type->base.qualifiers = type_qualifiers;
3160 /* FIXME: check type qualifiers here */
3162 type_t *result = typehash_insert(type);
3163 if(newtype && result != type) {
3167 specifiers->type = result;
3172 static type_qualifiers_t parse_type_qualifiers(void)
3174 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3177 switch(token.type) {
3178 /* type qualifiers */
3179 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3180 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3181 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3182 /* microsoft extended type modifiers */
3183 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3184 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3185 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3186 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3187 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3190 return type_qualifiers;
3195 static declaration_t *parse_identifier_list(void)
3197 declaration_t *declarations = NULL;
3198 declaration_t *last_declaration = NULL;
3200 declaration_t *const declaration = allocate_declaration_zero();
3201 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3202 declaration->source_position = token.source_position;
3203 declaration->symbol = token.v.symbol;
3206 if(last_declaration != NULL) {
3207 last_declaration->next = declaration;
3209 declarations = declaration;
3211 last_declaration = declaration;
3213 if(token.type != ',')
3216 } while(token.type == T_IDENTIFIER);
3218 return declarations;
3221 static void semantic_parameter(declaration_t *declaration)
3223 /* TODO: improve error messages */
3225 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3226 errorf(HERE, "typedef not allowed in parameter list");
3227 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3228 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3229 errorf(HERE, "parameter may only have none or register storage class");
3232 type_t *const orig_type = declaration->type;
3233 type_t * type = skip_typeref(orig_type);
3235 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3236 * into a pointer. § 6.7.5.3 (7) */
3237 if (is_type_array(type)) {
3238 type_t *const element_type = type->array.element_type;
3240 type = make_pointer_type(element_type, type->base.qualifiers);
3242 declaration->type = type;
3245 if(is_type_incomplete(type)) {
3246 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3247 orig_type, declaration->symbol);
3251 static declaration_t *parse_parameter(void)
3253 declaration_specifiers_t specifiers;
3254 memset(&specifiers, 0, sizeof(specifiers));
3256 parse_declaration_specifiers(&specifiers);
3258 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3260 semantic_parameter(declaration);
3265 static declaration_t *parse_parameters(function_type_t *type)
3267 if(token.type == T_IDENTIFIER) {
3268 symbol_t *symbol = token.v.symbol;
3269 if(!is_typedef_symbol(symbol)) {
3270 type->kr_style_parameters = true;
3271 return parse_identifier_list();
3275 if(token.type == ')') {
3276 type->unspecified_parameters = 1;
3279 if(token.type == T_void && look_ahead(1)->type == ')') {
3284 declaration_t *declarations = NULL;
3285 declaration_t *declaration;
3286 declaration_t *last_declaration = NULL;
3287 function_parameter_t *parameter;
3288 function_parameter_t *last_parameter = NULL;
3291 switch(token.type) {
3295 return declarations;
3298 case T___extension__:
3300 declaration = parse_parameter();
3302 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3303 memset(parameter, 0, sizeof(parameter[0]));
3304 parameter->type = declaration->type;
3306 if(last_parameter != NULL) {
3307 last_declaration->next = declaration;
3308 last_parameter->next = parameter;
3310 type->parameters = parameter;
3311 declarations = declaration;
3313 last_parameter = parameter;
3314 last_declaration = declaration;
3318 return declarations;
3320 if(token.type != ',')
3321 return declarations;
3331 } construct_type_kind_t;
3333 typedef struct construct_type_t construct_type_t;
3334 struct construct_type_t {
3335 construct_type_kind_t kind;
3336 construct_type_t *next;
3339 typedef struct parsed_pointer_t parsed_pointer_t;
3340 struct parsed_pointer_t {
3341 construct_type_t construct_type;
3342 type_qualifiers_t type_qualifiers;
3345 typedef struct construct_function_type_t construct_function_type_t;
3346 struct construct_function_type_t {
3347 construct_type_t construct_type;
3348 type_t *function_type;
3351 typedef struct parsed_array_t parsed_array_t;
3352 struct parsed_array_t {
3353 construct_type_t construct_type;
3354 type_qualifiers_t type_qualifiers;
3360 typedef struct construct_base_type_t construct_base_type_t;
3361 struct construct_base_type_t {
3362 construct_type_t construct_type;
3366 static construct_type_t *parse_pointer_declarator(void)
3370 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3371 memset(pointer, 0, sizeof(pointer[0]));
3372 pointer->construct_type.kind = CONSTRUCT_POINTER;
3373 pointer->type_qualifiers = parse_type_qualifiers();
3375 return (construct_type_t*) pointer;
3378 static construct_type_t *parse_array_declarator(void)
3381 add_anchor_token(']');
3383 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3384 memset(array, 0, sizeof(array[0]));
3385 array->construct_type.kind = CONSTRUCT_ARRAY;
3387 if(token.type == T_static) {
3388 array->is_static = true;
3392 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3393 if(type_qualifiers != 0) {
3394 if(token.type == T_static) {
3395 array->is_static = true;
3399 array->type_qualifiers = type_qualifiers;
3401 if(token.type == '*' && look_ahead(1)->type == ']') {
3402 array->is_variable = true;
3404 } else if(token.type != ']') {
3405 array->size = parse_assignment_expression();
3408 rem_anchor_token(']');
3411 return (construct_type_t*) array;
3416 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3419 add_anchor_token(')');
3422 if(declaration != NULL) {
3423 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3425 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3428 declaration_t *parameters = parse_parameters(&type->function);
3429 if(declaration != NULL) {
3430 declaration->scope.declarations = parameters;
3433 construct_function_type_t *construct_function_type =
3434 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3435 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3436 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3437 construct_function_type->function_type = type;
3439 rem_anchor_token(')');
3443 return (construct_type_t*) construct_function_type;
3446 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3447 bool may_be_abstract)
3449 /* construct a single linked list of construct_type_t's which describe
3450 * how to construct the final declarator type */
3451 construct_type_t *first = NULL;
3452 construct_type_t *last = NULL;
3453 gnu_attribute_t *attributes = NULL;
3456 while(token.type == '*') {
3457 construct_type_t *type = parse_pointer_declarator();
3468 /* TODO: find out if this is correct */
3469 parse_attributes(&attributes);
3471 construct_type_t *inner_types = NULL;
3473 switch(token.type) {
3475 if(declaration == NULL) {
3476 errorf(HERE, "no identifier expected in typename");
3478 declaration->symbol = token.v.symbol;
3479 declaration->source_position = token.source_position;
3485 add_anchor_token(')');
3486 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3487 rem_anchor_token(')');
3493 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3494 /* avoid a loop in the outermost scope, because eat_statement doesn't
3496 if(token.type == '}' && current_function == NULL) {
3504 construct_type_t *p = last;
3507 construct_type_t *type;
3508 switch(token.type) {
3510 type = parse_function_declarator(declaration);
3513 type = parse_array_declarator();
3516 goto declarator_finished;
3519 /* insert in the middle of the list (behind p) */
3521 type->next = p->next;
3532 declarator_finished:
3533 parse_attributes(&attributes);
3535 /* append inner_types at the end of the list, we don't to set last anymore
3536 * as it's not needed anymore */
3538 assert(first == NULL);
3539 first = inner_types;
3541 last->next = inner_types;
3549 static type_t *construct_declarator_type(construct_type_t *construct_list,
3552 construct_type_t *iter = construct_list;
3553 for( ; iter != NULL; iter = iter->next) {
3554 switch(iter->kind) {
3555 case CONSTRUCT_INVALID:
3556 internal_errorf(HERE, "invalid type construction found");
3557 case CONSTRUCT_FUNCTION: {
3558 construct_function_type_t *construct_function_type
3559 = (construct_function_type_t*) iter;
3561 type_t *function_type = construct_function_type->function_type;
3563 function_type->function.return_type = type;
3565 type_t *skipped_return_type = skip_typeref(type);
3566 if (is_type_function(skipped_return_type)) {
3567 errorf(HERE, "function returning function is not allowed");
3568 type = type_error_type;
3569 } else if (is_type_array(skipped_return_type)) {
3570 errorf(HERE, "function returning array is not allowed");
3571 type = type_error_type;
3573 type = function_type;
3578 case CONSTRUCT_POINTER: {
3579 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3580 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3581 pointer_type->pointer.points_to = type;
3582 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3584 type = pointer_type;
3588 case CONSTRUCT_ARRAY: {
3589 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3590 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3592 expression_t *size_expression = parsed_array->size;
3593 if(size_expression != NULL) {
3595 = create_implicit_cast(size_expression, type_size_t);
3598 array_type->base.qualifiers = parsed_array->type_qualifiers;
3599 array_type->array.element_type = type;
3600 array_type->array.is_static = parsed_array->is_static;
3601 array_type->array.is_variable = parsed_array->is_variable;
3602 array_type->array.size_expression = size_expression;
3604 if(size_expression != NULL) {
3605 if(is_constant_expression(size_expression)) {
3606 array_type->array.size_constant = true;
3607 array_type->array.size
3608 = fold_constant(size_expression);
3610 array_type->array.is_vla = true;
3614 type_t *skipped_type = skip_typeref(type);
3615 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3616 errorf(HERE, "array of void is not allowed");
3617 type = type_error_type;
3625 type_t *hashed_type = typehash_insert(type);
3626 if(hashed_type != type) {
3627 /* the function type was constructed earlier freeing it here will
3628 * destroy other types... */
3629 if(iter->kind != CONSTRUCT_FUNCTION) {
3639 static declaration_t *parse_declarator(
3640 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3642 declaration_t *const declaration = allocate_declaration_zero();
3643 declaration->declared_storage_class = specifiers->declared_storage_class;
3644 declaration->decl_modifiers = specifiers->decl_modifiers;
3645 declaration->deprecated = specifiers->deprecated;
3646 declaration->deprecated_string = specifiers->deprecated_string;
3647 declaration->get_property_sym = specifiers->get_property_sym;
3648 declaration->put_property_sym = specifiers->put_property_sym;
3649 declaration->is_inline = specifiers->is_inline;
3651 declaration->storage_class = specifiers->declared_storage_class;
3652 if(declaration->storage_class == STORAGE_CLASS_NONE
3653 && scope != global_scope) {
3654 declaration->storage_class = STORAGE_CLASS_AUTO;
3657 if(specifiers->alignment != 0) {
3658 /* TODO: add checks here */
3659 declaration->alignment = specifiers->alignment;
3662 construct_type_t *construct_type
3663 = parse_inner_declarator(declaration, may_be_abstract);
3664 type_t *const type = specifiers->type;
3665 declaration->type = construct_declarator_type(construct_type, type);
3667 if(construct_type != NULL) {
3668 obstack_free(&temp_obst, construct_type);
3674 static type_t *parse_abstract_declarator(type_t *base_type)
3676 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3678 type_t *result = construct_declarator_type(construct_type, base_type);
3679 if(construct_type != NULL) {
3680 obstack_free(&temp_obst, construct_type);
3686 static declaration_t *append_declaration(declaration_t* const declaration)
3688 if (last_declaration != NULL) {
3689 last_declaration->next = declaration;
3691 scope->declarations = declaration;
3693 last_declaration = declaration;
3698 * Check if the declaration of main is suspicious. main should be a
3699 * function with external linkage, returning int, taking either zero
3700 * arguments, two, or three arguments of appropriate types, ie.
3702 * int main([ int argc, char **argv [, char **env ] ]).
3704 * @param decl the declaration to check
3705 * @param type the function type of the declaration
3707 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3709 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3710 warningf(&decl->source_position,
3711 "'main' is normally a non-static function");
3713 if (skip_typeref(func_type->return_type) != type_int) {
3714 warningf(&decl->source_position,
3715 "return type of 'main' should be 'int', but is '%T'",
3716 func_type->return_type);
3718 const function_parameter_t *parm = func_type->parameters;
3720 type_t *const first_type = parm->type;
3721 if (!types_compatible(skip_typeref(first_type), type_int)) {
3722 warningf(&decl->source_position,
3723 "first argument of 'main' should be 'int', but is '%T'", first_type);
3727 type_t *const second_type = parm->type;
3728 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3729 warningf(&decl->source_position,
3730 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3734 type_t *const third_type = parm->type;
3735 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3736 warningf(&decl->source_position,
3737 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3741 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3745 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3751 * Check if a symbol is the equal to "main".
3753 static bool is_sym_main(const symbol_t *const sym)
3755 return strcmp(sym->string, "main") == 0;
3758 static declaration_t *internal_record_declaration(
3759 declaration_t *const declaration,
3760 const bool is_function_definition)
3762 const symbol_t *const symbol = declaration->symbol;
3763 const namespace_t namespc = (namespace_t)declaration->namespc;
3765 type_t *const orig_type = declaration->type;
3766 type_t *const type = skip_typeref(orig_type);
3767 if (is_type_function(type) &&
3768 type->function.unspecified_parameters &&
3769 warning.strict_prototypes) {
3770 warningf(&declaration->source_position,
3771 "function declaration '%#T' is not a prototype",
3772 orig_type, declaration->symbol);
3775 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3776 check_type_of_main(declaration, &type->function);
3779 assert(declaration->symbol != NULL);
3780 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3782 assert(declaration != previous_declaration);
3783 if (previous_declaration != NULL) {
3784 if (previous_declaration->parent_scope == scope) {
3785 /* can happen for K&R style declarations */
3786 if(previous_declaration->type == NULL) {
3787 previous_declaration->type = declaration->type;
3790 const type_t *prev_type = skip_typeref(previous_declaration->type);
3791 if (!types_compatible(type, prev_type)) {
3792 errorf(&declaration->source_position,
3793 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3794 orig_type, symbol, previous_declaration->type, symbol,
3795 &previous_declaration->source_position);
3797 unsigned old_storage_class = previous_declaration->storage_class;
3798 if(old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3799 errorf(&declaration->source_position,
3800 "redeclaration of enum entry '%Y' (declared %P)",
3801 symbol, &previous_declaration->source_position);
3802 return previous_declaration;
3805 unsigned new_storage_class = declaration->storage_class;
3807 if(is_type_incomplete(prev_type)) {
3808 previous_declaration->type = type;
3812 /* pretend no storage class means extern for function
3813 * declarations (except if the previous declaration is neither
3814 * none nor extern) */
3815 if (is_type_function(type)) {
3816 switch (old_storage_class) {
3817 case STORAGE_CLASS_NONE:
3818 old_storage_class = STORAGE_CLASS_EXTERN;
3820 case STORAGE_CLASS_EXTERN:
3821 if (is_function_definition) {
3822 if (warning.missing_prototypes &&
3823 prev_type->function.unspecified_parameters &&
3824 !is_sym_main(symbol)) {
3825 warningf(&declaration->source_position,
3826 "no previous prototype for '%#T'",
3829 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3830 new_storage_class = STORAGE_CLASS_EXTERN;
3838 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3839 new_storage_class == STORAGE_CLASS_EXTERN) {
3840 warn_redundant_declaration:
3841 if (warning.redundant_decls) {
3842 warningf(&declaration->source_position,
3843 "redundant declaration for '%Y' (declared %P)",
3844 symbol, &previous_declaration->source_position);
3846 } else if (current_function == NULL) {
3847 if (old_storage_class != STORAGE_CLASS_STATIC &&
3848 new_storage_class == STORAGE_CLASS_STATIC) {
3849 errorf(&declaration->source_position,
3850 "static declaration of '%Y' follows non-static declaration (declared %P)",
3851 symbol, &previous_declaration->source_position);
3853 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3854 goto warn_redundant_declaration;
3856 if (new_storage_class == STORAGE_CLASS_NONE) {
3857 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3858 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3862 if (old_storage_class == new_storage_class) {
3863 errorf(&declaration->source_position,
3864 "redeclaration of '%Y' (declared %P)",
3865 symbol, &previous_declaration->source_position);
3867 errorf(&declaration->source_position,
3868 "redeclaration of '%Y' with different linkage (declared %P)",
3869 symbol, &previous_declaration->source_position);
3873 return previous_declaration;
3875 } else if (is_function_definition) {
3876 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3877 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3878 warningf(&declaration->source_position,
3879 "no previous prototype for '%#T'", orig_type, symbol);
3880 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3881 warningf(&declaration->source_position,
3882 "no previous declaration for '%#T'", orig_type,
3886 } else if (warning.missing_declarations &&
3887 scope == global_scope &&
3888 !is_type_function(type) && (
3889 declaration->storage_class == STORAGE_CLASS_NONE ||
3890 declaration->storage_class == STORAGE_CLASS_THREAD
3892 warningf(&declaration->source_position,
3893 "no previous declaration for '%#T'", orig_type, symbol);
3896 assert(declaration->parent_scope == NULL);
3897 assert(scope != NULL);
3899 declaration->parent_scope = scope;
3901 environment_push(declaration);
3902 return append_declaration(declaration);
3905 static declaration_t *record_declaration(declaration_t *declaration)
3907 return internal_record_declaration(declaration, false);
3910 static declaration_t *record_function_definition(declaration_t *declaration)
3912 return internal_record_declaration(declaration, true);
3915 static void parser_error_multiple_definition(declaration_t *declaration,
3916 const source_position_t *source_position)
3918 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
3919 declaration->symbol, &declaration->source_position);
3922 static bool is_declaration_specifier(const token_t *token,
3923 bool only_type_specifiers)
3925 switch(token->type) {
3929 return is_typedef_symbol(token->v.symbol);
3931 case T___extension__:
3934 return !only_type_specifiers;
3941 static void parse_init_declarator_rest(declaration_t *declaration)
3945 type_t *orig_type = declaration->type;
3946 type_t *type = skip_typeref(orig_type);
3948 if(declaration->init.initializer != NULL) {
3949 parser_error_multiple_definition(declaration, HERE);
3952 bool must_be_constant = false;
3953 if(declaration->storage_class == STORAGE_CLASS_STATIC
3954 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3955 || declaration->parent_scope == global_scope) {
3956 must_be_constant = true;
3959 parse_initializer_env_t env;
3960 env.type = orig_type;
3961 env.must_be_constant = must_be_constant;
3962 env.declaration = declaration;
3964 initializer_t *initializer = parse_initializer(&env);
3966 if(env.type != orig_type) {
3967 orig_type = env.type;
3968 type = skip_typeref(orig_type);
3969 declaration->type = env.type;
3972 if(is_type_function(type)) {
3973 errorf(&declaration->source_position,
3974 "initializers not allowed for function types at declator '%Y' (type '%T')",
3975 declaration->symbol, orig_type);
3977 declaration->init.initializer = initializer;
3981 /* parse rest of a declaration without any declarator */
3982 static void parse_anonymous_declaration_rest(
3983 const declaration_specifiers_t *specifiers,
3984 parsed_declaration_func finished_declaration)
3988 declaration_t *const declaration = allocate_declaration_zero();
3989 declaration->type = specifiers->type;
3990 declaration->declared_storage_class = specifiers->declared_storage_class;
3991 declaration->source_position = specifiers->source_position;
3992 declaration->decl_modifiers = specifiers->decl_modifiers;
3994 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3995 warningf(&declaration->source_position,
3996 "useless storage class in empty declaration");
3998 declaration->storage_class = STORAGE_CLASS_NONE;
4000 type_t *type = declaration->type;
4001 switch (type->kind) {
4002 case TYPE_COMPOUND_STRUCT:
4003 case TYPE_COMPOUND_UNION: {
4004 if (type->compound.declaration->symbol == NULL) {
4005 warningf(&declaration->source_position,
4006 "unnamed struct/union that defines no instances");
4015 warningf(&declaration->source_position, "empty declaration");
4019 finished_declaration(declaration);
4022 static void parse_declaration_rest(declaration_t *ndeclaration,
4023 const declaration_specifiers_t *specifiers,
4024 parsed_declaration_func finished_declaration)
4026 add_anchor_token(';');
4027 add_anchor_token('=');
4028 add_anchor_token(',');
4030 declaration_t *declaration = finished_declaration(ndeclaration);
4032 type_t *orig_type = declaration->type;
4033 type_t *type = skip_typeref(orig_type);
4035 if (type->kind != TYPE_FUNCTION &&
4036 declaration->is_inline &&
4037 is_type_valid(type)) {
4038 warningf(&declaration->source_position,
4039 "variable '%Y' declared 'inline'\n", declaration->symbol);
4042 if(token.type == '=') {
4043 parse_init_declarator_rest(declaration);
4046 if(token.type != ',')
4050 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4055 rem_anchor_token(';');
4056 rem_anchor_token('=');
4057 rem_anchor_token(',');
4060 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4062 symbol_t *symbol = declaration->symbol;
4063 if(symbol == NULL) {
4064 errorf(HERE, "anonymous declaration not valid as function parameter");
4067 namespace_t namespc = (namespace_t) declaration->namespc;
4068 if(namespc != NAMESPACE_NORMAL) {
4069 return record_declaration(declaration);
4072 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4073 if(previous_declaration == NULL ||
4074 previous_declaration->parent_scope != scope) {
4075 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4080 if(previous_declaration->type == NULL) {
4081 previous_declaration->type = declaration->type;
4082 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4083 previous_declaration->storage_class = declaration->storage_class;
4084 previous_declaration->parent_scope = scope;
4085 return previous_declaration;
4087 return record_declaration(declaration);
4091 static void parse_declaration(parsed_declaration_func finished_declaration)
4093 declaration_specifiers_t specifiers;
4094 memset(&specifiers, 0, sizeof(specifiers));
4095 parse_declaration_specifiers(&specifiers);
4097 if(token.type == ';') {
4098 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4100 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4101 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4105 static void parse_kr_declaration_list(declaration_t *declaration)
4107 type_t *type = skip_typeref(declaration->type);
4108 if(!is_type_function(type))
4111 if(!type->function.kr_style_parameters)
4114 /* push function parameters */
4115 int top = environment_top();
4116 scope_t *last_scope = scope;
4117 set_scope(&declaration->scope);
4119 declaration_t *parameter = declaration->scope.declarations;
4120 for( ; parameter != NULL; parameter = parameter->next) {
4121 assert(parameter->parent_scope == NULL);
4122 parameter->parent_scope = scope;
4123 environment_push(parameter);
4126 /* parse declaration list */
4127 while(is_declaration_specifier(&token, false)) {
4128 parse_declaration(finished_kr_declaration);
4131 /* pop function parameters */
4132 assert(scope == &declaration->scope);
4133 set_scope(last_scope);
4134 environment_pop_to(top);
4136 /* update function type */
4137 type_t *new_type = duplicate_type(type);
4138 new_type->function.kr_style_parameters = false;
4140 function_parameter_t *parameters = NULL;
4141 function_parameter_t *last_parameter = NULL;
4143 declaration_t *parameter_declaration = declaration->scope.declarations;
4144 for( ; parameter_declaration != NULL;
4145 parameter_declaration = parameter_declaration->next) {
4146 type_t *parameter_type = parameter_declaration->type;
4147 if(parameter_type == NULL) {
4149 errorf(HERE, "no type specified for function parameter '%Y'",
4150 parameter_declaration->symbol);
4152 if (warning.implicit_int) {
4153 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4154 parameter_declaration->symbol);
4156 parameter_type = type_int;
4157 parameter_declaration->type = parameter_type;
4161 semantic_parameter(parameter_declaration);
4162 parameter_type = parameter_declaration->type;
4164 function_parameter_t *function_parameter
4165 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4166 memset(function_parameter, 0, sizeof(function_parameter[0]));
4168 function_parameter->type = parameter_type;
4169 if(last_parameter != NULL) {
4170 last_parameter->next = function_parameter;
4172 parameters = function_parameter;
4174 last_parameter = function_parameter;
4176 new_type->function.parameters = parameters;
4178 type = typehash_insert(new_type);
4179 if(type != new_type) {
4180 obstack_free(type_obst, new_type);
4183 declaration->type = type;
4186 static bool first_err = true;
4189 * When called with first_err set, prints the name of the current function,
4192 static void print_in_function(void) {
4195 diagnosticf("%s: In function '%Y':\n",
4196 current_function->source_position.input_name,
4197 current_function->symbol);
4202 * Check if all labels are defined in the current function.
4203 * Check if all labels are used in the current function.
4205 static void check_labels(void)
4207 for (const goto_statement_t *goto_statement = goto_first;
4208 goto_statement != NULL;
4209 goto_statement = goto_statement->next) {
4210 declaration_t *label = goto_statement->label;
4213 if (label->source_position.input_name == NULL) {
4214 print_in_function();
4215 errorf(&goto_statement->base.source_position,
4216 "label '%Y' used but not defined", label->symbol);
4219 goto_first = goto_last = NULL;
4221 if (warning.unused_label) {
4222 for (const label_statement_t *label_statement = label_first;
4223 label_statement != NULL;
4224 label_statement = label_statement->next) {
4225 const declaration_t *label = label_statement->label;
4227 if (! label->used) {
4228 print_in_function();
4229 warningf(&label_statement->base.source_position,
4230 "label '%Y' defined but not used", label->symbol);
4234 label_first = label_last = NULL;
4238 * Check declarations of current_function for unused entities.
4240 static void check_declarations(void)
4242 if (warning.unused_parameter) {
4243 const scope_t *scope = ¤t_function->scope;
4245 const declaration_t *parameter = scope->declarations;
4246 for (; parameter != NULL; parameter = parameter->next) {
4247 if (! parameter->used) {
4248 print_in_function();
4249 warningf(¶meter->source_position,
4250 "unused parameter '%Y'", parameter->symbol);
4254 if (warning.unused_variable) {
4258 static void parse_external_declaration(void)
4260 /* function-definitions and declarations both start with declaration
4262 declaration_specifiers_t specifiers;
4263 memset(&specifiers, 0, sizeof(specifiers));
4265 add_anchor_token(';');
4266 parse_declaration_specifiers(&specifiers);
4267 rem_anchor_token(';');
4269 /* must be a declaration */
4270 if(token.type == ';') {
4271 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4275 add_anchor_token(',');
4276 add_anchor_token('=');
4277 rem_anchor_token(';');
4279 /* declarator is common to both function-definitions and declarations */
4280 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4282 rem_anchor_token(',');
4283 rem_anchor_token('=');
4284 rem_anchor_token(';');
4286 /* must be a declaration */
4287 if(token.type == ',' || token.type == '=' || token.type == ';') {
4288 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4292 /* must be a function definition */
4293 parse_kr_declaration_list(ndeclaration);
4295 if(token.type != '{') {
4296 parse_error_expected("while parsing function definition", '{', NULL);
4297 eat_until_matching_token(';');
4301 type_t *type = ndeclaration->type;
4303 /* note that we don't skip typerefs: the standard doesn't allow them here
4304 * (so we can't use is_type_function here) */
4305 if(type->kind != TYPE_FUNCTION) {
4306 if (is_type_valid(type)) {
4307 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4308 type, ndeclaration->symbol);
4314 /* § 6.7.5.3 (14) a function definition with () means no
4315 * parameters (and not unspecified parameters) */
4316 if(type->function.unspecified_parameters) {
4317 type_t *duplicate = duplicate_type(type);
4318 duplicate->function.unspecified_parameters = false;
4320 type = typehash_insert(duplicate);
4321 if(type != duplicate) {
4322 obstack_free(type_obst, duplicate);
4324 ndeclaration->type = type;
4327 declaration_t *const declaration = record_function_definition(ndeclaration);
4328 if(ndeclaration != declaration) {
4329 declaration->scope = ndeclaration->scope;
4331 type = skip_typeref(declaration->type);
4333 /* push function parameters and switch scope */
4334 int top = environment_top();
4335 scope_t *last_scope = scope;
4336 set_scope(&declaration->scope);
4338 declaration_t *parameter = declaration->scope.declarations;
4339 for( ; parameter != NULL; parameter = parameter->next) {
4340 if(parameter->parent_scope == &ndeclaration->scope) {
4341 parameter->parent_scope = scope;
4343 assert(parameter->parent_scope == NULL
4344 || parameter->parent_scope == scope);
4345 parameter->parent_scope = scope;
4346 environment_push(parameter);
4349 if(declaration->init.statement != NULL) {
4350 parser_error_multiple_definition(declaration, HERE);
4352 goto end_of_parse_external_declaration;
4354 /* parse function body */
4355 int label_stack_top = label_top();
4356 declaration_t *old_current_function = current_function;
4357 current_function = declaration;
4359 declaration->init.statement = parse_compound_statement(false);
4362 check_declarations();
4364 assert(current_function == declaration);
4365 current_function = old_current_function;
4366 label_pop_to(label_stack_top);
4369 end_of_parse_external_declaration:
4370 assert(scope == &declaration->scope);
4371 set_scope(last_scope);
4372 environment_pop_to(top);
4375 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4376 source_position_t *source_position)
4378 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4380 type->bitfield.base_type = base_type;
4381 type->bitfield.size = size;
4386 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4389 declaration_t *iter = compound_declaration->scope.declarations;
4390 for( ; iter != NULL; iter = iter->next) {
4391 if(iter->namespc != NAMESPACE_NORMAL)
4394 if(iter->symbol == NULL) {
4395 type_t *type = skip_typeref(iter->type);
4396 if(is_type_compound(type)) {
4397 declaration_t *result
4398 = find_compound_entry(type->compound.declaration, symbol);
4405 if(iter->symbol == symbol) {
4413 static void parse_compound_declarators(declaration_t *struct_declaration,
4414 const declaration_specifiers_t *specifiers)
4416 declaration_t *last_declaration = struct_declaration->scope.declarations;
4417 if(last_declaration != NULL) {
4418 while(last_declaration->next != NULL) {
4419 last_declaration = last_declaration->next;
4424 declaration_t *declaration;
4426 if(token.type == ':') {
4427 source_position_t source_position = *HERE;
4430 type_t *base_type = specifiers->type;
4431 expression_t *size = parse_constant_expression();
4433 if(!is_type_integer(skip_typeref(base_type))) {
4434 errorf(HERE, "bitfield base type '%T' is not an integer type",
4438 type_t *type = make_bitfield_type(base_type, size, &source_position);
4440 declaration = allocate_declaration_zero();
4441 declaration->namespc = NAMESPACE_NORMAL;
4442 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4443 declaration->storage_class = STORAGE_CLASS_NONE;
4444 declaration->source_position = source_position;
4445 declaration->decl_modifiers = specifiers->decl_modifiers;
4446 declaration->type = type;
4448 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4450 type_t *orig_type = declaration->type;
4451 type_t *type = skip_typeref(orig_type);
4453 if(token.type == ':') {
4454 source_position_t source_position = *HERE;
4456 expression_t *size = parse_constant_expression();
4458 if(!is_type_integer(type)) {
4459 errorf(HERE, "bitfield base type '%T' is not an "
4460 "integer type", orig_type);
4463 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4464 declaration->type = bitfield_type;
4466 /* TODO we ignore arrays for now... what is missing is a check
4467 * that they're at the end of the struct */
4468 if(is_type_incomplete(type) && !is_type_array(type)) {
4470 "compound member '%Y' has incomplete type '%T'",
4471 declaration->symbol, orig_type);
4472 } else if(is_type_function(type)) {
4473 errorf(HERE, "compound member '%Y' must not have function "
4474 "type '%T'", declaration->symbol, orig_type);
4479 /* make sure we don't define a symbol multiple times */
4480 symbol_t *symbol = declaration->symbol;
4481 if(symbol != NULL) {
4482 declaration_t *prev_decl
4483 = find_compound_entry(struct_declaration, symbol);
4485 if(prev_decl != NULL) {
4486 assert(prev_decl->symbol == symbol);
4487 errorf(&declaration->source_position,
4488 "multiple declarations of symbol '%Y' (declared %P)",
4489 symbol, &prev_decl->source_position);
4493 /* append declaration */
4494 if(last_declaration != NULL) {
4495 last_declaration->next = declaration;
4497 struct_declaration->scope.declarations = declaration;
4499 last_declaration = declaration;
4501 if(token.type != ',')
4511 static void parse_compound_type_entries(declaration_t *compound_declaration)
4514 add_anchor_token('}');
4516 while(token.type != '}' && token.type != T_EOF) {
4517 declaration_specifiers_t specifiers;
4518 memset(&specifiers, 0, sizeof(specifiers));
4519 parse_declaration_specifiers(&specifiers);
4521 parse_compound_declarators(compound_declaration, &specifiers);
4523 rem_anchor_token('}');
4525 if(token.type == T_EOF) {
4526 errorf(HERE, "EOF while parsing struct");
4531 static type_t *parse_typename(void)
4533 declaration_specifiers_t specifiers;
4534 memset(&specifiers, 0, sizeof(specifiers));
4535 parse_declaration_specifiers(&specifiers);
4536 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4537 /* TODO: improve error message, user does probably not know what a
4538 * storage class is...
4540 errorf(HERE, "typename may not have a storage class");
4543 type_t *result = parse_abstract_declarator(specifiers.type);
4551 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4552 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4553 expression_t *left);
4555 typedef struct expression_parser_function_t expression_parser_function_t;
4556 struct expression_parser_function_t {
4557 unsigned precedence;
4558 parse_expression_function parser;
4559 unsigned infix_precedence;
4560 parse_expression_infix_function infix_parser;
4563 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4566 * Prints an error message if an expression was expected but not read
4568 static expression_t *expected_expression_error(void)
4570 /* skip the error message if the error token was read */
4571 if (token.type != T_ERROR) {
4572 errorf(HERE, "expected expression, got token '%K'", &token);
4576 return create_invalid_expression();
4580 * Parse a string constant.
4582 static expression_t *parse_string_const(void)
4585 if (token.type == T_STRING_LITERAL) {
4586 string_t res = token.v.string;
4588 while (token.type == T_STRING_LITERAL) {
4589 res = concat_strings(&res, &token.v.string);
4592 if (token.type != T_WIDE_STRING_LITERAL) {
4593 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4594 /* note: that we use type_char_ptr here, which is already the
4595 * automatic converted type. revert_automatic_type_conversion
4596 * will construct the array type */
4597 cnst->base.type = type_char_ptr;
4598 cnst->string.value = res;
4602 wres = concat_string_wide_string(&res, &token.v.wide_string);
4604 wres = token.v.wide_string;
4609 switch (token.type) {
4610 case T_WIDE_STRING_LITERAL:
4611 wres = concat_wide_strings(&wres, &token.v.wide_string);
4614 case T_STRING_LITERAL:
4615 wres = concat_wide_string_string(&wres, &token.v.string);
4619 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4620 cnst->base.type = type_wchar_t_ptr;
4621 cnst->wide_string.value = wres;
4630 * Parse an integer constant.
4632 static expression_t *parse_int_const(void)
4634 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4635 cnst->base.source_position = *HERE;
4636 cnst->base.type = token.datatype;
4637 cnst->conste.v.int_value = token.v.intvalue;
4645 * Parse a character constant.
4647 static expression_t *parse_character_constant(void)
4649 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4651 cnst->base.source_position = *HERE;
4652 cnst->base.type = token.datatype;
4653 cnst->conste.v.character = token.v.string;
4655 if (cnst->conste.v.character.size != 1) {
4656 if (warning.multichar && (c_mode & _GNUC)) {
4658 warningf(HERE, "multi-character character constant");
4660 errorf(HERE, "more than 1 characters in character constant");
4669 * Parse a wide character constant.
4671 static expression_t *parse_wide_character_constant(void)
4673 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4675 cnst->base.source_position = *HERE;
4676 cnst->base.type = token.datatype;
4677 cnst->conste.v.wide_character = token.v.wide_string;
4679 if (cnst->conste.v.wide_character.size != 1) {
4680 if (warning.multichar && (c_mode & _GNUC)) {
4682 warningf(HERE, "multi-character character constant");
4684 errorf(HERE, "more than 1 characters in character constant");
4693 * Parse a float constant.
4695 static expression_t *parse_float_const(void)
4697 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4698 cnst->base.type = token.datatype;
4699 cnst->conste.v.float_value = token.v.floatvalue;
4706 static declaration_t *create_implicit_function(symbol_t *symbol,
4707 const source_position_t *source_position)
4709 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4710 ntype->function.return_type = type_int;
4711 ntype->function.unspecified_parameters = true;
4713 type_t *type = typehash_insert(ntype);
4718 declaration_t *const declaration = allocate_declaration_zero();
4719 declaration->storage_class = STORAGE_CLASS_EXTERN;
4720 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4721 declaration->type = type;
4722 declaration->symbol = symbol;
4723 declaration->source_position = *source_position;
4724 declaration->parent_scope = global_scope;
4726 scope_t *old_scope = scope;
4727 set_scope(global_scope);
4729 environment_push(declaration);
4730 /* prepends the declaration to the global declarations list */
4731 declaration->next = scope->declarations;
4732 scope->declarations = declaration;
4734 assert(scope == global_scope);
4735 set_scope(old_scope);
4741 * Creates a return_type (func)(argument_type) function type if not
4744 * @param return_type the return type
4745 * @param argument_type the argument type
4747 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4749 function_parameter_t *parameter
4750 = obstack_alloc(type_obst, sizeof(parameter[0]));
4751 memset(parameter, 0, sizeof(parameter[0]));
4752 parameter->type = argument_type;
4754 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4755 type->function.return_type = return_type;
4756 type->function.parameters = parameter;
4758 type_t *result = typehash_insert(type);
4759 if(result != type) {
4767 * Creates a function type for some function like builtins.
4769 * @param symbol the symbol describing the builtin
4771 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4773 switch(symbol->ID) {
4774 case T___builtin_alloca:
4775 return make_function_1_type(type_void_ptr, type_size_t);
4776 case T___builtin_nan:
4777 return make_function_1_type(type_double, type_char_ptr);
4778 case T___builtin_nanf:
4779 return make_function_1_type(type_float, type_char_ptr);
4780 case T___builtin_nand:
4781 return make_function_1_type(type_long_double, type_char_ptr);
4782 case T___builtin_va_end:
4783 return make_function_1_type(type_void, type_valist);
4785 internal_errorf(HERE, "not implemented builtin symbol found");
4790 * Performs automatic type cast as described in § 6.3.2.1.
4792 * @param orig_type the original type
4794 static type_t *automatic_type_conversion(type_t *orig_type)
4796 type_t *type = skip_typeref(orig_type);
4797 if(is_type_array(type)) {
4798 array_type_t *array_type = &type->array;
4799 type_t *element_type = array_type->element_type;
4800 unsigned qualifiers = array_type->base.qualifiers;
4802 return make_pointer_type(element_type, qualifiers);
4805 if(is_type_function(type)) {
4806 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4813 * reverts the automatic casts of array to pointer types and function
4814 * to function-pointer types as defined § 6.3.2.1
4816 type_t *revert_automatic_type_conversion(const expression_t *expression)
4818 switch (expression->kind) {
4819 case EXPR_REFERENCE: return expression->reference.declaration->type;
4820 case EXPR_SELECT: return expression->select.compound_entry->type;
4822 case EXPR_UNARY_DEREFERENCE: {
4823 const expression_t *const value = expression->unary.value;
4824 type_t *const type = skip_typeref(value->base.type);
4825 assert(is_type_pointer(type));
4826 return type->pointer.points_to;
4829 case EXPR_BUILTIN_SYMBOL:
4830 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4832 case EXPR_ARRAY_ACCESS: {
4833 const expression_t *array_ref = expression->array_access.array_ref;
4834 type_t *type_left = skip_typeref(array_ref->base.type);
4835 if (!is_type_valid(type_left))
4837 assert(is_type_pointer(type_left));
4838 return type_left->pointer.points_to;
4841 case EXPR_STRING_LITERAL: {
4842 size_t size = expression->string.value.size;
4843 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4846 case EXPR_WIDE_STRING_LITERAL: {
4847 size_t size = expression->wide_string.value.size;
4848 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4851 case EXPR_COMPOUND_LITERAL:
4852 return expression->compound_literal.type;
4857 return expression->base.type;
4860 static expression_t *parse_reference(void)
4862 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4864 reference_expression_t *ref = &expression->reference;
4865 symbol_t *const symbol = token.v.symbol;
4867 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
4869 source_position_t source_position = token.source_position;
4872 if(declaration == NULL) {
4873 if (! strict_mode && token.type == '(') {
4874 /* an implicitly defined function */
4875 if (warning.implicit_function_declaration) {
4876 warningf(HERE, "implicit declaration of function '%Y'",
4880 declaration = create_implicit_function(symbol,
4883 errorf(HERE, "unknown symbol '%Y' found.", symbol);
4884 return create_invalid_expression();
4888 type_t *type = declaration->type;
4890 /* we always do the auto-type conversions; the & and sizeof parser contains
4891 * code to revert this! */
4892 type = automatic_type_conversion(type);
4894 ref->declaration = declaration;
4895 ref->base.type = type;
4897 /* this declaration is used */
4898 declaration->used = true;
4900 /* check for deprecated functions */
4901 if(declaration->deprecated != 0) {
4902 const char *prefix = "";
4903 if (is_type_function(declaration->type))
4904 prefix = "function ";
4906 if (declaration->deprecated_string != NULL) {
4907 warningf(&source_position,
4908 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4909 declaration->deprecated_string);
4911 warningf(&source_position,
4912 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4919 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4923 /* TODO check if explicit cast is allowed and issue warnings/errors */
4926 static expression_t *parse_compound_literal(type_t *type)
4928 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4930 parse_initializer_env_t env;
4932 env.declaration = NULL;
4933 env.must_be_constant = false;
4934 initializer_t *initializer = parse_initializer(&env);
4937 expression->compound_literal.initializer = initializer;
4938 expression->compound_literal.type = type;
4939 expression->base.type = automatic_type_conversion(type);
4945 * Parse a cast expression.
4947 static expression_t *parse_cast(void)
4949 source_position_t source_position = token.source_position;
4951 type_t *type = parse_typename();
4953 /* matching add_anchor_token() is at call site */
4954 rem_anchor_token(')');
4957 if(token.type == '{') {
4958 return parse_compound_literal(type);
4961 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4962 cast->base.source_position = source_position;
4964 expression_t *value = parse_sub_expression(20);
4966 check_cast_allowed(value, type);
4968 cast->base.type = type;
4969 cast->unary.value = value;
4973 return create_invalid_expression();
4977 * Parse a statement expression.
4979 static expression_t *parse_statement_expression(void)
4981 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4983 statement_t *statement = parse_compound_statement(true);
4984 expression->statement.statement = statement;
4985 expression->base.source_position = statement->base.source_position;
4987 /* find last statement and use its type */
4988 type_t *type = type_void;
4989 const statement_t *stmt = statement->compound.statements;
4991 while (stmt->base.next != NULL)
4992 stmt = stmt->base.next;
4994 if (stmt->kind == STATEMENT_EXPRESSION) {
4995 type = stmt->expression.expression->base.type;
4998 warningf(&expression->base.source_position, "empty statement expression ({})");
5000 expression->base.type = type;
5006 return create_invalid_expression();
5010 * Parse a braced expression.
5012 static expression_t *parse_brace_expression(void)
5015 add_anchor_token(')');
5017 switch(token.type) {
5019 /* gcc extension: a statement expression */
5020 return parse_statement_expression();
5024 return parse_cast();
5026 if(is_typedef_symbol(token.v.symbol)) {
5027 return parse_cast();
5031 expression_t *result = parse_expression();
5032 rem_anchor_token(')');
5037 return create_invalid_expression();
5040 static expression_t *parse_function_keyword(void)
5045 if (current_function == NULL) {
5046 errorf(HERE, "'__func__' used outside of a function");
5049 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5050 expression->base.type = type_char_ptr;
5051 expression->funcname.kind = FUNCNAME_FUNCTION;
5056 static expression_t *parse_pretty_function_keyword(void)
5058 eat(T___PRETTY_FUNCTION__);
5060 if (current_function == NULL) {
5061 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5064 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5065 expression->base.type = type_char_ptr;
5066 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5071 static expression_t *parse_funcsig_keyword(void)
5075 if (current_function == NULL) {
5076 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5079 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5080 expression->base.type = type_char_ptr;
5081 expression->funcname.kind = FUNCNAME_FUNCSIG;
5086 static expression_t *parse_funcdname_keyword(void)
5088 eat(T___FUNCDNAME__);
5090 if (current_function == NULL) {
5091 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5094 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5095 expression->base.type = type_char_ptr;
5096 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5101 static designator_t *parse_designator(void)
5103 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5104 result->source_position = *HERE;
5106 if(token.type != T_IDENTIFIER) {
5107 parse_error_expected("while parsing member designator",
5108 T_IDENTIFIER, NULL);
5111 result->symbol = token.v.symbol;
5114 designator_t *last_designator = result;
5116 if(token.type == '.') {
5118 if(token.type != T_IDENTIFIER) {
5119 parse_error_expected("while parsing member designator",
5120 T_IDENTIFIER, NULL);
5123 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5124 designator->source_position = *HERE;
5125 designator->symbol = token.v.symbol;
5128 last_designator->next = designator;
5129 last_designator = designator;
5132 if(token.type == '[') {
5134 add_anchor_token(']');
5135 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5136 designator->source_position = *HERE;
5137 designator->array_index = parse_expression();
5138 rem_anchor_token(']');
5140 if(designator->array_index == NULL) {
5144 last_designator->next = designator;
5145 last_designator = designator;
5157 * Parse the __builtin_offsetof() expression.
5159 static expression_t *parse_offsetof(void)
5161 eat(T___builtin_offsetof);
5163 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5164 expression->base.type = type_size_t;
5167 add_anchor_token(',');
5168 type_t *type = parse_typename();
5169 rem_anchor_token(',');
5171 add_anchor_token(')');
5172 designator_t *designator = parse_designator();
5173 rem_anchor_token(')');
5176 expression->offsetofe.type = type;
5177 expression->offsetofe.designator = designator;
5180 memset(&path, 0, sizeof(path));
5181 path.top_type = type;
5182 path.path = NEW_ARR_F(type_path_entry_t, 0);
5184 descend_into_subtype(&path);
5186 if(!walk_designator(&path, designator, true)) {
5187 return create_invalid_expression();
5190 DEL_ARR_F(path.path);
5194 return create_invalid_expression();
5198 * Parses a _builtin_va_start() expression.
5200 static expression_t *parse_va_start(void)
5202 eat(T___builtin_va_start);
5204 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5207 add_anchor_token(',');
5208 expression->va_starte.ap = parse_assignment_expression();
5209 rem_anchor_token(',');
5211 expression_t *const expr = parse_assignment_expression();
5212 if (expr->kind == EXPR_REFERENCE) {
5213 declaration_t *const decl = expr->reference.declaration;
5215 return create_invalid_expression();
5216 if (decl->parent_scope == ¤t_function->scope &&
5217 decl->next == NULL) {
5218 expression->va_starte.parameter = decl;
5223 errorf(&expr->base.source_position,
5224 "second argument of 'va_start' must be last parameter of the current function");
5226 return create_invalid_expression();
5230 * Parses a _builtin_va_arg() expression.
5232 static expression_t *parse_va_arg(void)
5234 eat(T___builtin_va_arg);
5236 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5239 expression->va_arge.ap = parse_assignment_expression();
5241 expression->base.type = parse_typename();
5246 return create_invalid_expression();
5249 static expression_t *parse_builtin_symbol(void)
5251 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5253 symbol_t *symbol = token.v.symbol;
5255 expression->builtin_symbol.symbol = symbol;
5258 type_t *type = get_builtin_symbol_type(symbol);
5259 type = automatic_type_conversion(type);
5261 expression->base.type = type;
5266 * Parses a __builtin_constant() expression.
5268 static expression_t *parse_builtin_constant(void)
5270 eat(T___builtin_constant_p);
5272 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5275 add_anchor_token(')');
5276 expression->builtin_constant.value = parse_assignment_expression();
5277 rem_anchor_token(')');
5279 expression->base.type = type_int;
5283 return create_invalid_expression();
5287 * Parses a __builtin_prefetch() expression.
5289 static expression_t *parse_builtin_prefetch(void)
5291 eat(T___builtin_prefetch);
5293 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5296 add_anchor_token(')');
5297 expression->builtin_prefetch.adr = parse_assignment_expression();
5298 if (token.type == ',') {
5300 expression->builtin_prefetch.rw = parse_assignment_expression();
5302 if (token.type == ',') {
5304 expression->builtin_prefetch.locality = parse_assignment_expression();
5306 rem_anchor_token(')');
5308 expression->base.type = type_void;
5312 return create_invalid_expression();
5316 * Parses a __builtin_is_*() compare expression.
5318 static expression_t *parse_compare_builtin(void)
5320 expression_t *expression;
5322 switch(token.type) {
5323 case T___builtin_isgreater:
5324 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5326 case T___builtin_isgreaterequal:
5327 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5329 case T___builtin_isless:
5330 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5332 case T___builtin_islessequal:
5333 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5335 case T___builtin_islessgreater:
5336 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5338 case T___builtin_isunordered:
5339 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5342 internal_errorf(HERE, "invalid compare builtin found");
5345 expression->base.source_position = *HERE;
5349 expression->binary.left = parse_assignment_expression();
5351 expression->binary.right = parse_assignment_expression();
5354 type_t *const orig_type_left = expression->binary.left->base.type;
5355 type_t *const orig_type_right = expression->binary.right->base.type;
5357 type_t *const type_left = skip_typeref(orig_type_left);
5358 type_t *const type_right = skip_typeref(orig_type_right);
5359 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5360 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5361 type_error_incompatible("invalid operands in comparison",
5362 &expression->base.source_position, orig_type_left, orig_type_right);
5365 semantic_comparison(&expression->binary);
5370 return create_invalid_expression();
5374 * Parses a __builtin_expect() expression.
5376 static expression_t *parse_builtin_expect(void)
5378 eat(T___builtin_expect);
5380 expression_t *expression
5381 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5384 expression->binary.left = parse_assignment_expression();
5386 expression->binary.right = parse_constant_expression();
5389 expression->base.type = expression->binary.left->base.type;
5393 return create_invalid_expression();
5397 * Parses a MS assume() expression.
5399 static expression_t *parse_assume(void) {
5402 expression_t *expression
5403 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5406 add_anchor_token(')');
5407 expression->unary.value = parse_assignment_expression();
5408 rem_anchor_token(')');
5411 expression->base.type = type_void;
5414 return create_invalid_expression();
5418 * Parse a microsoft __noop expression.
5420 static expression_t *parse_noop_expression(void) {
5421 source_position_t source_position = *HERE;
5424 if (token.type == '(') {
5425 /* parse arguments */
5427 add_anchor_token(')');
5428 add_anchor_token(',');
5430 if(token.type != ')') {
5432 (void)parse_assignment_expression();
5433 if(token.type != ',')
5439 rem_anchor_token(',');
5440 rem_anchor_token(')');
5443 /* the result is a (int)0 */
5444 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5445 cnst->base.source_position = source_position;
5446 cnst->base.type = type_int;
5447 cnst->conste.v.int_value = 0;
5448 cnst->conste.is_ms_noop = true;
5453 return create_invalid_expression();
5457 * Parses a primary expression.
5459 static expression_t *parse_primary_expression(void)
5461 switch (token.type) {
5462 case T_INTEGER: return parse_int_const();
5463 case T_CHARACTER_CONSTANT: return parse_character_constant();
5464 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5465 case T_FLOATINGPOINT: return parse_float_const();
5466 case T_STRING_LITERAL:
5467 case T_WIDE_STRING_LITERAL: return parse_string_const();
5468 case T_IDENTIFIER: return parse_reference();
5469 case T___FUNCTION__:
5470 case T___func__: return parse_function_keyword();
5471 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5472 case T___FUNCSIG__: return parse_funcsig_keyword();
5473 case T___FUNCDNAME__: return parse_funcdname_keyword();
5474 case T___builtin_offsetof: return parse_offsetof();
5475 case T___builtin_va_start: return parse_va_start();
5476 case T___builtin_va_arg: return parse_va_arg();
5477 case T___builtin_expect: return parse_builtin_expect();
5478 case T___builtin_alloca:
5479 case T___builtin_nan:
5480 case T___builtin_nand:
5481 case T___builtin_nanf:
5482 case T___builtin_va_end: return parse_builtin_symbol();
5483 case T___builtin_isgreater:
5484 case T___builtin_isgreaterequal:
5485 case T___builtin_isless:
5486 case T___builtin_islessequal:
5487 case T___builtin_islessgreater:
5488 case T___builtin_isunordered: return parse_compare_builtin();
5489 case T___builtin_constant_p: return parse_builtin_constant();
5490 case T___builtin_prefetch: return parse_builtin_prefetch();
5491 case T__assume: return parse_assume();
5493 case '(': return parse_brace_expression();
5494 case T___noop: return parse_noop_expression();
5497 errorf(HERE, "unexpected token %K, expected an expression", &token);
5498 return create_invalid_expression();
5502 * Check if the expression has the character type and issue a warning then.
5504 static void check_for_char_index_type(const expression_t *expression) {
5505 type_t *const type = expression->base.type;
5506 const type_t *const base_type = skip_typeref(type);
5508 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5509 warning.char_subscripts) {
5510 warningf(&expression->base.source_position,
5511 "array subscript has type '%T'", type);
5515 static expression_t *parse_array_expression(unsigned precedence,
5521 add_anchor_token(']');
5523 expression_t *inside = parse_expression();
5525 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5527 array_access_expression_t *array_access = &expression->array_access;
5529 type_t *const orig_type_left = left->base.type;
5530 type_t *const orig_type_inside = inside->base.type;
5532 type_t *const type_left = skip_typeref(orig_type_left);
5533 type_t *const type_inside = skip_typeref(orig_type_inside);
5535 type_t *return_type;
5536 if (is_type_pointer(type_left)) {
5537 return_type = type_left->pointer.points_to;
5538 array_access->array_ref = left;
5539 array_access->index = inside;
5540 check_for_char_index_type(inside);
5541 } else if (is_type_pointer(type_inside)) {
5542 return_type = type_inside->pointer.points_to;
5543 array_access->array_ref = inside;
5544 array_access->index = left;
5545 array_access->flipped = true;
5546 check_for_char_index_type(left);
5548 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5550 "array access on object with non-pointer types '%T', '%T'",
5551 orig_type_left, orig_type_inside);
5553 return_type = type_error_type;
5554 array_access->array_ref = create_invalid_expression();
5557 rem_anchor_token(']');
5558 if(token.type != ']') {
5559 parse_error_expected("Problem while parsing array access", ']', NULL);
5564 return_type = automatic_type_conversion(return_type);
5565 expression->base.type = return_type;
5570 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5572 expression_t *tp_expression = allocate_expression_zero(kind);
5573 tp_expression->base.type = type_size_t;
5575 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5577 add_anchor_token(')');
5578 tp_expression->typeprop.type = parse_typename();
5579 rem_anchor_token(')');
5582 expression_t *expression = parse_sub_expression(precedence);
5583 expression->base.type = revert_automatic_type_conversion(expression);
5585 tp_expression->typeprop.type = expression->base.type;
5586 tp_expression->typeprop.tp_expression = expression;
5589 return tp_expression;
5591 return create_invalid_expression();
5594 static expression_t *parse_sizeof(unsigned precedence)
5597 return parse_typeprop(EXPR_SIZEOF, precedence);
5600 static expression_t *parse_alignof(unsigned precedence)
5603 return parse_typeprop(EXPR_SIZEOF, precedence);
5606 static expression_t *parse_select_expression(unsigned precedence,
5607 expression_t *compound)
5610 assert(token.type == '.' || token.type == T_MINUSGREATER);
5612 bool is_pointer = (token.type == T_MINUSGREATER);
5615 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5616 select->select.compound = compound;
5618 if(token.type != T_IDENTIFIER) {
5619 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5622 symbol_t *symbol = token.v.symbol;
5623 select->select.symbol = symbol;
5626 type_t *const orig_type = compound->base.type;
5627 type_t *const type = skip_typeref(orig_type);
5629 type_t *type_left = type;
5631 if (!is_type_pointer(type)) {
5632 if (is_type_valid(type)) {
5633 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5635 return create_invalid_expression();
5637 type_left = type->pointer.points_to;
5639 type_left = skip_typeref(type_left);
5641 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5642 type_left->kind != TYPE_COMPOUND_UNION) {
5643 if (is_type_valid(type_left)) {
5644 errorf(HERE, "request for member '%Y' in something not a struct or "
5645 "union, but '%T'", symbol, type_left);
5647 return create_invalid_expression();
5650 declaration_t *const declaration = type_left->compound.declaration;
5652 if(!declaration->init.is_defined) {
5653 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5655 return create_invalid_expression();
5658 declaration_t *iter = find_compound_entry(declaration, symbol);
5660 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5661 return create_invalid_expression();
5664 /* we always do the auto-type conversions; the & and sizeof parser contains
5665 * code to revert this! */
5666 type_t *expression_type = automatic_type_conversion(iter->type);
5668 select->select.compound_entry = iter;
5669 select->base.type = expression_type;
5671 if(expression_type->kind == TYPE_BITFIELD) {
5672 expression_t *extract
5673 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5674 extract->unary.value = select;
5675 extract->base.type = expression_type->bitfield.base_type;
5684 * Parse a call expression, ie. expression '( ... )'.
5686 * @param expression the function address
5688 static expression_t *parse_call_expression(unsigned precedence,
5689 expression_t *expression)
5692 expression_t *result = allocate_expression_zero(EXPR_CALL);
5693 result->base.source_position = expression->base.source_position;
5695 call_expression_t *call = &result->call;
5696 call->function = expression;
5698 type_t *const orig_type = expression->base.type;
5699 type_t *const type = skip_typeref(orig_type);
5701 function_type_t *function_type = NULL;
5702 if (is_type_pointer(type)) {
5703 type_t *const to_type = skip_typeref(type->pointer.points_to);
5705 if (is_type_function(to_type)) {
5706 function_type = &to_type->function;
5707 call->base.type = function_type->return_type;
5711 if (function_type == NULL && is_type_valid(type)) {
5712 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5715 /* parse arguments */
5717 add_anchor_token(')');
5718 add_anchor_token(',');
5720 if(token.type != ')') {
5721 call_argument_t *last_argument = NULL;
5724 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5726 argument->expression = parse_assignment_expression();
5727 if(last_argument == NULL) {
5728 call->arguments = argument;
5730 last_argument->next = argument;
5732 last_argument = argument;
5734 if(token.type != ',')
5739 rem_anchor_token(',');
5740 rem_anchor_token(')');
5743 if(function_type != NULL) {
5744 function_parameter_t *parameter = function_type->parameters;
5745 call_argument_t *argument = call->arguments;
5746 for( ; parameter != NULL && argument != NULL;
5747 parameter = parameter->next, argument = argument->next) {
5748 type_t *expected_type = parameter->type;
5749 /* TODO report scope in error messages */
5750 expression_t *const arg_expr = argument->expression;
5751 type_t *const res_type = semantic_assign(expected_type, arg_expr,
5753 &arg_expr->base.source_position);
5754 if (res_type == NULL) {
5755 /* TODO improve error message */
5756 errorf(&arg_expr->base.source_position,
5757 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5758 arg_expr, arg_expr->base.type, expected_type);
5760 argument->expression = create_implicit_cast(argument->expression, expected_type);
5763 /* too few parameters */
5764 if(parameter != NULL) {
5765 errorf(HERE, "too few arguments to function '%E'", expression);
5766 } else if(argument != NULL) {
5767 /* too many parameters */
5768 if(!function_type->variadic
5769 && !function_type->unspecified_parameters) {
5770 errorf(HERE, "too many arguments to function '%E'", expression);
5772 /* do default promotion */
5773 for( ; argument != NULL; argument = argument->next) {
5774 type_t *type = argument->expression->base.type;
5776 type = skip_typeref(type);
5777 if(is_type_integer(type)) {
5778 type = promote_integer(type);
5779 } else if(type == type_float) {
5783 argument->expression
5784 = create_implicit_cast(argument->expression, type);
5787 check_format(&result->call);
5790 check_format(&result->call);
5796 return create_invalid_expression();
5799 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5801 static bool same_compound_type(const type_t *type1, const type_t *type2)
5804 is_type_compound(type1) &&
5805 type1->kind == type2->kind &&
5806 type1->compound.declaration == type2->compound.declaration;
5810 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5812 * @param expression the conditional expression
5814 static expression_t *parse_conditional_expression(unsigned precedence,
5815 expression_t *expression)
5818 add_anchor_token(':');
5820 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5822 conditional_expression_t *conditional = &result->conditional;
5823 conditional->condition = expression;
5826 type_t *const condition_type_orig = expression->base.type;
5827 type_t *const condition_type = skip_typeref(condition_type_orig);
5828 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5829 type_error("expected a scalar type in conditional condition",
5830 &expression->base.source_position, condition_type_orig);
5833 expression_t *true_expression = parse_expression();
5834 rem_anchor_token(':');
5836 expression_t *false_expression = parse_sub_expression(precedence);
5838 type_t *const orig_true_type = true_expression->base.type;
5839 type_t *const orig_false_type = false_expression->base.type;
5840 type_t *const true_type = skip_typeref(orig_true_type);
5841 type_t *const false_type = skip_typeref(orig_false_type);
5844 type_t *result_type;
5845 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5846 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5847 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5848 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5849 warningf(&expression->base.source_position,
5850 "ISO C forbids conditional expression with only one void side");
5852 result_type = type_void;
5853 } else if (is_type_arithmetic(true_type)
5854 && is_type_arithmetic(false_type)) {
5855 result_type = semantic_arithmetic(true_type, false_type);
5857 true_expression = create_implicit_cast(true_expression, result_type);
5858 false_expression = create_implicit_cast(false_expression, result_type);
5860 conditional->true_expression = true_expression;
5861 conditional->false_expression = false_expression;
5862 conditional->base.type = result_type;
5863 } else if (same_compound_type(true_type, false_type)) {
5864 /* just take 1 of the 2 types */
5865 result_type = true_type;
5866 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5867 type_t *pointer_type;
5869 expression_t *other_expression;
5870 if (is_type_pointer(true_type)) {
5871 pointer_type = true_type;
5872 other_type = false_type;
5873 other_expression = false_expression;
5875 pointer_type = false_type;
5876 other_type = true_type;
5877 other_expression = true_expression;
5880 if(is_type_pointer(other_type)) {
5881 if(!pointers_compatible(true_type, false_type)) {
5882 warningf(&expression->base.source_position,
5883 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5885 result_type = true_type;
5886 } else if(is_null_pointer_constant(other_expression)) {
5887 result_type = pointer_type;
5888 } else if(is_type_integer(other_type)) {
5889 warningf(&expression->base.source_position,
5890 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5891 result_type = pointer_type;
5893 type_error_incompatible("while parsing conditional",
5894 &expression->base.source_position, true_type, false_type);
5895 result_type = type_error_type;
5898 /* TODO: one pointer to void*, other some pointer */
5900 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5901 type_error_incompatible("while parsing conditional",
5902 &expression->base.source_position, true_type,
5905 result_type = type_error_type;
5908 conditional->true_expression
5909 = create_implicit_cast(true_expression, result_type);
5910 conditional->false_expression
5911 = create_implicit_cast(false_expression, result_type);
5912 conditional->base.type = result_type;
5915 return create_invalid_expression();
5919 * Parse an extension expression.
5921 static expression_t *parse_extension(unsigned precedence)
5923 eat(T___extension__);
5925 /* TODO enable extensions */
5926 expression_t *expression = parse_sub_expression(precedence);
5927 /* TODO disable extensions */
5932 * Parse a __builtin_classify_type() expression.
5934 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5936 eat(T___builtin_classify_type);
5938 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5939 result->base.type = type_int;
5942 add_anchor_token(')');
5943 expression_t *expression = parse_sub_expression(precedence);
5944 rem_anchor_token(')');
5946 result->classify_type.type_expression = expression;
5950 return create_invalid_expression();
5953 static void semantic_incdec(unary_expression_t *expression)
5955 type_t *const orig_type = expression->value->base.type;
5956 type_t *const type = skip_typeref(orig_type);
5957 /* TODO !is_type_real && !is_type_pointer */
5958 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5959 if (is_type_valid(type)) {
5960 /* TODO: improve error message */
5961 errorf(HERE, "operation needs an arithmetic or pointer type");
5966 expression->base.type = orig_type;
5969 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5971 type_t *const orig_type = expression->value->base.type;
5972 type_t *const type = skip_typeref(orig_type);
5973 if(!is_type_arithmetic(type)) {
5974 if (is_type_valid(type)) {
5975 /* TODO: improve error message */
5976 errorf(HERE, "operation needs an arithmetic type");
5981 expression->base.type = orig_type;
5984 static void semantic_unexpr_scalar(unary_expression_t *expression)
5986 type_t *const orig_type = expression->value->base.type;
5987 type_t *const type = skip_typeref(orig_type);
5988 if (!is_type_scalar(type)) {
5989 if (is_type_valid(type)) {
5990 errorf(HERE, "operand of ! must be of scalar type");
5995 expression->base.type = orig_type;
5998 static void semantic_unexpr_integer(unary_expression_t *expression)
6000 type_t *const orig_type = expression->value->base.type;
6001 type_t *const type = skip_typeref(orig_type);
6002 if (!is_type_integer(type)) {
6003 if (is_type_valid(type)) {
6004 errorf(HERE, "operand of ~ must be of integer type");
6009 expression->base.type = orig_type;
6012 static void semantic_dereference(unary_expression_t *expression)
6014 type_t *const orig_type = expression->value->base.type;
6015 type_t *const type = skip_typeref(orig_type);
6016 if(!is_type_pointer(type)) {
6017 if (is_type_valid(type)) {
6018 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6023 type_t *result_type = type->pointer.points_to;
6024 result_type = automatic_type_conversion(result_type);
6025 expression->base.type = result_type;
6029 * Check the semantic of the address taken expression.
6031 static void semantic_take_addr(unary_expression_t *expression)
6033 expression_t *value = expression->value;
6034 value->base.type = revert_automatic_type_conversion(value);
6036 type_t *orig_type = value->base.type;
6037 if(!is_type_valid(orig_type))
6040 if(value->kind == EXPR_REFERENCE) {
6041 declaration_t *const declaration = value->reference.declaration;
6042 if(declaration != NULL) {
6043 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6044 errorf(&expression->base.source_position,
6045 "address of register variable '%Y' requested",
6046 declaration->symbol);
6048 declaration->address_taken = 1;
6052 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6055 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6056 static expression_t *parse_##unexpression_type(unsigned precedence) \
6060 expression_t *unary_expression \
6061 = allocate_expression_zero(unexpression_type); \
6062 unary_expression->base.source_position = *HERE; \
6063 unary_expression->unary.value = parse_sub_expression(precedence); \
6065 sfunc(&unary_expression->unary); \
6067 return unary_expression; \
6070 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6071 semantic_unexpr_arithmetic)
6072 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6073 semantic_unexpr_arithmetic)
6074 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6075 semantic_unexpr_scalar)
6076 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6077 semantic_dereference)
6078 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6080 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6081 semantic_unexpr_integer)
6082 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6084 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6087 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6089 static expression_t *parse_##unexpression_type(unsigned precedence, \
6090 expression_t *left) \
6092 (void) precedence; \
6095 expression_t *unary_expression \
6096 = allocate_expression_zero(unexpression_type); \
6097 unary_expression->unary.value = left; \
6099 sfunc(&unary_expression->unary); \
6101 return unary_expression; \
6104 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6105 EXPR_UNARY_POSTFIX_INCREMENT,
6107 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6108 EXPR_UNARY_POSTFIX_DECREMENT,
6111 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6113 /* TODO: handle complex + imaginary types */
6115 /* § 6.3.1.8 Usual arithmetic conversions */
6116 if(type_left == type_long_double || type_right == type_long_double) {
6117 return type_long_double;
6118 } else if(type_left == type_double || type_right == type_double) {
6120 } else if(type_left == type_float || type_right == type_float) {
6124 type_right = promote_integer(type_right);
6125 type_left = promote_integer(type_left);
6127 if(type_left == type_right)
6130 bool signed_left = is_type_signed(type_left);
6131 bool signed_right = is_type_signed(type_right);
6132 int rank_left = get_rank(type_left);
6133 int rank_right = get_rank(type_right);
6134 if(rank_left < rank_right) {
6135 if(signed_left == signed_right || !signed_right) {
6141 if(signed_left == signed_right || !signed_left) {
6150 * Check the semantic restrictions for a binary expression.
6152 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6154 expression_t *const left = expression->left;
6155 expression_t *const right = expression->right;
6156 type_t *const orig_type_left = left->base.type;
6157 type_t *const orig_type_right = right->base.type;
6158 type_t *const type_left = skip_typeref(orig_type_left);
6159 type_t *const type_right = skip_typeref(orig_type_right);
6161 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6162 /* TODO: improve error message */
6163 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6164 errorf(HERE, "operation needs arithmetic types");
6169 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6170 expression->left = create_implicit_cast(left, arithmetic_type);
6171 expression->right = create_implicit_cast(right, arithmetic_type);
6172 expression->base.type = arithmetic_type;
6175 static void semantic_shift_op(binary_expression_t *expression)
6177 expression_t *const left = expression->left;
6178 expression_t *const right = expression->right;
6179 type_t *const orig_type_left = left->base.type;
6180 type_t *const orig_type_right = right->base.type;
6181 type_t * type_left = skip_typeref(orig_type_left);
6182 type_t * type_right = skip_typeref(orig_type_right);
6184 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6185 /* TODO: improve error message */
6186 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6187 errorf(HERE, "operation needs integer types");
6192 type_left = promote_integer(type_left);
6193 type_right = promote_integer(type_right);
6195 expression->left = create_implicit_cast(left, type_left);
6196 expression->right = create_implicit_cast(right, type_right);
6197 expression->base.type = type_left;
6200 static void semantic_add(binary_expression_t *expression)
6202 expression_t *const left = expression->left;
6203 expression_t *const right = expression->right;
6204 type_t *const orig_type_left = left->base.type;
6205 type_t *const orig_type_right = right->base.type;
6206 type_t *const type_left = skip_typeref(orig_type_left);
6207 type_t *const type_right = skip_typeref(orig_type_right);
6210 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6211 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6212 expression->left = create_implicit_cast(left, arithmetic_type);
6213 expression->right = create_implicit_cast(right, arithmetic_type);
6214 expression->base.type = arithmetic_type;
6216 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6217 expression->base.type = type_left;
6218 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
6219 expression->base.type = type_right;
6220 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6221 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
6225 static void semantic_sub(binary_expression_t *expression)
6227 expression_t *const left = expression->left;
6228 expression_t *const right = expression->right;
6229 type_t *const orig_type_left = left->base.type;
6230 type_t *const orig_type_right = right->base.type;
6231 type_t *const type_left = skip_typeref(orig_type_left);
6232 type_t *const type_right = skip_typeref(orig_type_right);
6235 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6236 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6237 expression->left = create_implicit_cast(left, arithmetic_type);
6238 expression->right = create_implicit_cast(right, arithmetic_type);
6239 expression->base.type = arithmetic_type;
6241 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6242 expression->base.type = type_left;
6243 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6244 if(!pointers_compatible(type_left, type_right)) {
6246 "pointers to incompatible objects to binary '-' ('%T', '%T')",
6247 orig_type_left, orig_type_right);
6249 expression->base.type = type_ptrdiff_t;
6251 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6252 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6253 orig_type_left, orig_type_right);
6258 * Check the semantics of comparison expressions.
6260 * @param expression The expression to check.
6262 static void semantic_comparison(binary_expression_t *expression)
6264 expression_t *left = expression->left;
6265 expression_t *right = expression->right;
6266 type_t *orig_type_left = left->base.type;
6267 type_t *orig_type_right = right->base.type;
6269 type_t *type_left = skip_typeref(orig_type_left);
6270 type_t *type_right = skip_typeref(orig_type_right);
6272 /* TODO non-arithmetic types */
6273 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6274 /* test for signed vs unsigned compares */
6275 if (warning.sign_compare &&
6276 (expression->base.kind != EXPR_BINARY_EQUAL &&
6277 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6278 (is_type_signed(type_left) != is_type_signed(type_right))) {
6280 /* check if 1 of the operands is a constant, in this case we just
6281 * check wether we can safely represent the resulting constant in
6282 * the type of the other operand. */
6283 expression_t *const_expr = NULL;
6284 expression_t *other_expr = NULL;
6286 if(is_constant_expression(left)) {
6289 } else if(is_constant_expression(right)) {
6294 type_t *other_type = skip_typeref(other_expr->base.type);
6295 if(const_expr != NULL) {
6296 long val = fold_constant(const_expr);
6297 /* TODO: check if val can be represented by other_type */
6301 warningf(&expression->base.source_position,
6302 "comparison between signed and unsigned");
6304 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6305 expression->left = create_implicit_cast(left, arithmetic_type);
6306 expression->right = create_implicit_cast(right, arithmetic_type);
6307 expression->base.type = arithmetic_type;
6308 if (warning.float_equal &&
6309 (expression->base.kind == EXPR_BINARY_EQUAL ||
6310 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6311 is_type_float(arithmetic_type)) {
6312 warningf(&expression->base.source_position,
6313 "comparing floating point with == or != is unsafe");
6315 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6316 /* TODO check compatibility */
6317 } else if (is_type_pointer(type_left)) {
6318 expression->right = create_implicit_cast(right, type_left);
6319 } else if (is_type_pointer(type_right)) {
6320 expression->left = create_implicit_cast(left, type_right);
6321 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6322 type_error_incompatible("invalid operands in comparison",
6323 &expression->base.source_position,
6324 type_left, type_right);
6326 expression->base.type = type_int;
6329 static void semantic_arithmetic_assign(binary_expression_t *expression)
6331 expression_t *left = expression->left;
6332 expression_t *right = expression->right;
6333 type_t *orig_type_left = left->base.type;
6334 type_t *orig_type_right = right->base.type;
6336 type_t *type_left = skip_typeref(orig_type_left);
6337 type_t *type_right = skip_typeref(orig_type_right);
6339 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6340 /* TODO: improve error message */
6341 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6342 errorf(HERE, "operation needs arithmetic types");
6347 /* combined instructions are tricky. We can't create an implicit cast on
6348 * the left side, because we need the uncasted form for the store.
6349 * The ast2firm pass has to know that left_type must be right_type
6350 * for the arithmetic operation and create a cast by itself */
6351 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6352 expression->right = create_implicit_cast(right, arithmetic_type);
6353 expression->base.type = type_left;
6356 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6358 expression_t *const left = expression->left;
6359 expression_t *const right = expression->right;
6360 type_t *const orig_type_left = left->base.type;
6361 type_t *const orig_type_right = right->base.type;
6362 type_t *const type_left = skip_typeref(orig_type_left);
6363 type_t *const type_right = skip_typeref(orig_type_right);
6365 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6366 /* combined instructions are tricky. We can't create an implicit cast on
6367 * the left side, because we need the uncasted form for the store.
6368 * The ast2firm pass has to know that left_type must be right_type
6369 * for the arithmetic operation and create a cast by itself */
6370 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6371 expression->right = create_implicit_cast(right, arithmetic_type);
6372 expression->base.type = type_left;
6373 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6374 expression->base.type = type_left;
6375 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6376 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6381 * Check the semantic restrictions of a logical expression.
6383 static void semantic_logical_op(binary_expression_t *expression)
6385 expression_t *const left = expression->left;
6386 expression_t *const right = expression->right;
6387 type_t *const orig_type_left = left->base.type;
6388 type_t *const orig_type_right = right->base.type;
6389 type_t *const type_left = skip_typeref(orig_type_left);
6390 type_t *const type_right = skip_typeref(orig_type_right);
6392 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6393 /* TODO: improve error message */
6394 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6395 errorf(HERE, "operation needs scalar types");
6400 expression->base.type = type_int;
6404 * Checks if a compound type has constant fields.
6406 static bool has_const_fields(const compound_type_t *type)
6408 const scope_t *scope = &type->declaration->scope;
6409 const declaration_t *declaration = scope->declarations;
6411 for (; declaration != NULL; declaration = declaration->next) {
6412 if (declaration->namespc != NAMESPACE_NORMAL)
6415 const type_t *decl_type = skip_typeref(declaration->type);
6416 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6424 * Check the semantic restrictions of a binary assign expression.
6426 static void semantic_binexpr_assign(binary_expression_t *expression)
6428 expression_t *left = expression->left;
6429 type_t *orig_type_left = left->base.type;
6431 type_t *type_left = revert_automatic_type_conversion(left);
6432 type_left = skip_typeref(orig_type_left);
6434 /* must be a modifiable lvalue */
6435 if (is_type_array(type_left)) {
6436 errorf(HERE, "cannot assign to arrays ('%E')", left);
6439 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6440 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6444 if(is_type_incomplete(type_left)) {
6446 "left-hand side of assignment '%E' has incomplete type '%T'",
6447 left, orig_type_left);
6450 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6451 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6452 left, orig_type_left);
6456 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6457 "assignment", &left->base.source_position);
6458 if (res_type == NULL) {
6459 errorf(&expression->base.source_position,
6460 "cannot assign to '%T' from '%T'",
6461 orig_type_left, expression->right->base.type);
6463 expression->right = create_implicit_cast(expression->right, res_type);
6466 expression->base.type = orig_type_left;
6470 * Determine if the outermost operation (or parts thereof) of the given
6471 * expression has no effect in order to generate a warning about this fact.
6472 * Therefore in some cases this only examines some of the operands of the
6473 * expression (see comments in the function and examples below).
6475 * f() + 23; // warning, because + has no effect
6476 * x || f(); // no warning, because x controls execution of f()
6477 * x ? y : f(); // warning, because y has no effect
6478 * (void)x; // no warning to be able to suppress the warning
6479 * This function can NOT be used for an "expression has definitely no effect"-
6481 static bool expression_has_effect(const expression_t *const expr)
6483 switch (expr->kind) {
6484 case EXPR_UNKNOWN: break;
6485 case EXPR_INVALID: return true; /* do NOT warn */
6486 case EXPR_REFERENCE: return false;
6487 /* suppress the warning for microsoft __noop operations */
6488 case EXPR_CONST: return expr->conste.is_ms_noop;
6489 case EXPR_CHARACTER_CONSTANT: return false;
6490 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6491 case EXPR_STRING_LITERAL: return false;
6492 case EXPR_WIDE_STRING_LITERAL: return false;
6495 const call_expression_t *const call = &expr->call;
6496 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6499 switch (call->function->builtin_symbol.symbol->ID) {
6500 case T___builtin_va_end: return true;
6501 default: return false;
6505 /* Generate the warning if either the left or right hand side of a
6506 * conditional expression has no effect */
6507 case EXPR_CONDITIONAL: {
6508 const conditional_expression_t *const cond = &expr->conditional;
6510 expression_has_effect(cond->true_expression) &&
6511 expression_has_effect(cond->false_expression);
6514 case EXPR_SELECT: return false;
6515 case EXPR_ARRAY_ACCESS: return false;
6516 case EXPR_SIZEOF: return false;
6517 case EXPR_CLASSIFY_TYPE: return false;
6518 case EXPR_ALIGNOF: return false;
6520 case EXPR_FUNCNAME: return false;
6521 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6522 case EXPR_BUILTIN_CONSTANT_P: return false;
6523 case EXPR_BUILTIN_PREFETCH: return true;
6524 case EXPR_OFFSETOF: return false;
6525 case EXPR_VA_START: return true;
6526 case EXPR_VA_ARG: return true;
6527 case EXPR_STATEMENT: return true; // TODO
6528 case EXPR_COMPOUND_LITERAL: return false;
6530 case EXPR_UNARY_NEGATE: return false;
6531 case EXPR_UNARY_PLUS: return false;
6532 case EXPR_UNARY_BITWISE_NEGATE: return false;
6533 case EXPR_UNARY_NOT: return false;
6534 case EXPR_UNARY_DEREFERENCE: return false;
6535 case EXPR_UNARY_TAKE_ADDRESS: return false;
6536 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6537 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6538 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6539 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6541 /* Treat void casts as if they have an effect in order to being able to
6542 * suppress the warning */
6543 case EXPR_UNARY_CAST: {
6544 type_t *const type = skip_typeref(expr->base.type);
6545 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6548 case EXPR_UNARY_CAST_IMPLICIT: return true;
6549 case EXPR_UNARY_ASSUME: return true;
6550 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6552 case EXPR_BINARY_ADD: return false;
6553 case EXPR_BINARY_SUB: return false;
6554 case EXPR_BINARY_MUL: return false;
6555 case EXPR_BINARY_DIV: return false;
6556 case EXPR_BINARY_MOD: return false;
6557 case EXPR_BINARY_EQUAL: return false;
6558 case EXPR_BINARY_NOTEQUAL: return false;
6559 case EXPR_BINARY_LESS: return false;
6560 case EXPR_BINARY_LESSEQUAL: return false;
6561 case EXPR_BINARY_GREATER: return false;
6562 case EXPR_BINARY_GREATEREQUAL: return false;
6563 case EXPR_BINARY_BITWISE_AND: return false;
6564 case EXPR_BINARY_BITWISE_OR: return false;
6565 case EXPR_BINARY_BITWISE_XOR: return false;
6566 case EXPR_BINARY_SHIFTLEFT: return false;
6567 case EXPR_BINARY_SHIFTRIGHT: return false;
6568 case EXPR_BINARY_ASSIGN: return true;
6569 case EXPR_BINARY_MUL_ASSIGN: return true;
6570 case EXPR_BINARY_DIV_ASSIGN: return true;
6571 case EXPR_BINARY_MOD_ASSIGN: return true;
6572 case EXPR_BINARY_ADD_ASSIGN: return true;
6573 case EXPR_BINARY_SUB_ASSIGN: return true;
6574 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6575 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6576 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6577 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6578 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6580 /* Only examine the right hand side of && and ||, because the left hand
6581 * side already has the effect of controlling the execution of the right
6583 case EXPR_BINARY_LOGICAL_AND:
6584 case EXPR_BINARY_LOGICAL_OR:
6585 /* Only examine the right hand side of a comma expression, because the left
6586 * hand side has a separate warning */
6587 case EXPR_BINARY_COMMA:
6588 return expression_has_effect(expr->binary.right);
6590 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6591 case EXPR_BINARY_ISGREATER: return false;
6592 case EXPR_BINARY_ISGREATEREQUAL: return false;
6593 case EXPR_BINARY_ISLESS: return false;
6594 case EXPR_BINARY_ISLESSEQUAL: return false;
6595 case EXPR_BINARY_ISLESSGREATER: return false;
6596 case EXPR_BINARY_ISUNORDERED: return false;
6599 internal_errorf(HERE, "unexpected expression");
6602 static void semantic_comma(binary_expression_t *expression)
6604 if (warning.unused_value) {
6605 const expression_t *const left = expression->left;
6606 if (!expression_has_effect(left)) {
6607 warningf(&left->base.source_position,
6608 "left-hand operand of comma expression has no effect");
6611 expression->base.type = expression->right->base.type;
6614 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6615 static expression_t *parse_##binexpression_type(unsigned precedence, \
6616 expression_t *left) \
6619 source_position_t pos = *HERE; \
6621 expression_t *right = parse_sub_expression(precedence + lr); \
6623 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6624 binexpr->base.source_position = pos; \
6625 binexpr->binary.left = left; \
6626 binexpr->binary.right = right; \
6627 sfunc(&binexpr->binary); \
6632 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6633 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6634 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6635 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6636 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6637 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6638 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6639 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6640 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6642 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6643 semantic_comparison, 1)
6644 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6645 semantic_comparison, 1)
6646 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6647 semantic_comparison, 1)
6648 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6649 semantic_comparison, 1)
6651 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6652 semantic_binexpr_arithmetic, 1)
6653 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6654 semantic_binexpr_arithmetic, 1)
6655 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6656 semantic_binexpr_arithmetic, 1)
6657 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6658 semantic_logical_op, 1)
6659 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6660 semantic_logical_op, 1)
6661 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6662 semantic_shift_op, 1)
6663 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6664 semantic_shift_op, 1)
6665 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6666 semantic_arithmetic_addsubb_assign, 0)
6667 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6668 semantic_arithmetic_addsubb_assign, 0)
6669 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6670 semantic_arithmetic_assign, 0)
6671 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6672 semantic_arithmetic_assign, 0)
6673 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6674 semantic_arithmetic_assign, 0)
6675 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6676 semantic_arithmetic_assign, 0)
6677 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6678 semantic_arithmetic_assign, 0)
6679 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6680 semantic_arithmetic_assign, 0)
6681 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6682 semantic_arithmetic_assign, 0)
6683 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6684 semantic_arithmetic_assign, 0)
6686 static expression_t *parse_sub_expression(unsigned precedence)
6688 if(token.type < 0) {
6689 return expected_expression_error();
6692 expression_parser_function_t *parser
6693 = &expression_parsers[token.type];
6694 source_position_t source_position = token.source_position;
6697 if(parser->parser != NULL) {
6698 left = parser->parser(parser->precedence);
6700 left = parse_primary_expression();
6702 assert(left != NULL);
6703 left->base.source_position = source_position;
6706 if(token.type < 0) {
6707 return expected_expression_error();
6710 parser = &expression_parsers[token.type];
6711 if(parser->infix_parser == NULL)
6713 if(parser->infix_precedence < precedence)
6716 left = parser->infix_parser(parser->infix_precedence, left);
6718 assert(left != NULL);
6719 assert(left->kind != EXPR_UNKNOWN);
6720 left->base.source_position = source_position;
6727 * Parse an expression.
6729 static expression_t *parse_expression(void)
6731 return parse_sub_expression(1);
6735 * Register a parser for a prefix-like operator with given precedence.
6737 * @param parser the parser function
6738 * @param token_type the token type of the prefix token
6739 * @param precedence the precedence of the operator
6741 static void register_expression_parser(parse_expression_function parser,
6742 int token_type, unsigned precedence)
6744 expression_parser_function_t *entry = &expression_parsers[token_type];
6746 if(entry->parser != NULL) {
6747 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6748 panic("trying to register multiple expression parsers for a token");
6750 entry->parser = parser;
6751 entry->precedence = precedence;
6755 * Register a parser for an infix operator with given precedence.
6757 * @param parser the parser function
6758 * @param token_type the token type of the infix operator
6759 * @param precedence the precedence of the operator
6761 static void register_infix_parser(parse_expression_infix_function parser,
6762 int token_type, unsigned precedence)
6764 expression_parser_function_t *entry = &expression_parsers[token_type];
6766 if(entry->infix_parser != NULL) {
6767 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6768 panic("trying to register multiple infix expression parsers for a "
6771 entry->infix_parser = parser;
6772 entry->infix_precedence = precedence;
6776 * Initialize the expression parsers.
6778 static void init_expression_parsers(void)
6780 memset(&expression_parsers, 0, sizeof(expression_parsers));
6782 register_infix_parser(parse_array_expression, '[', 30);
6783 register_infix_parser(parse_call_expression, '(', 30);
6784 register_infix_parser(parse_select_expression, '.', 30);
6785 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6786 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6788 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6791 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6792 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6793 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6794 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6795 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6796 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6797 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6798 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6799 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6800 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6801 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6802 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6803 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6804 T_EXCLAMATIONMARKEQUAL, 13);
6805 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6806 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6807 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6808 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6809 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6810 register_infix_parser(parse_conditional_expression, '?', 7);
6811 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6812 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6813 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6814 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6815 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6816 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6817 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6818 T_LESSLESSEQUAL, 2);
6819 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6820 T_GREATERGREATEREQUAL, 2);
6821 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6823 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6825 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6828 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6830 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6831 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6832 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6833 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6834 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6835 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6836 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6838 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6840 register_expression_parser(parse_sizeof, T_sizeof, 25);
6841 register_expression_parser(parse_alignof, T___alignof__, 25);
6842 register_expression_parser(parse_extension, T___extension__, 25);
6843 register_expression_parser(parse_builtin_classify_type,
6844 T___builtin_classify_type, 25);
6848 * Parse a asm statement constraints specification.
6850 static asm_constraint_t *parse_asm_constraints(void)
6852 asm_constraint_t *result = NULL;
6853 asm_constraint_t *last = NULL;
6855 while(token.type == T_STRING_LITERAL || token.type == '[') {
6856 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6857 memset(constraint, 0, sizeof(constraint[0]));
6859 if(token.type == '[') {
6861 if(token.type != T_IDENTIFIER) {
6862 parse_error_expected("while parsing asm constraint",
6863 T_IDENTIFIER, NULL);
6866 constraint->symbol = token.v.symbol;
6871 constraint->constraints = parse_string_literals();
6873 constraint->expression = parse_expression();
6877 last->next = constraint;
6879 result = constraint;
6883 if(token.type != ',')
6894 * Parse a asm statement clobber specification.
6896 static asm_clobber_t *parse_asm_clobbers(void)
6898 asm_clobber_t *result = NULL;
6899 asm_clobber_t *last = NULL;
6901 while(token.type == T_STRING_LITERAL) {
6902 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6903 clobber->clobber = parse_string_literals();
6906 last->next = clobber;
6912 if(token.type != ',')
6921 * Parse an asm statement.
6923 static statement_t *parse_asm_statement(void)
6927 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6928 statement->base.source_position = token.source_position;
6930 asm_statement_t *asm_statement = &statement->asms;
6932 if(token.type == T_volatile) {
6934 asm_statement->is_volatile = true;
6938 add_anchor_token(')');
6939 add_anchor_token(':');
6940 asm_statement->asm_text = parse_string_literals();
6942 if(token.type != ':') {
6943 rem_anchor_token(':');
6948 asm_statement->inputs = parse_asm_constraints();
6949 if(token.type != ':') {
6950 rem_anchor_token(':');
6955 asm_statement->outputs = parse_asm_constraints();
6956 if(token.type != ':') {
6957 rem_anchor_token(':');
6960 rem_anchor_token(':');
6963 asm_statement->clobbers = parse_asm_clobbers();
6966 rem_anchor_token(')');
6971 return create_invalid_statement();
6975 * Parse a case statement.
6977 static statement_t *parse_case_statement(void)
6981 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6983 statement->base.source_position = token.source_position;
6984 statement->case_label.expression = parse_expression();
6986 if (c_mode & _GNUC) {
6987 if (token.type == T_DOTDOTDOT) {
6989 statement->case_label.end_range = parse_expression();
6995 if (! is_constant_expression(statement->case_label.expression)) {
6996 errorf(&statement->base.source_position,
6997 "case label does not reduce to an integer constant");
6999 /* TODO: check if the case label is already known */
7000 if (current_switch != NULL) {
7001 /* link all cases into the switch statement */
7002 if (current_switch->last_case == NULL) {
7003 current_switch->first_case =
7004 current_switch->last_case = &statement->case_label;
7006 current_switch->last_case->next = &statement->case_label;
7009 errorf(&statement->base.source_position,
7010 "case label not within a switch statement");
7013 statement->case_label.statement = parse_statement();
7017 return create_invalid_statement();
7021 * Finds an existing default label of a switch statement.
7023 static case_label_statement_t *
7024 find_default_label(const switch_statement_t *statement)
7026 case_label_statement_t *label = statement->first_case;
7027 for ( ; label != NULL; label = label->next) {
7028 if (label->expression == NULL)
7035 * Parse a default statement.
7037 static statement_t *parse_default_statement(void)
7041 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7043 statement->base.source_position = token.source_position;
7046 if (current_switch != NULL) {
7047 const case_label_statement_t *def_label = find_default_label(current_switch);
7048 if (def_label != NULL) {
7049 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7050 &def_label->base.source_position);
7052 /* link all cases into the switch statement */
7053 if (current_switch->last_case == NULL) {
7054 current_switch->first_case =
7055 current_switch->last_case = &statement->case_label;
7057 current_switch->last_case->next = &statement->case_label;
7061 errorf(&statement->base.source_position,
7062 "'default' label not within a switch statement");
7064 statement->case_label.statement = parse_statement();
7068 return create_invalid_statement();
7072 * Return the declaration for a given label symbol or create a new one.
7074 static declaration_t *get_label(symbol_t *symbol)
7076 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7077 assert(current_function != NULL);
7078 /* if we found a label in the same function, then we already created the
7080 if(candidate != NULL
7081 && candidate->parent_scope == ¤t_function->scope) {
7085 /* otherwise we need to create a new one */
7086 declaration_t *const declaration = allocate_declaration_zero();
7087 declaration->namespc = NAMESPACE_LABEL;
7088 declaration->symbol = symbol;
7090 label_push(declaration);
7096 * Parse a label statement.
7098 static statement_t *parse_label_statement(void)
7100 assert(token.type == T_IDENTIFIER);
7101 symbol_t *symbol = token.v.symbol;
7104 declaration_t *label = get_label(symbol);
7106 /* if source position is already set then the label is defined twice,
7107 * otherwise it was just mentioned in a goto so far */
7108 if(label->source_position.input_name != NULL) {
7109 errorf(HERE, "duplicate label '%Y' (declared %P)",
7110 symbol, &label->source_position);
7112 label->source_position = token.source_position;
7115 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7117 statement->base.source_position = token.source_position;
7118 statement->label.label = label;
7122 if(token.type == '}') {
7123 /* TODO only warn? */
7125 warningf(HERE, "label at end of compound statement");
7126 statement->label.statement = create_empty_statement();
7128 errorf(HERE, "label at end of compound statement");
7129 statement->label.statement = create_invalid_statement();
7133 if (token.type == ';') {
7134 /* eat an empty statement here, to avoid the warning about an empty
7135 * after a label. label:; is commonly used to have a label before
7137 statement->label.statement = create_empty_statement();
7140 statement->label.statement = parse_statement();
7144 /* remember the labels's in a list for later checking */
7145 if (label_last == NULL) {
7146 label_first = &statement->label;
7148 label_last->next = &statement->label;
7150 label_last = &statement->label;
7156 * Parse an if statement.
7158 static statement_t *parse_if(void)
7162 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7163 statement->base.source_position = token.source_position;
7166 add_anchor_token(')');
7167 statement->ifs.condition = parse_expression();
7168 rem_anchor_token(')');
7171 add_anchor_token(T_else);
7172 statement->ifs.true_statement = parse_statement();
7173 rem_anchor_token(T_else);
7175 if(token.type == T_else) {
7177 statement->ifs.false_statement = parse_statement();
7182 return create_invalid_statement();
7186 * Parse a switch statement.
7188 static statement_t *parse_switch(void)
7192 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7193 statement->base.source_position = token.source_position;
7196 expression_t *const expr = parse_expression();
7197 type_t * type = skip_typeref(expr->base.type);
7198 if (is_type_integer(type)) {
7199 type = promote_integer(type);
7200 } else if (is_type_valid(type)) {
7201 errorf(&expr->base.source_position,
7202 "switch quantity is not an integer, but '%T'", type);
7203 type = type_error_type;
7205 statement->switchs.expression = create_implicit_cast(expr, type);
7208 switch_statement_t *rem = current_switch;
7209 current_switch = &statement->switchs;
7210 statement->switchs.body = parse_statement();
7211 current_switch = rem;
7213 if(warning.switch_default &&
7214 find_default_label(&statement->switchs) == NULL) {
7215 warningf(&statement->base.source_position, "switch has no default case");
7220 return create_invalid_statement();
7223 static statement_t *parse_loop_body(statement_t *const loop)
7225 statement_t *const rem = current_loop;
7226 current_loop = loop;
7228 statement_t *const body = parse_statement();
7235 * Parse a while statement.
7237 static statement_t *parse_while(void)
7241 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7242 statement->base.source_position = token.source_position;
7245 add_anchor_token(')');
7246 statement->whiles.condition = parse_expression();
7247 rem_anchor_token(')');
7250 statement->whiles.body = parse_loop_body(statement);
7254 return create_invalid_statement();
7258 * Parse a do statement.
7260 static statement_t *parse_do(void)
7264 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7266 statement->base.source_position = token.source_position;
7268 add_anchor_token(T_while);
7269 statement->do_while.body = parse_loop_body(statement);
7270 rem_anchor_token(T_while);
7274 add_anchor_token(')');
7275 statement->do_while.condition = parse_expression();
7276 rem_anchor_token(')');
7282 return create_invalid_statement();
7286 * Parse a for statement.
7288 static statement_t *parse_for(void)
7292 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7293 statement->base.source_position = token.source_position;
7295 int top = environment_top();
7296 scope_t *last_scope = scope;
7297 set_scope(&statement->fors.scope);
7300 add_anchor_token(')');
7302 if(token.type != ';') {
7303 if(is_declaration_specifier(&token, false)) {
7304 parse_declaration(record_declaration);
7306 add_anchor_token(';');
7307 expression_t *const init = parse_expression();
7308 statement->fors.initialisation = init;
7309 if (warning.unused_value && !expression_has_effect(init)) {
7310 warningf(&init->base.source_position,
7311 "initialisation of 'for'-statement has no effect");
7313 rem_anchor_token(';');
7320 if(token.type != ';') {
7321 add_anchor_token(';');
7322 statement->fors.condition = parse_expression();
7323 rem_anchor_token(';');
7326 if(token.type != ')') {
7327 expression_t *const step = parse_expression();
7328 statement->fors.step = step;
7329 if (warning.unused_value && !expression_has_effect(step)) {
7330 warningf(&step->base.source_position,
7331 "step of 'for'-statement has no effect");
7334 rem_anchor_token(')');
7336 statement->fors.body = parse_loop_body(statement);
7338 assert(scope == &statement->fors.scope);
7339 set_scope(last_scope);
7340 environment_pop_to(top);
7345 rem_anchor_token(')');
7346 assert(scope == &statement->fors.scope);
7347 set_scope(last_scope);
7348 environment_pop_to(top);
7350 return create_invalid_statement();
7354 * Parse a goto statement.
7356 static statement_t *parse_goto(void)
7360 if(token.type != T_IDENTIFIER) {
7361 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7365 symbol_t *symbol = token.v.symbol;
7368 declaration_t *label = get_label(symbol);
7370 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7371 statement->base.source_position = token.source_position;
7373 statement->gotos.label = label;
7375 /* remember the goto's in a list for later checking */
7376 if (goto_last == NULL) {
7377 goto_first = &statement->gotos;
7379 goto_last->next = &statement->gotos;
7381 goto_last = &statement->gotos;
7387 return create_invalid_statement();
7391 * Parse a continue statement.
7393 static statement_t *parse_continue(void)
7395 statement_t *statement;
7396 if (current_loop == NULL) {
7397 errorf(HERE, "continue statement not within loop");
7398 statement = create_invalid_statement();
7400 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7402 statement->base.source_position = token.source_position;
7410 return create_invalid_statement();
7414 * Parse a break statement.
7416 static statement_t *parse_break(void)
7418 statement_t *statement;
7419 if (current_switch == NULL && current_loop == NULL) {
7420 errorf(HERE, "break statement not within loop or switch");
7421 statement = create_invalid_statement();
7423 statement = allocate_statement_zero(STATEMENT_BREAK);
7425 statement->base.source_position = token.source_position;
7433 return create_invalid_statement();
7437 * Parse a __leave statement.
7439 static statement_t *parse_leave(void)
7441 statement_t *statement;
7442 if (current_try == NULL) {
7443 errorf(HERE, "__leave statement not within __try");
7444 statement = create_invalid_statement();
7446 statement = allocate_statement_zero(STATEMENT_LEAVE);
7448 statement->base.source_position = token.source_position;
7456 return create_invalid_statement();
7460 * Check if a given declaration represents a local variable.
7462 static bool is_local_var_declaration(const declaration_t *declaration) {
7463 switch ((storage_class_tag_t) declaration->storage_class) {
7464 case STORAGE_CLASS_AUTO:
7465 case STORAGE_CLASS_REGISTER: {
7466 const type_t *type = skip_typeref(declaration->type);
7467 if(is_type_function(type)) {
7479 * Check if a given declaration represents a variable.
7481 static bool is_var_declaration(const declaration_t *declaration) {
7482 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7485 const type_t *type = skip_typeref(declaration->type);
7486 return !is_type_function(type);
7490 * Check if a given expression represents a local variable.
7492 static bool is_local_variable(const expression_t *expression)
7494 if (expression->base.kind != EXPR_REFERENCE) {
7497 const declaration_t *declaration = expression->reference.declaration;
7498 return is_local_var_declaration(declaration);
7502 * Check if a given expression represents a local variable and
7503 * return its declaration then, else return NULL.
7505 declaration_t *expr_is_variable(const expression_t *expression)
7507 if (expression->base.kind != EXPR_REFERENCE) {
7510 declaration_t *declaration = expression->reference.declaration;
7511 if (is_var_declaration(declaration))
7517 * Parse a return statement.
7519 static statement_t *parse_return(void)
7521 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7522 statement->base.source_position = token.source_position;
7526 expression_t *return_value = NULL;
7527 if(token.type != ';') {
7528 return_value = parse_expression();
7532 const type_t *const func_type = current_function->type;
7533 assert(is_type_function(func_type));
7534 type_t *const return_type = skip_typeref(func_type->function.return_type);
7536 if(return_value != NULL) {
7537 type_t *return_value_type = skip_typeref(return_value->base.type);
7539 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7540 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7541 warningf(&statement->base.source_position,
7542 "'return' with a value, in function returning void");
7543 return_value = NULL;
7545 type_t *const res_type = semantic_assign(return_type,
7546 return_value, "'return'", &statement->base.source_position);
7547 if (res_type == NULL) {
7548 errorf(&statement->base.source_position,
7549 "cannot return something of type '%T' in function returning '%T'",
7550 return_value->base.type, return_type);
7552 return_value = create_implicit_cast(return_value, res_type);
7555 /* check for returning address of a local var */
7556 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7557 const expression_t *expression = return_value->unary.value;
7558 if (is_local_variable(expression)) {
7559 warningf(&statement->base.source_position,
7560 "function returns address of local variable");
7564 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7565 warningf(&statement->base.source_position,
7566 "'return' without value, in function returning non-void");
7569 statement->returns.value = return_value;
7573 return create_invalid_statement();
7577 * Parse a declaration statement.
7579 static statement_t *parse_declaration_statement(void)
7581 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7583 statement->base.source_position = token.source_position;
7585 declaration_t *before = last_declaration;
7586 parse_declaration(record_declaration);
7588 if(before == NULL) {
7589 statement->declaration.declarations_begin = scope->declarations;
7591 statement->declaration.declarations_begin = before->next;
7593 statement->declaration.declarations_end = last_declaration;
7599 * Parse an expression statement, ie. expr ';'.
7601 static statement_t *parse_expression_statement(void)
7603 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7605 statement->base.source_position = token.source_position;
7606 expression_t *const expr = parse_expression();
7607 statement->expression.expression = expr;
7613 return create_invalid_statement();
7617 * Parse a microsoft __try { } __finally { } or
7618 * __try{ } __except() { }
7620 static statement_t *parse_ms_try_statment(void) {
7621 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
7623 statement->base.source_position = token.source_position;
7626 ms_try_statement_t *rem = current_try;
7627 current_try = &statement->ms_try;
7628 statement->ms_try.try_statement = parse_compound_statement(false);
7631 if(token.type == T___except) {
7634 add_anchor_token(')');
7635 expression_t *const expr = parse_expression();
7636 type_t * type = skip_typeref(expr->base.type);
7637 if (is_type_integer(type)) {
7638 type = promote_integer(type);
7639 } else if (is_type_valid(type)) {
7640 errorf(&expr->base.source_position,
7641 "__expect expression is not an integer, but '%T'", type);
7642 type = type_error_type;
7644 statement->ms_try.except_expression = create_implicit_cast(expr, type);
7645 rem_anchor_token(')');
7647 statement->ms_try.final_statement = parse_compound_statement(false);
7648 } else if(token.type == T__finally) {
7650 statement->ms_try.final_statement = parse_compound_statement(false);
7652 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
7653 return create_invalid_statement();
7657 return create_invalid_statement();
7661 * Parse a statement.
7662 * There's also parse_statement() which additionally checks for
7663 * "statement has no effect" warnings
7665 static statement_t *intern_parse_statement(void)
7667 statement_t *statement = NULL;
7669 /* declaration or statement */
7670 add_anchor_token(';');
7671 switch(token.type) {
7673 statement = parse_asm_statement();
7677 statement = parse_case_statement();
7681 statement = parse_default_statement();
7685 statement = parse_compound_statement(false);
7689 statement = parse_if();
7693 statement = parse_switch();
7697 statement = parse_while();
7701 statement = parse_do();
7705 statement = parse_for();
7709 statement = parse_goto();
7713 statement = parse_continue();
7717 statement = parse_break();
7721 statement = parse_leave();
7725 statement = parse_return();
7729 if(warning.empty_statement) {
7730 warningf(HERE, "statement is empty");
7732 statement = create_empty_statement();
7737 if(look_ahead(1)->type == ':') {
7738 statement = parse_label_statement();
7742 if(is_typedef_symbol(token.v.symbol)) {
7743 statement = parse_declaration_statement();
7747 statement = parse_expression_statement();
7750 case T___extension__:
7751 /* this can be a prefix to a declaration or an expression statement */
7752 /* we simply eat it now and parse the rest with tail recursion */
7755 } while(token.type == T___extension__);
7756 statement = parse_statement();
7760 statement = parse_declaration_statement();
7764 statement = parse_ms_try_statment();
7768 statement = parse_expression_statement();
7771 rem_anchor_token(';');
7773 assert(statement != NULL
7774 && statement->base.source_position.input_name != NULL);
7780 * parse a statement and emits "statement has no effect" warning if needed
7781 * (This is really a wrapper around intern_parse_statement with check for 1
7782 * single warning. It is needed, because for statement expressions we have
7783 * to avoid the warning on the last statement)
7785 static statement_t *parse_statement(void)
7787 statement_t *statement = intern_parse_statement();
7789 if(statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
7790 expression_t *expression = statement->expression.expression;
7791 if(!expression_has_effect(expression)) {
7792 warningf(&expression->base.source_position,
7793 "statement has no effect");
7801 * Parse a compound statement.
7803 static statement_t *parse_compound_statement(bool inside_expression_statement)
7805 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7807 statement->base.source_position = token.source_position;
7810 add_anchor_token('}');
7812 int top = environment_top();
7813 scope_t *last_scope = scope;
7814 set_scope(&statement->compound.scope);
7816 statement_t *last_statement = NULL;
7818 while(token.type != '}' && token.type != T_EOF) {
7819 statement_t *sub_statement = intern_parse_statement();
7820 if(is_invalid_statement(sub_statement)) {
7821 /* an error occurred. if we are at an anchor, return */
7827 if(last_statement != NULL) {
7828 last_statement->base.next = sub_statement;
7830 statement->compound.statements = sub_statement;
7833 while(sub_statement->base.next != NULL)
7834 sub_statement = sub_statement->base.next;
7836 last_statement = sub_statement;
7839 if(token.type == '}') {
7842 errorf(&statement->base.source_position,
7843 "end of file while looking for closing '}'");
7846 /* look over all statements again to produce no effect warnings */
7847 if(warning.unused_value) {
7848 statement_t *sub_statement = statement->compound.statements;
7849 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
7850 if(sub_statement->kind != STATEMENT_EXPRESSION)
7852 /* don't emit a warning for the last expression in an expression
7853 * statement as it has always an effect */
7854 if(inside_expression_statement && sub_statement->base.next == NULL)
7857 expression_t *expression = sub_statement->expression.expression;
7858 if(!expression_has_effect(expression)) {
7859 warningf(&expression->base.source_position,
7860 "statement has no effect");
7866 rem_anchor_token('}');
7867 assert(scope == &statement->compound.scope);
7868 set_scope(last_scope);
7869 environment_pop_to(top);
7875 * Initialize builtin types.
7877 static void initialize_builtin_types(void)
7879 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7880 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7881 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7882 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7883 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7884 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7885 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7886 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7888 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7889 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7890 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7891 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7895 * Check for unused global static functions and variables
7897 static void check_unused_globals(void)
7899 if (!warning.unused_function && !warning.unused_variable)
7902 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7903 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7906 type_t *const type = decl->type;
7908 if (is_type_function(skip_typeref(type))) {
7909 if (!warning.unused_function || decl->is_inline)
7912 s = (decl->init.statement != NULL ? "defined" : "declared");
7914 if (!warning.unused_variable)
7920 warningf(&decl->source_position, "'%#T' %s but not used",
7921 type, decl->symbol, s);
7926 * Parse a translation unit.
7928 static translation_unit_t *parse_translation_unit(void)
7930 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7932 assert(global_scope == NULL);
7933 global_scope = &unit->scope;
7935 assert(scope == NULL);
7936 set_scope(&unit->scope);
7938 initialize_builtin_types();
7940 while(token.type != T_EOF) {
7941 if (token.type == ';') {
7942 /* TODO error in strict mode */
7943 warningf(HERE, "stray ';' outside of function");
7946 parse_external_declaration();
7950 assert(scope == &unit->scope);
7952 last_declaration = NULL;
7954 assert(global_scope == &unit->scope);
7955 check_unused_globals();
7956 global_scope = NULL;
7964 * @return the translation unit or NULL if errors occurred.
7966 translation_unit_t *parse(void)
7968 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7969 label_stack = NEW_ARR_F(stack_entry_t, 0);
7970 diagnostic_count = 0;
7974 type_set_output(stderr);
7975 ast_set_output(stderr);
7977 lookahead_bufpos = 0;
7978 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7981 translation_unit_t *unit = parse_translation_unit();
7983 DEL_ARR_F(environment_stack);
7984 DEL_ARR_F(label_stack);
7990 * Initialize the parser.
7992 void init_parser(void)
7995 /* add predefined symbols for extended-decl-modifier */
7996 sym_align = symbol_table_insert("align");
7997 sym_allocate = symbol_table_insert("allocate");
7998 sym_dllimport = symbol_table_insert("dllimport");
7999 sym_dllexport = symbol_table_insert("dllexport");
8000 sym_naked = symbol_table_insert("naked");
8001 sym_noinline = symbol_table_insert("noinline");
8002 sym_noreturn = symbol_table_insert("noreturn");
8003 sym_nothrow = symbol_table_insert("nothrow");
8004 sym_novtable = symbol_table_insert("novtable");
8005 sym_property = symbol_table_insert("property");
8006 sym_get = symbol_table_insert("get");
8007 sym_put = symbol_table_insert("put");
8008 sym_selectany = symbol_table_insert("selectany");
8009 sym_thread = symbol_table_insert("thread");
8010 sym_uuid = symbol_table_insert("uuid");
8011 sym_deprecated = symbol_table_insert("deprecated");
8012 sym_restrict = symbol_table_insert("restrict");
8013 sym_noalias = symbol_table_insert("noalias");
8015 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8017 init_expression_parsers();
8018 obstack_init(&temp_obst);
8020 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8021 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8025 * Terminate the parser.
8027 void exit_parser(void)
8029 obstack_free(&temp_obst, NULL);