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;
60 atomic_type_kind_t akind;
64 typedef struct declaration_specifiers_t declaration_specifiers_t;
65 struct declaration_specifiers_t {
66 source_position_t source_position;
67 unsigned char declared_storage_class;
68 unsigned char alignment; /**< Alignment, 0 if not set. */
69 unsigned int is_inline : 1;
70 unsigned int deprecated : 1;
71 decl_modifiers_t modifiers; /**< declaration modifiers */
72 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
73 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
74 symbol_t *get_property_sym; /**< the name of the get property if set. */
75 symbol_t *put_property_sym; /**< the name of the put property if set. */
80 * An environment for parsing initializers (and compound literals).
82 typedef struct parse_initializer_env_t {
83 type_t *type; /**< the type of the initializer. In case of an
84 array type with unspecified size this gets
85 adjusted to the actual size. */
86 declaration_t *declaration; /**< the declaration that is initialized if any */
87 bool must_be_constant;
88 } parse_initializer_env_t;
90 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
93 static token_t lookahead_buffer[MAX_LOOKAHEAD];
94 static int lookahead_bufpos;
95 static stack_entry_t *environment_stack = NULL;
96 static stack_entry_t *label_stack = NULL;
97 static scope_t *global_scope = NULL;
98 static scope_t *scope = NULL;
99 static declaration_t *last_declaration = NULL;
100 static declaration_t *current_function = NULL;
101 static switch_statement_t *current_switch = NULL;
102 static statement_t *current_loop = NULL;
103 static ms_try_statement_t *current_try = NULL;
104 static goto_statement_t *goto_first = NULL;
105 static goto_statement_t *goto_last = NULL;
106 static label_statement_t *label_first = NULL;
107 static label_statement_t *label_last = NULL;
108 static translation_unit_t *unit = NULL;
109 static struct obstack temp_obst;
111 static source_position_t null_position = { NULL, 0 };
113 /* symbols for Microsoft extended-decl-modifier */
114 static const symbol_t *sym_align = NULL;
115 static const symbol_t *sym_allocate = NULL;
116 static const symbol_t *sym_dllimport = NULL;
117 static const symbol_t *sym_dllexport = NULL;
118 static const symbol_t *sym_naked = NULL;
119 static const symbol_t *sym_noinline = NULL;
120 static const symbol_t *sym_noreturn = NULL;
121 static const symbol_t *sym_nothrow = NULL;
122 static const symbol_t *sym_novtable = NULL;
123 static const symbol_t *sym_property = NULL;
124 static const symbol_t *sym_get = NULL;
125 static const symbol_t *sym_put = NULL;
126 static const symbol_t *sym_selectany = NULL;
127 static const symbol_t *sym_thread = NULL;
128 static const symbol_t *sym_uuid = NULL;
129 static const symbol_t *sym_deprecated = NULL;
130 static const symbol_t *sym_restrict = NULL;
131 static const symbol_t *sym_noalias = NULL;
133 /** The token anchor set */
134 static unsigned char token_anchor_set[T_LAST_TOKEN];
136 /** The current source position. */
137 #define HERE (&token.source_position)
139 static type_t *type_valist;
141 static statement_t *parse_compound_statement(bool inside_expression_statement);
142 static statement_t *parse_statement(void);
144 static expression_t *parse_sub_expression(unsigned precedence);
145 static expression_t *parse_expression(void);
146 static type_t *parse_typename(void);
148 static void parse_compound_type_entries(declaration_t *compound_declaration);
149 static declaration_t *parse_declarator(
150 const declaration_specifiers_t *specifiers, bool may_be_abstract);
151 static declaration_t *record_declaration(declaration_t *declaration);
153 static void semantic_comparison(binary_expression_t *expression);
155 #define STORAGE_CLASSES \
162 #define TYPE_QUALIFIERS \
167 case T__forceinline: \
168 case T___attribute__:
170 #ifdef PROVIDE_COMPLEX
171 #define COMPLEX_SPECIFIERS \
173 #define IMAGINARY_SPECIFIERS \
176 #define COMPLEX_SPECIFIERS
177 #define IMAGINARY_SPECIFIERS
180 #define TYPE_SPECIFIERS \
195 case T___builtin_va_list: \
200 #define DECLARATION_START \
205 #define TYPENAME_START \
210 * Allocate an AST node with given size and
211 * initialize all fields with zero.
213 static void *allocate_ast_zero(size_t size)
215 void *res = allocate_ast(size);
216 memset(res, 0, size);
220 static declaration_t *allocate_declaration_zero(void)
222 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
223 declaration->type = type_error_type;
224 declaration->alignment = 0;
229 * Returns the size of a statement node.
231 * @param kind the statement kind
233 static size_t get_statement_struct_size(statement_kind_t kind)
235 static const size_t sizes[] = {
236 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
237 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
238 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
239 [STATEMENT_RETURN] = sizeof(return_statement_t),
240 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
241 [STATEMENT_IF] = sizeof(if_statement_t),
242 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
243 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
244 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
245 [STATEMENT_BREAK] = sizeof(statement_base_t),
246 [STATEMENT_GOTO] = sizeof(goto_statement_t),
247 [STATEMENT_LABEL] = sizeof(label_statement_t),
248 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
249 [STATEMENT_WHILE] = sizeof(while_statement_t),
250 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
251 [STATEMENT_FOR] = sizeof(for_statement_t),
252 [STATEMENT_ASM] = sizeof(asm_statement_t),
253 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
254 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
256 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
257 assert(sizes[kind] != 0);
262 * Returns the size of an expression node.
264 * @param kind the expression kind
266 static size_t get_expression_struct_size(expression_kind_t kind)
268 static const size_t sizes[] = {
269 [EXPR_INVALID] = sizeof(expression_base_t),
270 [EXPR_REFERENCE] = sizeof(reference_expression_t),
271 [EXPR_CONST] = sizeof(const_expression_t),
272 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
273 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
274 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
275 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
276 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
277 [EXPR_CALL] = sizeof(call_expression_t),
278 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
279 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
280 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
281 [EXPR_SELECT] = sizeof(select_expression_t),
282 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
283 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
284 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
285 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
286 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
287 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
288 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
289 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
290 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
291 [EXPR_VA_START] = sizeof(va_start_expression_t),
292 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
293 [EXPR_STATEMENT] = sizeof(statement_expression_t),
295 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
296 return sizes[EXPR_UNARY_FIRST];
298 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
299 return sizes[EXPR_BINARY_FIRST];
301 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
302 assert(sizes[kind] != 0);
307 * Allocate a statement node of given kind and initialize all
310 static statement_t *allocate_statement_zero(statement_kind_t kind)
312 size_t size = get_statement_struct_size(kind);
313 statement_t *res = allocate_ast_zero(size);
315 res->base.kind = kind;
320 * Allocate an expression node of given kind and initialize all
323 static expression_t *allocate_expression_zero(expression_kind_t kind)
325 size_t size = get_expression_struct_size(kind);
326 expression_t *res = allocate_ast_zero(size);
328 res->base.kind = kind;
329 res->base.type = type_error_type;
334 * Creates a new invalid expression.
336 static expression_t *create_invalid_expression(void)
338 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
339 expression->base.source_position = token.source_position;
344 * Creates a new invalid statement.
346 static statement_t *create_invalid_statement(void)
348 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
349 statement->base.source_position = token.source_position;
354 * Allocate a new empty statement.
356 static statement_t *create_empty_statement(void)
358 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
359 statement->base.source_position = token.source_position;
364 * Returns the size of a type node.
366 * @param kind the type kind
368 static size_t get_type_struct_size(type_kind_t kind)
370 static const size_t sizes[] = {
371 [TYPE_ATOMIC] = sizeof(atomic_type_t),
372 [TYPE_COMPLEX] = sizeof(complex_type_t),
373 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
374 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
375 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
376 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
377 [TYPE_ENUM] = sizeof(enum_type_t),
378 [TYPE_FUNCTION] = sizeof(function_type_t),
379 [TYPE_POINTER] = sizeof(pointer_type_t),
380 [TYPE_ARRAY] = sizeof(array_type_t),
381 [TYPE_BUILTIN] = sizeof(builtin_type_t),
382 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
383 [TYPE_TYPEOF] = sizeof(typeof_type_t),
385 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
386 assert(kind <= TYPE_TYPEOF);
387 assert(sizes[kind] != 0);
392 * Allocate a type node of given kind and initialize all
395 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
397 size_t size = get_type_struct_size(kind);
398 type_t *res = obstack_alloc(type_obst, size);
399 memset(res, 0, size);
401 res->base.kind = kind;
402 res->base.source_position = *source_position;
407 * Returns the size of an initializer node.
409 * @param kind the initializer kind
411 static size_t get_initializer_size(initializer_kind_t kind)
413 static const size_t sizes[] = {
414 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
415 [INITIALIZER_STRING] = sizeof(initializer_string_t),
416 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
417 [INITIALIZER_LIST] = sizeof(initializer_list_t),
418 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
420 assert(kind < sizeof(sizes) / sizeof(*sizes));
421 assert(sizes[kind] != 0);
426 * Allocate an initializer node of given kind and initialize all
429 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
431 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
438 * Free a type from the type obstack.
440 static void free_type(void *type)
442 obstack_free(type_obst, type);
446 * Returns the index of the top element of the environment stack.
448 static size_t environment_top(void)
450 return ARR_LEN(environment_stack);
454 * Returns the index of the top element of the label stack.
456 static size_t label_top(void)
458 return ARR_LEN(label_stack);
462 * Return the next token.
464 static inline void next_token(void)
466 token = lookahead_buffer[lookahead_bufpos];
467 lookahead_buffer[lookahead_bufpos] = lexer_token;
470 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
473 print_token(stderr, &token);
474 fprintf(stderr, "\n");
479 * Return the next token with a given lookahead.
481 static inline const token_t *look_ahead(int num)
483 assert(num > 0 && num <= MAX_LOOKAHEAD);
484 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
485 return &lookahead_buffer[pos];
489 * Adds a token to the token anchor set (a multi-set).
491 static void add_anchor_token(int token_type) {
492 assert(0 <= token_type && token_type < T_LAST_TOKEN);
493 ++token_anchor_set[token_type];
496 static int save_and_reset_anchor_state(int token_type) {
497 assert(0 <= token_type && token_type < T_LAST_TOKEN);
498 int count = token_anchor_set[token_type];
499 token_anchor_set[token_type] = 0;
503 static void restore_anchor_state(int token_type, int count) {
504 assert(0 <= token_type && token_type < T_LAST_TOKEN);
505 token_anchor_set[token_type] = count;
509 * Remove a token from the token anchor set (a multi-set).
511 static void rem_anchor_token(int token_type) {
512 assert(0 <= token_type && token_type < T_LAST_TOKEN);
513 --token_anchor_set[token_type];
516 static bool at_anchor(void) {
519 return token_anchor_set[token.type];
523 * Eat tokens until a matching token is found.
525 static void eat_until_matching_token(int type) {
526 unsigned parenthesis_count = 0;
527 unsigned brace_count = 0;
528 unsigned bracket_count = 0;
532 case '(': end_token = ')'; break;
533 case '{': end_token = '}'; break;
534 case '[': end_token = ']'; break;
535 default: end_token = type; break;
538 while(token.type != end_token ||
539 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
543 case '(': ++parenthesis_count; break;
544 case '{': ++brace_count; break;
545 case '[': ++bracket_count; break;
547 if (parenthesis_count > 0)
555 if (bracket_count > 0)
566 * Eat input tokens until an anchor is found.
568 static void eat_until_anchor(void) {
569 if (token.type == T_EOF)
571 while(token_anchor_set[token.type] == 0) {
572 if (token.type == '(' || token.type == '{' || token.type == '[')
573 eat_until_matching_token(token.type);
574 if (token.type == T_EOF)
580 static void eat_block(void) {
581 eat_until_matching_token('{');
582 if (token.type == '}')
587 * eat all token until a ';' is reached or a stop token is found.
589 static void eat_statement(void) {
590 eat_until_matching_token(';');
591 if (token.type == ';')
595 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
598 * Report a parse error because an expected token was not found.
601 #if defined __GNUC__ && __GNUC__ >= 4
602 __attribute__((sentinel))
604 void parse_error_expected(const char *message, ...)
606 if (message != NULL) {
607 errorf(HERE, "%s", message);
610 va_start(ap, message);
611 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
616 * Report a type error.
618 static void type_error(const char *msg, const source_position_t *source_position,
621 errorf(source_position, "%s, but found type '%T'", msg, type);
625 * Report an incompatible type.
627 static void type_error_incompatible(const char *msg,
628 const source_position_t *source_position, type_t *type1, type_t *type2)
630 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
635 * Expect the the current token is the expected token.
636 * If not, generate an error, eat the current statement,
637 * and goto the end_error label.
639 #define expect(expected) \
641 if (UNLIKELY(token.type != (expected))) { \
642 parse_error_expected(NULL, (expected), NULL); \
643 add_anchor_token(expected); \
644 eat_until_anchor(); \
645 if (token.type == expected) \
647 rem_anchor_token(expected); \
653 static void set_scope(scope_t *new_scope)
656 scope->last_declaration = last_declaration;
660 last_declaration = new_scope->last_declaration;
664 * Search a symbol in a given namespace and returns its declaration or
665 * NULL if this symbol was not found.
667 static declaration_t *get_declaration(const symbol_t *const symbol,
668 const namespace_t namespc)
670 declaration_t *declaration = symbol->declaration;
671 for( ; declaration != NULL; declaration = declaration->symbol_next) {
672 if (declaration->namespc == namespc)
680 * pushs an environment_entry on the environment stack and links the
681 * corresponding symbol to the new entry
683 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
685 symbol_t *symbol = declaration->symbol;
686 namespace_t namespc = (namespace_t) declaration->namespc;
688 /* replace/add declaration into declaration list of the symbol */
689 declaration_t *iter = symbol->declaration;
691 symbol->declaration = declaration;
693 declaration_t *iter_last = NULL;
694 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
695 /* replace an entry? */
696 if (iter->namespc == namespc) {
697 if (iter_last == NULL) {
698 symbol->declaration = declaration;
700 iter_last->symbol_next = declaration;
702 declaration->symbol_next = iter->symbol_next;
707 assert(iter_last->symbol_next == NULL);
708 iter_last->symbol_next = declaration;
712 /* remember old declaration */
714 entry.symbol = symbol;
715 entry.old_declaration = iter;
716 entry.namespc = (unsigned short) namespc;
717 ARR_APP1(stack_entry_t, *stack_ptr, entry);
720 static void environment_push(declaration_t *declaration)
722 assert(declaration->source_position.input_name != NULL);
723 assert(declaration->parent_scope != NULL);
724 stack_push(&environment_stack, declaration);
727 static void label_push(declaration_t *declaration)
729 declaration->parent_scope = ¤t_function->scope;
730 stack_push(&label_stack, declaration);
734 * pops symbols from the environment stack until @p new_top is the top element
736 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
738 stack_entry_t *stack = *stack_ptr;
739 size_t top = ARR_LEN(stack);
742 assert(new_top <= top);
746 for(i = top; i > new_top; --i) {
747 stack_entry_t *entry = &stack[i - 1];
749 declaration_t *old_declaration = entry->old_declaration;
750 symbol_t *symbol = entry->symbol;
751 namespace_t namespc = (namespace_t)entry->namespc;
753 /* replace/remove declaration */
754 declaration_t *declaration = symbol->declaration;
755 assert(declaration != NULL);
756 if (declaration->namespc == namespc) {
757 if (old_declaration == NULL) {
758 symbol->declaration = declaration->symbol_next;
760 symbol->declaration = old_declaration;
763 declaration_t *iter_last = declaration;
764 declaration_t *iter = declaration->symbol_next;
765 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
766 /* replace an entry? */
767 if (iter->namespc == namespc) {
768 assert(iter_last != NULL);
769 iter_last->symbol_next = old_declaration;
770 if (old_declaration != NULL) {
771 old_declaration->symbol_next = iter->symbol_next;
776 assert(iter != NULL);
780 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
783 static void environment_pop_to(size_t new_top)
785 stack_pop_to(&environment_stack, new_top);
788 static void label_pop_to(size_t new_top)
790 stack_pop_to(&label_stack, new_top);
794 static int get_rank(const type_t *type)
796 assert(!is_typeref(type));
797 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
798 * and esp. footnote 108). However we can't fold constants (yet), so we
799 * can't decide whether unsigned int is possible, while int always works.
800 * (unsigned int would be preferable when possible... for stuff like
801 * struct { enum { ... } bla : 4; } ) */
802 if (type->kind == TYPE_ENUM)
803 return ATOMIC_TYPE_INT;
805 assert(type->kind == TYPE_ATOMIC);
806 return type->atomic.akind;
809 static type_t *promote_integer(type_t *type)
811 if (type->kind == TYPE_BITFIELD)
812 type = type->bitfield.base_type;
814 if (get_rank(type) < ATOMIC_TYPE_INT)
821 * Create a cast expression.
823 * @param expression the expression to cast
824 * @param dest_type the destination type
826 static expression_t *create_cast_expression(expression_t *expression,
829 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
831 cast->unary.value = expression;
832 cast->base.type = dest_type;
838 * Check if a given expression represents the 0 pointer constant.
840 static bool is_null_pointer_constant(const expression_t *expression)
842 /* skip void* cast */
843 if (expression->kind == EXPR_UNARY_CAST
844 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
845 expression = expression->unary.value;
848 /* TODO: not correct yet, should be any constant integer expression
849 * which evaluates to 0 */
850 if (expression->kind != EXPR_CONST)
853 type_t *const type = skip_typeref(expression->base.type);
854 if (!is_type_integer(type))
857 return expression->conste.v.int_value == 0;
861 * Create an implicit cast expression.
863 * @param expression the expression to cast
864 * @param dest_type the destination type
866 static expression_t *create_implicit_cast(expression_t *expression,
869 type_t *const source_type = expression->base.type;
871 if (source_type == dest_type)
874 return create_cast_expression(expression, dest_type);
877 typedef enum assign_error_t {
879 ASSIGN_ERROR_INCOMPATIBLE,
880 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
881 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
882 ASSIGN_WARNING_POINTER_FROM_INT,
883 ASSIGN_WARNING_INT_FROM_POINTER
886 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
887 const expression_t *const right,
889 const source_position_t *source_position)
891 type_t *const orig_type_right = right->base.type;
892 type_t *const type_left = skip_typeref(orig_type_left);
893 type_t *const type_right = skip_typeref(orig_type_right);
898 case ASSIGN_ERROR_INCOMPATIBLE:
899 errorf(source_position,
900 "destination type '%T' in %s is incompatible with type '%T'",
901 orig_type_left, context, orig_type_right);
904 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
905 type_t *points_to_left
906 = skip_typeref(type_left->pointer.points_to);
907 type_t *points_to_right
908 = skip_typeref(type_right->pointer.points_to);
910 /* the left type has all qualifiers from the right type */
911 unsigned missing_qualifiers
912 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
913 errorf(source_position,
914 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type",
915 orig_type_left, context, orig_type_right, missing_qualifiers);
919 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
920 warningf(source_position,
921 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
922 orig_type_left, context, right, orig_type_right);
925 case ASSIGN_WARNING_POINTER_FROM_INT:
926 warningf(source_position,
927 "%s makes integer '%T' from pointer '%T' without a cast",
928 context, orig_type_left, orig_type_right);
931 case ASSIGN_WARNING_INT_FROM_POINTER:
932 warningf(source_position,
933 "%s makes integer '%T' from pointer '%T' without a cast",
934 context, orig_type_left, orig_type_right);
938 panic("invalid error value");
942 /** Implements the rules from § 6.5.16.1 */
943 static assign_error_t semantic_assign(type_t *orig_type_left,
944 const expression_t *const right)
946 type_t *const orig_type_right = right->base.type;
947 type_t *const type_left = skip_typeref(orig_type_left);
948 type_t *const type_right = skip_typeref(orig_type_right);
950 if (is_type_pointer(type_left)) {
951 if (is_null_pointer_constant(right)) {
952 return ASSIGN_SUCCESS;
953 } else if (is_type_pointer(type_right)) {
954 type_t *points_to_left
955 = skip_typeref(type_left->pointer.points_to);
956 type_t *points_to_right
957 = skip_typeref(type_right->pointer.points_to);
959 /* the left type has all qualifiers from the right type */
960 unsigned missing_qualifiers
961 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
962 if (missing_qualifiers != 0) {
963 return ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
966 points_to_left = get_unqualified_type(points_to_left);
967 points_to_right = get_unqualified_type(points_to_right);
969 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
970 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
971 return ASSIGN_SUCCESS;
974 if (!types_compatible(points_to_left, points_to_right)) {
975 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
978 return ASSIGN_SUCCESS;
979 } else if (is_type_integer(type_right)) {
980 return ASSIGN_WARNING_POINTER_FROM_INT;
982 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
983 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
984 && is_type_pointer(type_right))) {
985 return ASSIGN_SUCCESS;
986 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
987 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
988 type_t *const unqual_type_left = get_unqualified_type(type_left);
989 type_t *const unqual_type_right = get_unqualified_type(type_right);
990 if (types_compatible(unqual_type_left, unqual_type_right)) {
991 return ASSIGN_SUCCESS;
993 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
994 return ASSIGN_WARNING_INT_FROM_POINTER;
997 if (!is_type_valid(type_left) || !is_type_valid(type_right))
998 return ASSIGN_SUCCESS;
1000 return ASSIGN_ERROR_INCOMPATIBLE;
1003 static expression_t *parse_constant_expression(void)
1005 /* start parsing at precedence 7 (conditional expression) */
1006 expression_t *result = parse_sub_expression(7);
1008 if (!is_constant_expression(result)) {
1009 errorf(&result->base.source_position,
1010 "expression '%E' is not constant\n", result);
1016 static expression_t *parse_assignment_expression(void)
1018 /* start parsing at precedence 2 (assignment expression) */
1019 return parse_sub_expression(2);
1022 static type_t *make_global_typedef(const char *name, type_t *type)
1024 symbol_t *const symbol = symbol_table_insert(name);
1026 declaration_t *const declaration = allocate_declaration_zero();
1027 declaration->namespc = NAMESPACE_NORMAL;
1028 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1029 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1030 declaration->type = type;
1031 declaration->symbol = symbol;
1032 declaration->source_position = builtin_source_position;
1034 record_declaration(declaration);
1036 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1037 typedef_type->typedeft.declaration = declaration;
1039 return typedef_type;
1042 static string_t parse_string_literals(void)
1044 assert(token.type == T_STRING_LITERAL);
1045 string_t result = token.v.string;
1049 while (token.type == T_STRING_LITERAL) {
1050 result = concat_strings(&result, &token.v.string);
1057 static const char *gnu_attribute_names[GNU_AK_LAST] = {
1058 [GNU_AK_CONST] = "const",
1059 [GNU_AK_VOLATILE] = "volatile",
1060 [GNU_AK_CDECL] = "cdecl",
1061 [GNU_AK_STDCALL] = "stdcall",
1062 [GNU_AK_FASTCALL] = "fastcall",
1063 [GNU_AK_DEPRECATED] = "deprecated",
1064 [GNU_AK_NOINLINE] = "noinline",
1065 [GNU_AK_NORETURN] = "noreturn",
1066 [GNU_AK_NAKED] = "naked",
1067 [GNU_AK_PURE] = "pure",
1068 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1069 [GNU_AK_MALLOC] = "malloc",
1070 [GNU_AK_WEAK] = "weak",
1071 [GNU_AK_CONSTRUCTOR] = "constructor",
1072 [GNU_AK_DESTRUCTOR] = "destructor",
1073 [GNU_AK_NOTHROW] = "nothrow",
1074 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1075 [GNU_AK_COMMON] = "common",
1076 [GNU_AK_NOCOMMON] = "nocommon",
1077 [GNU_AK_PACKED] = "packed",
1078 [GNU_AK_SHARED] = "shared",
1079 [GNU_AK_NOTSHARED] = "notshared",
1080 [GNU_AK_USED] = "used",
1081 [GNU_AK_UNUSED] = "unused",
1082 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1083 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1084 [GNU_AK_LONGCALL] = "longcall",
1085 [GNU_AK_SHORTCALL] = "shortcall",
1086 [GNU_AK_LONG_CALL] = "long_call",
1087 [GNU_AK_SHORT_CALL] = "short_call",
1088 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1089 [GNU_AK_INTERRUPT] = "interrupt",
1090 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1091 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1092 [GNU_AK_NESTING] = "nesting",
1093 [GNU_AK_NEAR] = "near",
1094 [GNU_AK_FAR] = "far",
1095 [GNU_AK_SIGNAL] = "signal",
1096 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1097 [GNU_AK_TINY_DATA] = "tiny_data",
1098 [GNU_AK_SAVEALL] = "saveall",
1099 [GNU_AK_FLATTEN] = "flatten",
1100 [GNU_AK_SSEREGPARM] = "sseregparm",
1101 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1102 [GNU_AK_RETURN_TWICE] = "return_twice",
1103 [GNU_AK_MAY_ALIAS] = "may_alias",
1104 [GNU_AK_MS_STRUCT] = "ms_struct",
1105 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1106 [GNU_AK_DLLIMPORT] = "dllimport",
1107 [GNU_AK_DLLEXPORT] = "dllexport",
1108 [GNU_AK_ALIGNED] = "aligned",
1109 [GNU_AK_ALIAS] = "alias",
1110 [GNU_AK_SECTION] = "section",
1111 [GNU_AK_FORMAT] = "format",
1112 [GNU_AK_FORMAT_ARG] = "format_arg",
1113 [GNU_AK_WEAKREF] = "weakref",
1114 [GNU_AK_NONNULL] = "nonnull",
1115 [GNU_AK_TLS_MODEL] = "tls_model",
1116 [GNU_AK_VISIBILITY] = "visibility",
1117 [GNU_AK_REGPARM] = "regparm",
1118 [GNU_AK_MODE] = "mode",
1119 [GNU_AK_MODEL] = "model",
1120 [GNU_AK_TRAP_EXIT] = "trap_exit",
1121 [GNU_AK_SP_SWITCH] = "sp_switch",
1122 [GNU_AK_SENTINEL] = "sentinel"
1126 * compare two string, ignoring double underscores on the second.
1128 static int strcmp_underscore(const char *s1, const char *s2) {
1129 if (s2[0] == '_' && s2[1] == '_') {
1130 size_t len2 = strlen(s2);
1131 size_t len1 = strlen(s1);
1132 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1133 return strncmp(s1, s2+2, len2-4);
1137 return strcmp(s1, s2);
1141 * Allocate a new gnu temporal attribute.
1143 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1144 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1145 attribute->kind = kind;
1146 attribute->next = NULL;
1147 attribute->invalid = false;
1148 attribute->have_arguments = false;
1154 * parse one constant expression argument.
1156 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1157 expression_t *expression;
1158 add_anchor_token(')');
1159 expression = parse_constant_expression();
1160 rem_anchor_token(')');
1165 attribute->invalid = true;
1169 * parse a list of constant expressions arguments.
1171 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1172 expression_t *expression;
1173 add_anchor_token(')');
1174 add_anchor_token(',');
1176 expression = parse_constant_expression();
1177 if (token.type != ',')
1181 rem_anchor_token(',');
1182 rem_anchor_token(')');
1187 attribute->invalid = true;
1191 * parse one string literal argument.
1193 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1196 add_anchor_token('(');
1197 if (token.type != T_STRING_LITERAL) {
1198 parse_error_expected("while parsing attribute directive",
1199 T_STRING_LITERAL, NULL);
1202 *string = parse_string_literals();
1203 rem_anchor_token('(');
1207 attribute->invalid = true;
1211 * parse one tls model.
1213 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1214 static const char *tls_models[] = {
1220 string_t string = { NULL, 0 };
1221 parse_gnu_attribute_string_arg(attribute, &string);
1222 if (string.begin != NULL) {
1223 for(size_t i = 0; i < 4; ++i) {
1224 if (strcmp(tls_models[i], string.begin) == 0) {
1225 attribute->u.value = i;
1229 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1231 attribute->invalid = true;
1235 * parse one tls model.
1237 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1238 static const char *visibilities[] = {
1244 string_t string = { NULL, 0 };
1245 parse_gnu_attribute_string_arg(attribute, &string);
1246 if (string.begin != NULL) {
1247 for(size_t i = 0; i < 4; ++i) {
1248 if (strcmp(visibilities[i], string.begin) == 0) {
1249 attribute->u.value = i;
1253 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1255 attribute->invalid = true;
1259 * parse one (code) model.
1261 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1262 static const char *visibilities[] = {
1267 string_t string = { NULL, 0 };
1268 parse_gnu_attribute_string_arg(attribute, &string);
1269 if (string.begin != NULL) {
1270 for(int i = 0; i < 3; ++i) {
1271 if (strcmp(visibilities[i], string.begin) == 0) {
1272 attribute->u.value = i;
1276 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1278 attribute->invalid = true;
1281 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1283 /* TODO: find out what is allowed here... */
1285 /* at least: byte, word, pointer, list of machine modes
1286 * __XXX___ is interpreted as XXX */
1287 add_anchor_token(')');
1289 if (token.type != T_IDENTIFIER) {
1290 expect(T_IDENTIFIER);
1293 /* This isn't really correct, the backend should provide a list of machine
1294 * specific modes (according to gcc philosophy that is...) */
1295 const char *symbol_str = token.v.symbol->string;
1296 if (strcmp_underscore("QI", symbol_str) == 0 ||
1297 strcmp_underscore("byte", symbol_str) == 0) {
1298 attribute->u.akind = ATOMIC_TYPE_CHAR;
1299 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1300 attribute->u.akind = ATOMIC_TYPE_SHORT;
1301 } else if (strcmp_underscore("SI", symbol_str) == 0
1302 || strcmp_underscore("word", symbol_str) == 0
1303 || strcmp_underscore("pointer", symbol_str) == 0) {
1304 attribute->u.akind = ATOMIC_TYPE_INT;
1305 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1306 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1308 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1309 attribute->invalid = true;
1313 rem_anchor_token(')');
1317 attribute->invalid = true;
1321 * parse one interrupt argument.
1323 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1324 static const char *interrupts[] = {
1331 string_t string = { NULL, 0 };
1332 parse_gnu_attribute_string_arg(attribute, &string);
1333 if (string.begin != NULL) {
1334 for(size_t i = 0; i < 5; ++i) {
1335 if (strcmp(interrupts[i], string.begin) == 0) {
1336 attribute->u.value = i;
1340 errorf(HERE, "'%s' is not an interrupt", string.begin);
1342 attribute->invalid = true;
1346 * parse ( identifier, const expression, const expression )
1348 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1349 static const char *format_names[] = {
1357 if (token.type != T_IDENTIFIER) {
1358 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1361 const char *name = token.v.symbol->string;
1362 for(i = 0; i < 4; ++i) {
1363 if (strcmp_underscore(format_names[i], name) == 0)
1367 if (warning.attribute)
1368 warningf(HERE, "'%s' is an unrecognized format function type", name);
1373 add_anchor_token(')');
1374 add_anchor_token(',');
1375 parse_constant_expression();
1376 rem_anchor_token(',');
1377 rem_anchor_token('(');
1380 add_anchor_token(')');
1381 parse_constant_expression();
1382 rem_anchor_token('(');
1386 attribute->u.value = true;
1389 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1391 if (!attribute->have_arguments)
1394 /* should have no arguments */
1395 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1396 eat_until_matching_token('(');
1397 /* we have already consumed '(', so we stop before ')', eat it */
1399 attribute->invalid = true;
1403 * Parse one GNU attribute.
1405 * Note that attribute names can be specified WITH or WITHOUT
1406 * double underscores, ie const or __const__.
1408 * The following attributes are parsed without arguments
1433 * no_instrument_function
1434 * warn_unused_result
1451 * externally_visible
1459 * The following attributes are parsed with arguments
1460 * aligned( const expression )
1461 * alias( string literal )
1462 * section( string literal )
1463 * format( identifier, const expression, const expression )
1464 * format_arg( const expression )
1465 * tls_model( string literal )
1466 * visibility( string literal )
1467 * regparm( const expression )
1468 * model( string leteral )
1469 * trap_exit( const expression )
1470 * sp_switch( string literal )
1472 * The following attributes might have arguments
1473 * weak_ref( string literal )
1474 * non_null( const expression // ',' )
1475 * interrupt( string literal )
1476 * sentinel( constant expression )
1478 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1480 gnu_attribute_t *head = *attributes;
1481 gnu_attribute_t *last = *attributes;
1482 decl_modifiers_t modifiers = 0;
1483 gnu_attribute_t *attribute;
1485 eat(T___attribute__);
1489 if (token.type != ')') {
1490 /* find the end of the list */
1492 while(last->next != NULL)
1496 /* non-empty attribute list */
1499 if (token.type == T_const) {
1501 } else if (token.type == T_volatile) {
1503 } else if (token.type == T_cdecl) {
1504 /* __attribute__((cdecl)), WITH ms mode */
1506 } else if (token.type == T_IDENTIFIER) {
1507 const symbol_t *sym = token.v.symbol;
1510 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1517 for(i = 0; i < GNU_AK_LAST; ++i) {
1518 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1521 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1524 if (kind == GNU_AK_LAST) {
1525 if (warning.attribute)
1526 warningf(HERE, "'%s' attribute directive ignored", name);
1528 /* skip possible arguments */
1529 if (token.type == '(') {
1530 eat_until_matching_token(')');
1533 /* check for arguments */
1534 attribute = allocate_gnu_attribute(kind);
1535 if (token.type == '(') {
1537 if (token.type == ')') {
1538 /* empty args are allowed */
1541 attribute->have_arguments = true;
1546 case GNU_AK_VOLATILE:
1547 case GNU_AK_DEPRECATED:
1552 case GNU_AK_NOCOMMON:
1554 case GNU_AK_NOTSHARED:
1556 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1557 case GNU_AK_WARN_UNUSED_RESULT:
1558 case GNU_AK_LONGCALL:
1559 case GNU_AK_SHORTCALL:
1560 case GNU_AK_LONG_CALL:
1561 case GNU_AK_SHORT_CALL:
1562 case GNU_AK_FUNCTION_VECTOR:
1563 case GNU_AK_INTERRUPT_HANDLER:
1564 case GNU_AK_NMI_HANDLER:
1565 case GNU_AK_NESTING:
1569 case GNU_AK_EIGTHBIT_DATA:
1570 case GNU_AK_TINY_DATA:
1571 case GNU_AK_SAVEALL:
1572 case GNU_AK_FLATTEN:
1573 case GNU_AK_SSEREGPARM:
1574 case GNU_AK_EXTERNALLY_VISIBLE:
1575 case GNU_AK_RETURN_TWICE:
1576 case GNU_AK_MAY_ALIAS:
1577 case GNU_AK_MS_STRUCT:
1578 case GNU_AK_GCC_STRUCT:
1581 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1582 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1583 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1584 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1585 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1586 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1587 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1588 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1589 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1590 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1591 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1592 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1593 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1594 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1595 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1597 case GNU_AK_ALIGNED:
1598 /* __align__ may be used without an argument */
1599 if (attribute->have_arguments) {
1600 parse_gnu_attribute_const_arg(attribute);
1604 case GNU_AK_FORMAT_ARG:
1605 case GNU_AK_REGPARM:
1606 case GNU_AK_TRAP_EXIT:
1607 if (!attribute->have_arguments) {
1608 /* should have arguments */
1609 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1610 attribute->invalid = true;
1612 parse_gnu_attribute_const_arg(attribute);
1615 case GNU_AK_SECTION:
1616 case GNU_AK_SP_SWITCH:
1617 if (!attribute->have_arguments) {
1618 /* should have arguments */
1619 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1620 attribute->invalid = true;
1622 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1625 if (!attribute->have_arguments) {
1626 /* should have arguments */
1627 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1628 attribute->invalid = true;
1630 parse_gnu_attribute_format_args(attribute);
1632 case GNU_AK_WEAKREF:
1633 /* may have one string argument */
1634 if (attribute->have_arguments)
1635 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1637 case GNU_AK_NONNULL:
1638 if (attribute->have_arguments)
1639 parse_gnu_attribute_const_arg_list(attribute);
1641 case GNU_AK_TLS_MODEL:
1642 if (!attribute->have_arguments) {
1643 /* should have arguments */
1644 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1646 parse_gnu_attribute_tls_model_arg(attribute);
1648 case GNU_AK_VISIBILITY:
1649 if (!attribute->have_arguments) {
1650 /* should have arguments */
1651 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1653 parse_gnu_attribute_visibility_arg(attribute);
1656 if (!attribute->have_arguments) {
1657 /* should have arguments */
1658 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1660 parse_gnu_attribute_model_arg(attribute);
1664 if (!attribute->have_arguments) {
1665 /* should have arguments */
1666 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1668 parse_gnu_attribute_mode_arg(attribute);
1671 case GNU_AK_INTERRUPT:
1672 /* may have one string argument */
1673 if (attribute->have_arguments)
1674 parse_gnu_attribute_interrupt_arg(attribute);
1676 case GNU_AK_SENTINEL:
1677 /* may have one string argument */
1678 if (attribute->have_arguments)
1679 parse_gnu_attribute_const_arg(attribute);
1682 /* already handled */
1686 check_no_argument(attribute, name);
1689 if (attribute != NULL) {
1691 last->next = attribute;
1694 head = last = attribute;
1698 if (token.type != ',')
1712 * Parse GNU attributes.
1714 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1716 decl_modifiers_t modifiers = 0;
1719 switch(token.type) {
1720 case T___attribute__:
1721 modifiers |= parse_gnu_attribute(attributes);
1727 if (token.type != T_STRING_LITERAL) {
1728 parse_error_expected("while parsing assembler attribute",
1729 T_STRING_LITERAL, NULL);
1730 eat_until_matching_token('(');
1733 parse_string_literals();
1738 case T_cdecl: modifiers |= DM_CDECL; break;
1739 case T__fastcall: modifiers |= DM_FASTCALL; break;
1740 case T__stdcall: modifiers |= DM_STDCALL; break;
1743 /* TODO record modifier */
1744 warningf(HERE, "Ignoring declaration modifier %K", &token);
1748 default: return modifiers;
1755 static designator_t *parse_designation(void)
1757 designator_t *result = NULL;
1758 designator_t *last = NULL;
1761 designator_t *designator;
1762 switch(token.type) {
1764 designator = allocate_ast_zero(sizeof(designator[0]));
1765 designator->source_position = token.source_position;
1767 add_anchor_token(']');
1768 designator->array_index = parse_constant_expression();
1769 rem_anchor_token(']');
1773 designator = allocate_ast_zero(sizeof(designator[0]));
1774 designator->source_position = token.source_position;
1776 if (token.type != T_IDENTIFIER) {
1777 parse_error_expected("while parsing designator",
1778 T_IDENTIFIER, NULL);
1781 designator->symbol = token.v.symbol;
1789 assert(designator != NULL);
1791 last->next = designator;
1793 result = designator;
1801 static initializer_t *initializer_from_string(array_type_t *type,
1802 const string_t *const string)
1804 /* TODO: check len vs. size of array type */
1807 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1808 initializer->string.string = *string;
1813 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1814 wide_string_t *const string)
1816 /* TODO: check len vs. size of array type */
1819 initializer_t *const initializer =
1820 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1821 initializer->wide_string.string = *string;
1827 * Build an initializer from a given expression.
1829 static initializer_t *initializer_from_expression(type_t *orig_type,
1830 expression_t *expression)
1832 /* TODO check that expression is a constant expression */
1834 /* § 6.7.8.14/15 char array may be initialized by string literals */
1835 type_t *type = skip_typeref(orig_type);
1836 type_t *expr_type_orig = expression->base.type;
1837 type_t *expr_type = skip_typeref(expr_type_orig);
1838 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1839 array_type_t *const array_type = &type->array;
1840 type_t *const element_type = skip_typeref(array_type->element_type);
1842 if (element_type->kind == TYPE_ATOMIC) {
1843 atomic_type_kind_t akind = element_type->atomic.akind;
1844 switch (expression->kind) {
1845 case EXPR_STRING_LITERAL:
1846 if (akind == ATOMIC_TYPE_CHAR
1847 || akind == ATOMIC_TYPE_SCHAR
1848 || akind == ATOMIC_TYPE_UCHAR) {
1849 return initializer_from_string(array_type,
1850 &expression->string.value);
1853 case EXPR_WIDE_STRING_LITERAL: {
1854 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1855 if (get_unqualified_type(element_type) == bare_wchar_type) {
1856 return initializer_from_wide_string(array_type,
1857 &expression->wide_string.value);
1867 assign_error_t error = semantic_assign(type, expression);
1868 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1870 report_assign_error(error, type, expression, "initializer",
1871 &expression->base.source_position);
1873 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1874 result->value.value = create_implicit_cast(expression, type);
1880 * Checks if a given expression can be used as an constant initializer.
1882 static bool is_initializer_constant(const expression_t *expression)
1884 return is_constant_expression(expression)
1885 || is_address_constant(expression);
1889 * Parses an scalar initializer.
1891 * § 6.7.8.11; eat {} without warning
1893 static initializer_t *parse_scalar_initializer(type_t *type,
1894 bool must_be_constant)
1896 /* there might be extra {} hierarchies */
1898 if (token.type == '{') {
1899 warningf(HERE, "extra curly braces around scalar initializer");
1903 } while (token.type == '{');
1906 expression_t *expression = parse_assignment_expression();
1907 if (must_be_constant && !is_initializer_constant(expression)) {
1908 errorf(&expression->base.source_position,
1909 "Initialisation expression '%E' is not constant\n",
1913 initializer_t *initializer = initializer_from_expression(type, expression);
1915 if (initializer == NULL) {
1916 errorf(&expression->base.source_position,
1917 "expression '%E' (type '%T') doesn't match expected type '%T'",
1918 expression, expression->base.type, type);
1923 bool additional_warning_displayed = false;
1925 if (token.type == ',') {
1928 if (token.type != '}') {
1929 if (!additional_warning_displayed) {
1930 warningf(HERE, "additional elements in scalar initializer");
1931 additional_warning_displayed = true;
1942 * An entry in the type path.
1944 typedef struct type_path_entry_t type_path_entry_t;
1945 struct type_path_entry_t {
1946 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1948 size_t index; /**< For array types: the current index. */
1949 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1954 * A type path expression a position inside compound or array types.
1956 typedef struct type_path_t type_path_t;
1957 struct type_path_t {
1958 type_path_entry_t *path; /**< An flexible array containing the current path. */
1959 type_t *top_type; /**< type of the element the path points */
1960 size_t max_index; /**< largest index in outermost array */
1964 * Prints a type path for debugging.
1966 static __attribute__((unused)) void debug_print_type_path(
1967 const type_path_t *path)
1969 size_t len = ARR_LEN(path->path);
1971 for(size_t i = 0; i < len; ++i) {
1972 const type_path_entry_t *entry = & path->path[i];
1974 type_t *type = skip_typeref(entry->type);
1975 if (is_type_compound(type)) {
1976 /* in gcc mode structs can have no members */
1977 if (entry->v.compound_entry == NULL) {
1981 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1982 } else if (is_type_array(type)) {
1983 fprintf(stderr, "[%zd]", entry->v.index);
1985 fprintf(stderr, "-INVALID-");
1988 if (path->top_type != NULL) {
1989 fprintf(stderr, " (");
1990 print_type(path->top_type);
1991 fprintf(stderr, ")");
1996 * Return the top type path entry, ie. in a path
1997 * (type).a.b returns the b.
1999 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2001 size_t len = ARR_LEN(path->path);
2003 return &path->path[len-1];
2007 * Enlarge the type path by an (empty) element.
2009 static type_path_entry_t *append_to_type_path(type_path_t *path)
2011 size_t len = ARR_LEN(path->path);
2012 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2014 type_path_entry_t *result = & path->path[len];
2015 memset(result, 0, sizeof(result[0]));
2020 * Descending into a sub-type. Enter the scope of the current
2023 static void descend_into_subtype(type_path_t *path)
2025 type_t *orig_top_type = path->top_type;
2026 type_t *top_type = skip_typeref(orig_top_type);
2028 assert(is_type_compound(top_type) || is_type_array(top_type));
2030 type_path_entry_t *top = append_to_type_path(path);
2031 top->type = top_type;
2033 if (is_type_compound(top_type)) {
2034 declaration_t *declaration = top_type->compound.declaration;
2035 declaration_t *entry = declaration->scope.declarations;
2036 top->v.compound_entry = entry;
2038 if (entry != NULL) {
2039 path->top_type = entry->type;
2041 path->top_type = NULL;
2044 assert(is_type_array(top_type));
2047 path->top_type = top_type->array.element_type;
2052 * Pop an entry from the given type path, ie. returning from
2053 * (type).a.b to (type).a
2055 static void ascend_from_subtype(type_path_t *path)
2057 type_path_entry_t *top = get_type_path_top(path);
2059 path->top_type = top->type;
2061 size_t len = ARR_LEN(path->path);
2062 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2066 * Pop entries from the given type path until the given
2067 * path level is reached.
2069 static void ascend_to(type_path_t *path, size_t top_path_level)
2071 size_t len = ARR_LEN(path->path);
2073 while(len > top_path_level) {
2074 ascend_from_subtype(path);
2075 len = ARR_LEN(path->path);
2079 static bool walk_designator(type_path_t *path, const designator_t *designator,
2080 bool used_in_offsetof)
2082 for( ; designator != NULL; designator = designator->next) {
2083 type_path_entry_t *top = get_type_path_top(path);
2084 type_t *orig_type = top->type;
2086 type_t *type = skip_typeref(orig_type);
2088 if (designator->symbol != NULL) {
2089 symbol_t *symbol = designator->symbol;
2090 if (!is_type_compound(type)) {
2091 if (is_type_valid(type)) {
2092 errorf(&designator->source_position,
2093 "'.%Y' designator used for non-compound type '%T'",
2099 declaration_t *declaration = type->compound.declaration;
2100 declaration_t *iter = declaration->scope.declarations;
2101 for( ; iter != NULL; iter = iter->next) {
2102 if (iter->symbol == symbol) {
2107 errorf(&designator->source_position,
2108 "'%T' has no member named '%Y'", orig_type, symbol);
2111 if (used_in_offsetof) {
2112 type_t *real_type = skip_typeref(iter->type);
2113 if (real_type->kind == TYPE_BITFIELD) {
2114 errorf(&designator->source_position,
2115 "offsetof designator '%Y' may not specify bitfield",
2121 top->type = orig_type;
2122 top->v.compound_entry = iter;
2123 orig_type = iter->type;
2125 expression_t *array_index = designator->array_index;
2126 assert(designator->array_index != NULL);
2128 if (!is_type_array(type)) {
2129 if (is_type_valid(type)) {
2130 errorf(&designator->source_position,
2131 "[%E] designator used for non-array type '%T'",
2132 array_index, orig_type);
2136 if (!is_type_valid(array_index->base.type)) {
2140 long index = fold_constant(array_index);
2141 if (!used_in_offsetof) {
2143 errorf(&designator->source_position,
2144 "array index [%E] must be positive", array_index);
2147 if (type->array.size_constant == true) {
2148 long array_size = type->array.size;
2149 if (index >= array_size) {
2150 errorf(&designator->source_position,
2151 "designator [%E] (%d) exceeds array size %d",
2152 array_index, index, array_size);
2158 top->type = orig_type;
2159 top->v.index = (size_t) index;
2160 orig_type = type->array.element_type;
2162 path->top_type = orig_type;
2164 if (designator->next != NULL) {
2165 descend_into_subtype(path);
2174 static void advance_current_object(type_path_t *path, size_t top_path_level)
2176 type_path_entry_t *top = get_type_path_top(path);
2178 type_t *type = skip_typeref(top->type);
2179 if (is_type_union(type)) {
2180 /* in unions only the first element is initialized */
2181 top->v.compound_entry = NULL;
2182 } else if (is_type_struct(type)) {
2183 declaration_t *entry = top->v.compound_entry;
2185 entry = entry->next;
2186 top->v.compound_entry = entry;
2187 if (entry != NULL) {
2188 path->top_type = entry->type;
2192 assert(is_type_array(type));
2196 if (!type->array.size_constant || top->v.index < type->array.size) {
2201 /* we're past the last member of the current sub-aggregate, try if we
2202 * can ascend in the type hierarchy and continue with another subobject */
2203 size_t len = ARR_LEN(path->path);
2205 if (len > top_path_level) {
2206 ascend_from_subtype(path);
2207 advance_current_object(path, top_path_level);
2209 path->top_type = NULL;
2214 * skip until token is found.
2216 static void skip_until(int type) {
2217 while(token.type != type) {
2218 if (token.type == T_EOF)
2225 * skip any {...} blocks until a closing bracket is reached.
2227 static void skip_initializers(void)
2229 if (token.type == '{')
2232 while(token.type != '}') {
2233 if (token.type == T_EOF)
2235 if (token.type == '{') {
2243 static initializer_t *create_empty_initializer(void)
2245 static initializer_t empty_initializer
2246 = { .list = { { INITIALIZER_LIST }, 0 } };
2247 return &empty_initializer;
2251 * Parse a part of an initialiser for a struct or union,
2253 static initializer_t *parse_sub_initializer(type_path_t *path,
2254 type_t *outer_type, size_t top_path_level,
2255 parse_initializer_env_t *env)
2257 if (token.type == '}') {
2258 /* empty initializer */
2259 return create_empty_initializer();
2262 type_t *orig_type = path->top_type;
2263 type_t *type = NULL;
2265 if (orig_type == NULL) {
2266 /* We are initializing an empty compound. */
2268 type = skip_typeref(orig_type);
2270 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2271 * initializers in this case. */
2272 if (!is_type_valid(type)) {
2273 skip_initializers();
2274 return create_empty_initializer();
2278 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2281 designator_t *designator = NULL;
2282 if (token.type == '.' || token.type == '[') {
2283 designator = parse_designation();
2285 /* reset path to toplevel, evaluate designator from there */
2286 ascend_to(path, top_path_level);
2287 if (!walk_designator(path, designator, false)) {
2288 /* can't continue after designation error */
2292 initializer_t *designator_initializer
2293 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2294 designator_initializer->designator.designator = designator;
2295 ARR_APP1(initializer_t*, initializers, designator_initializer);
2297 orig_type = path->top_type;
2298 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2303 if (token.type == '{') {
2304 if (type != NULL && is_type_scalar(type)) {
2305 sub = parse_scalar_initializer(type, env->must_be_constant);
2309 if (env->declaration != NULL) {
2310 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2311 env->declaration->symbol);
2313 errorf(HERE, "extra brace group at end of initializer");
2316 descend_into_subtype(path);
2318 add_anchor_token('}');
2319 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2321 rem_anchor_token('}');
2324 ascend_from_subtype(path);
2328 goto error_parse_next;
2332 /* must be an expression */
2333 expression_t *expression = parse_assignment_expression();
2335 if (env->must_be_constant && !is_initializer_constant(expression)) {
2336 errorf(&expression->base.source_position,
2337 "Initialisation expression '%E' is not constant\n",
2342 /* we are already outside, ... */
2346 /* handle { "string" } special case */
2347 if ((expression->kind == EXPR_STRING_LITERAL
2348 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2349 && outer_type != NULL) {
2350 sub = initializer_from_expression(outer_type, expression);
2352 if (token.type == ',') {
2355 if (token.type != '}') {
2356 warningf(HERE, "excessive elements in initializer for type '%T'",
2359 /* TODO: eat , ... */
2364 /* descend into subtypes until expression matches type */
2366 orig_type = path->top_type;
2367 type = skip_typeref(orig_type);
2369 sub = initializer_from_expression(orig_type, expression);
2373 if (!is_type_valid(type)) {
2376 if (is_type_scalar(type)) {
2377 errorf(&expression->base.source_position,
2378 "expression '%E' doesn't match expected type '%T'",
2379 expression, orig_type);
2383 descend_into_subtype(path);
2387 /* update largest index of top array */
2388 const type_path_entry_t *first = &path->path[0];
2389 type_t *first_type = first->type;
2390 first_type = skip_typeref(first_type);
2391 if (is_type_array(first_type)) {
2392 size_t index = first->v.index;
2393 if (index > path->max_index)
2394 path->max_index = index;
2398 /* append to initializers list */
2399 ARR_APP1(initializer_t*, initializers, sub);
2402 if (env->declaration != NULL)
2403 warningf(HERE, "excess elements in struct initializer for '%Y'",
2404 env->declaration->symbol);
2406 warningf(HERE, "excess elements in struct initializer");
2410 if (token.type == '}') {
2414 if (token.type == '}') {
2419 /* advance to the next declaration if we are not at the end */
2420 advance_current_object(path, top_path_level);
2421 orig_type = path->top_type;
2422 if (orig_type != NULL)
2423 type = skip_typeref(orig_type);
2429 size_t len = ARR_LEN(initializers);
2430 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2431 initializer_t *result = allocate_ast_zero(size);
2432 result->kind = INITIALIZER_LIST;
2433 result->list.len = len;
2434 memcpy(&result->list.initializers, initializers,
2435 len * sizeof(initializers[0]));
2437 DEL_ARR_F(initializers);
2438 ascend_to(path, top_path_level+1);
2443 skip_initializers();
2444 DEL_ARR_F(initializers);
2445 ascend_to(path, top_path_level+1);
2450 * Parses an initializer. Parsers either a compound literal
2451 * (env->declaration == NULL) or an initializer of a declaration.
2453 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2455 type_t *type = skip_typeref(env->type);
2456 initializer_t *result = NULL;
2459 if (is_type_scalar(type)) {
2460 result = parse_scalar_initializer(type, env->must_be_constant);
2461 } else if (token.type == '{') {
2465 memset(&path, 0, sizeof(path));
2466 path.top_type = env->type;
2467 path.path = NEW_ARR_F(type_path_entry_t, 0);
2469 descend_into_subtype(&path);
2471 add_anchor_token('}');
2472 result = parse_sub_initializer(&path, env->type, 1, env);
2473 rem_anchor_token('}');
2475 max_index = path.max_index;
2476 DEL_ARR_F(path.path);
2480 /* parse_scalar_initializer() also works in this case: we simply
2481 * have an expression without {} around it */
2482 result = parse_scalar_initializer(type, env->must_be_constant);
2485 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2486 * the array type size */
2487 if (is_type_array(type) && type->array.size_expression == NULL
2488 && result != NULL) {
2490 switch (result->kind) {
2491 case INITIALIZER_LIST:
2492 size = max_index + 1;
2495 case INITIALIZER_STRING:
2496 size = result->string.string.size;
2499 case INITIALIZER_WIDE_STRING:
2500 size = result->wide_string.string.size;
2503 case INITIALIZER_DESIGNATOR:
2504 case INITIALIZER_VALUE:
2505 /* can happen for parse errors */
2510 internal_errorf(HERE, "invalid initializer type");
2513 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2514 cnst->base.type = type_size_t;
2515 cnst->conste.v.int_value = size;
2517 type_t *new_type = duplicate_type(type);
2519 new_type->array.size_expression = cnst;
2520 new_type->array.size_constant = true;
2521 new_type->array.size = size;
2522 env->type = new_type;
2530 static declaration_t *append_declaration(declaration_t *declaration);
2532 static declaration_t *parse_compound_type_specifier(bool is_struct)
2534 gnu_attribute_t *attributes = NULL;
2535 decl_modifiers_t modifiers = 0;
2542 symbol_t *symbol = NULL;
2543 declaration_t *declaration = NULL;
2545 if (token.type == T___attribute__) {
2546 modifiers |= parse_attributes(&attributes);
2549 if (token.type == T_IDENTIFIER) {
2550 symbol = token.v.symbol;
2553 namespace_t const namespc =
2554 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2555 declaration = get_declaration(symbol, namespc);
2556 if (declaration != NULL) {
2557 if (declaration->parent_scope != scope &&
2558 (token.type == '{' || token.type == ';')) {
2560 } else if (declaration->init.complete &&
2561 token.type == '{') {
2562 assert(symbol != NULL);
2563 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2564 is_struct ? "struct" : "union", symbol,
2565 &declaration->source_position);
2566 declaration->scope.declarations = NULL;
2569 } else if (token.type != '{') {
2571 parse_error_expected("while parsing struct type specifier",
2572 T_IDENTIFIER, '{', NULL);
2574 parse_error_expected("while parsing union type specifier",
2575 T_IDENTIFIER, '{', NULL);
2581 if (declaration == NULL) {
2582 declaration = allocate_declaration_zero();
2583 declaration->namespc =
2584 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2585 declaration->source_position = token.source_position;
2586 declaration->symbol = symbol;
2587 declaration->parent_scope = scope;
2588 if (symbol != NULL) {
2589 environment_push(declaration);
2591 append_declaration(declaration);
2594 if (token.type == '{') {
2595 declaration->init.complete = true;
2597 parse_compound_type_entries(declaration);
2598 modifiers |= parse_attributes(&attributes);
2601 declaration->modifiers |= modifiers;
2605 static void parse_enum_entries(type_t *const enum_type)
2609 if (token.type == '}') {
2611 errorf(HERE, "empty enum not allowed");
2615 add_anchor_token('}');
2617 if (token.type != T_IDENTIFIER) {
2618 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2620 rem_anchor_token('}');
2624 declaration_t *const entry = allocate_declaration_zero();
2625 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2626 entry->type = enum_type;
2627 entry->symbol = token.v.symbol;
2628 entry->source_position = token.source_position;
2631 if (token.type == '=') {
2633 expression_t *value = parse_constant_expression();
2635 value = create_implicit_cast(value, enum_type);
2636 entry->init.enum_value = value;
2641 record_declaration(entry);
2643 if (token.type != ',')
2646 } while(token.type != '}');
2647 rem_anchor_token('}');
2655 static type_t *parse_enum_specifier(void)
2657 gnu_attribute_t *attributes = NULL;
2658 declaration_t *declaration;
2662 if (token.type == T_IDENTIFIER) {
2663 symbol = token.v.symbol;
2666 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2667 } else if (token.type != '{') {
2668 parse_error_expected("while parsing enum type specifier",
2669 T_IDENTIFIER, '{', NULL);
2676 if (declaration == NULL) {
2677 declaration = allocate_declaration_zero();
2678 declaration->namespc = NAMESPACE_ENUM;
2679 declaration->source_position = token.source_position;
2680 declaration->symbol = symbol;
2681 declaration->parent_scope = scope;
2684 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2685 type->enumt.declaration = declaration;
2687 if (token.type == '{') {
2688 if (declaration->init.complete) {
2689 errorf(HERE, "multiple definitions of enum %Y", symbol);
2691 if (symbol != NULL) {
2692 environment_push(declaration);
2694 append_declaration(declaration);
2695 declaration->init.complete = true;
2697 parse_enum_entries(type);
2698 parse_attributes(&attributes);
2705 * if a symbol is a typedef to another type, return true
2707 static bool is_typedef_symbol(symbol_t *symbol)
2709 const declaration_t *const declaration =
2710 get_declaration(symbol, NAMESPACE_NORMAL);
2712 declaration != NULL &&
2713 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2716 static type_t *parse_typeof(void)
2723 add_anchor_token(')');
2725 expression_t *expression = NULL;
2728 switch(token.type) {
2729 case T___extension__:
2730 /* this can be a prefix to a typename or an expression */
2731 /* we simply eat it now. */
2734 } while(token.type == T___extension__);
2738 if (is_typedef_symbol(token.v.symbol)) {
2739 type = parse_typename();
2741 expression = parse_expression();
2742 type = expression->base.type;
2747 type = parse_typename();
2751 expression = parse_expression();
2752 type = expression->base.type;
2756 rem_anchor_token(')');
2759 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2760 typeof_type->typeoft.expression = expression;
2761 typeof_type->typeoft.typeof_type = type;
2769 SPECIFIER_SIGNED = 1 << 0,
2770 SPECIFIER_UNSIGNED = 1 << 1,
2771 SPECIFIER_LONG = 1 << 2,
2772 SPECIFIER_INT = 1 << 3,
2773 SPECIFIER_DOUBLE = 1 << 4,
2774 SPECIFIER_CHAR = 1 << 5,
2775 SPECIFIER_SHORT = 1 << 6,
2776 SPECIFIER_LONG_LONG = 1 << 7,
2777 SPECIFIER_FLOAT = 1 << 8,
2778 SPECIFIER_BOOL = 1 << 9,
2779 SPECIFIER_VOID = 1 << 10,
2780 SPECIFIER_INT8 = 1 << 11,
2781 SPECIFIER_INT16 = 1 << 12,
2782 SPECIFIER_INT32 = 1 << 13,
2783 SPECIFIER_INT64 = 1 << 14,
2784 SPECIFIER_INT128 = 1 << 15,
2785 SPECIFIER_COMPLEX = 1 << 16,
2786 SPECIFIER_IMAGINARY = 1 << 17,
2789 static type_t *create_builtin_type(symbol_t *const symbol,
2790 type_t *const real_type)
2792 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2793 type->builtin.symbol = symbol;
2794 type->builtin.real_type = real_type;
2796 type_t *result = typehash_insert(type);
2797 if (type != result) {
2804 static type_t *get_typedef_type(symbol_t *symbol)
2806 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2807 if (declaration == NULL ||
2808 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2811 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2812 type->typedeft.declaration = declaration;
2818 * check for the allowed MS alignment values.
2820 static bool check_elignment_value(long long intvalue) {
2821 if (intvalue < 1 || intvalue > 8192) {
2822 errorf(HERE, "illegal alignment value");
2825 unsigned v = (unsigned)intvalue;
2826 for(unsigned i = 1; i <= 8192; i += i) {
2830 errorf(HERE, "alignment must be power of two");
2834 #define DET_MOD(name, tag) do { \
2835 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2836 *modifiers |= tag; \
2839 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2841 decl_modifiers_t *modifiers = &specifiers->modifiers;
2844 if (token.type == T_restrict) {
2846 DET_MOD(restrict, DM_RESTRICT);
2848 } else if (token.type != T_IDENTIFIER)
2850 symbol_t *symbol = token.v.symbol;
2851 if (symbol == sym_align) {
2854 if (token.type != T_INTEGER)
2856 if (check_elignment_value(token.v.intvalue)) {
2857 if (specifiers->alignment != 0)
2858 warningf(HERE, "align used more than once");
2859 specifiers->alignment = (unsigned char)token.v.intvalue;
2863 } else if (symbol == sym_allocate) {
2866 if (token.type != T_IDENTIFIER)
2868 (void)token.v.symbol;
2870 } else if (symbol == sym_dllimport) {
2872 DET_MOD(dllimport, DM_DLLIMPORT);
2873 } else if (symbol == sym_dllexport) {
2875 DET_MOD(dllexport, DM_DLLEXPORT);
2876 } else if (symbol == sym_thread) {
2878 DET_MOD(thread, DM_THREAD);
2879 } else if (symbol == sym_naked) {
2881 DET_MOD(naked, DM_NAKED);
2882 } else if (symbol == sym_noinline) {
2884 DET_MOD(noinline, DM_NOINLINE);
2885 } else if (symbol == sym_noreturn) {
2887 DET_MOD(noreturn, DM_NORETURN);
2888 } else if (symbol == sym_nothrow) {
2890 DET_MOD(nothrow, DM_NOTHROW);
2891 } else if (symbol == sym_novtable) {
2893 DET_MOD(novtable, DM_NOVTABLE);
2894 } else if (symbol == sym_property) {
2898 bool is_get = false;
2899 if (token.type != T_IDENTIFIER)
2901 if (token.v.symbol == sym_get) {
2903 } else if (token.v.symbol == sym_put) {
2905 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2910 if (token.type != T_IDENTIFIER)
2913 if (specifiers->get_property_sym != NULL) {
2914 errorf(HERE, "get property name already specified");
2916 specifiers->get_property_sym = token.v.symbol;
2919 if (specifiers->put_property_sym != NULL) {
2920 errorf(HERE, "put property name already specified");
2922 specifiers->put_property_sym = token.v.symbol;
2926 if (token.type == ',') {
2933 } else if (symbol == sym_selectany) {
2935 DET_MOD(selectany, DM_SELECTANY);
2936 } else if (symbol == sym_uuid) {
2939 if (token.type != T_STRING_LITERAL)
2943 } else if (symbol == sym_deprecated) {
2945 if (specifiers->deprecated != 0)
2946 warningf(HERE, "deprecated used more than once");
2947 specifiers->deprecated = 1;
2948 if (token.type == '(') {
2950 if (token.type == T_STRING_LITERAL) {
2951 specifiers->deprecated_string = token.v.string.begin;
2954 errorf(HERE, "string literal expected");
2958 } else if (symbol == sym_noalias) {
2960 DET_MOD(noalias, DM_NOALIAS);
2962 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2964 if (token.type == '(')
2968 if (token.type == ',')
2975 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2977 type_t *type = NULL;
2978 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2979 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
2980 unsigned type_specifiers = 0;
2983 specifiers->source_position = token.source_position;
2986 specifiers->modifiers
2987 |= parse_attributes(&specifiers->gnu_attributes);
2988 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
2989 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
2991 switch(token.type) {
2994 #define MATCH_STORAGE_CLASS(token, class) \
2996 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2997 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2999 specifiers->declared_storage_class = class; \
3003 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3004 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3005 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3006 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3007 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3012 add_anchor_token(')');
3013 parse_microsoft_extended_decl_modifier(specifiers);
3014 rem_anchor_token(')');
3019 switch (specifiers->declared_storage_class) {
3020 case STORAGE_CLASS_NONE:
3021 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3024 case STORAGE_CLASS_EXTERN:
3025 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3028 case STORAGE_CLASS_STATIC:
3029 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3033 errorf(HERE, "multiple storage classes in declaration specifiers");
3039 /* type qualifiers */
3040 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3042 qualifiers |= qualifier; \
3046 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3047 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3048 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3049 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3050 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3051 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3052 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3053 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3055 case T___extension__:
3060 /* type specifiers */
3061 #define MATCH_SPECIFIER(token, specifier, name) \
3064 if (type_specifiers & specifier) { \
3065 errorf(HERE, "multiple " name " type specifiers given"); \
3067 type_specifiers |= specifier; \
3071 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3072 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3073 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3074 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3075 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3076 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3077 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3078 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3079 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3080 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3081 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3082 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3083 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3084 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3085 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3086 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3088 case T__forceinline:
3089 /* only in microsoft mode */
3090 specifiers->modifiers |= DM_FORCEINLINE;
3094 specifiers->is_inline = true;
3099 if (type_specifiers & SPECIFIER_LONG_LONG) {
3100 errorf(HERE, "multiple type specifiers given");
3101 } else if (type_specifiers & SPECIFIER_LONG) {
3102 type_specifiers |= SPECIFIER_LONG_LONG;
3104 type_specifiers |= SPECIFIER_LONG;
3109 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3111 type->compound.declaration = parse_compound_type_specifier(true);
3115 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3116 type->compound.declaration = parse_compound_type_specifier(false);
3117 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3118 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3122 type = parse_enum_specifier();
3125 type = parse_typeof();
3127 case T___builtin_va_list:
3128 type = duplicate_type(type_valist);
3132 case T_IDENTIFIER: {
3133 /* only parse identifier if we haven't found a type yet */
3134 if (type != NULL || type_specifiers != 0)
3135 goto finish_specifiers;
3137 type_t *typedef_type = get_typedef_type(token.v.symbol);
3139 if (typedef_type == NULL)
3140 goto finish_specifiers;
3143 type = typedef_type;
3147 /* function specifier */
3149 goto finish_specifiers;
3156 atomic_type_kind_t atomic_type;
3158 /* match valid basic types */
3159 switch(type_specifiers) {
3160 case SPECIFIER_VOID:
3161 atomic_type = ATOMIC_TYPE_VOID;
3163 case SPECIFIER_CHAR:
3164 atomic_type = ATOMIC_TYPE_CHAR;
3166 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3167 atomic_type = ATOMIC_TYPE_SCHAR;
3169 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3170 atomic_type = ATOMIC_TYPE_UCHAR;
3172 case SPECIFIER_SHORT:
3173 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3174 case SPECIFIER_SHORT | SPECIFIER_INT:
3175 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3176 atomic_type = ATOMIC_TYPE_SHORT;
3178 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3179 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3180 atomic_type = ATOMIC_TYPE_USHORT;
3183 case SPECIFIER_SIGNED:
3184 case SPECIFIER_SIGNED | SPECIFIER_INT:
3185 atomic_type = ATOMIC_TYPE_INT;
3187 case SPECIFIER_UNSIGNED:
3188 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3189 atomic_type = ATOMIC_TYPE_UINT;
3191 case SPECIFIER_LONG:
3192 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3193 case SPECIFIER_LONG | SPECIFIER_INT:
3194 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3195 atomic_type = ATOMIC_TYPE_LONG;
3197 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3198 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3199 atomic_type = ATOMIC_TYPE_ULONG;
3201 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3202 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3203 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3204 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3206 atomic_type = ATOMIC_TYPE_LONGLONG;
3208 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3209 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3211 atomic_type = ATOMIC_TYPE_ULONGLONG;
3214 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3215 atomic_type = unsigned_int8_type_kind;
3218 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3219 atomic_type = unsigned_int16_type_kind;
3222 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3223 atomic_type = unsigned_int32_type_kind;
3226 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3227 atomic_type = unsigned_int64_type_kind;
3230 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3231 atomic_type = unsigned_int128_type_kind;
3234 case SPECIFIER_INT8:
3235 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3236 atomic_type = int8_type_kind;
3239 case SPECIFIER_INT16:
3240 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3241 atomic_type = int16_type_kind;
3244 case SPECIFIER_INT32:
3245 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3246 atomic_type = int32_type_kind;
3249 case SPECIFIER_INT64:
3250 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3251 atomic_type = int64_type_kind;
3254 case SPECIFIER_INT128:
3255 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3256 atomic_type = int128_type_kind;
3259 case SPECIFIER_FLOAT:
3260 atomic_type = ATOMIC_TYPE_FLOAT;
3262 case SPECIFIER_DOUBLE:
3263 atomic_type = ATOMIC_TYPE_DOUBLE;
3265 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3266 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3268 case SPECIFIER_BOOL:
3269 atomic_type = ATOMIC_TYPE_BOOL;
3271 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3272 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3273 atomic_type = ATOMIC_TYPE_FLOAT;
3275 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3276 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3277 atomic_type = ATOMIC_TYPE_DOUBLE;
3279 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3280 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3281 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3284 /* invalid specifier combination, give an error message */
3285 if (type_specifiers == 0) {
3286 if (! strict_mode) {
3287 if (warning.implicit_int) {
3288 warningf(HERE, "no type specifiers in declaration, using 'int'");
3290 atomic_type = ATOMIC_TYPE_INT;
3293 errorf(HERE, "no type specifiers given in declaration");
3295 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3296 (type_specifiers & SPECIFIER_UNSIGNED)) {
3297 errorf(HERE, "signed and unsigned specifiers gives");
3298 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3299 errorf(HERE, "only integer types can be signed or unsigned");
3301 errorf(HERE, "multiple datatypes in declaration");
3303 atomic_type = ATOMIC_TYPE_INVALID;
3306 if (type_specifiers & SPECIFIER_COMPLEX &&
3307 atomic_type != ATOMIC_TYPE_INVALID) {
3308 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3309 type->complex.akind = atomic_type;
3310 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3311 atomic_type != ATOMIC_TYPE_INVALID) {
3312 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3313 type->imaginary.akind = atomic_type;
3315 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3316 type->atomic.akind = atomic_type;
3320 if (type_specifiers != 0) {
3321 errorf(HERE, "multiple datatypes in declaration");
3325 /* FIXME: check type qualifiers here */
3327 type->base.qualifiers = qualifiers;
3328 type->base.modifiers = modifiers;
3330 type_t *result = typehash_insert(type);
3331 if (newtype && result != type) {
3335 specifiers->type = result;
3340 static type_qualifiers_t parse_type_qualifiers(void)
3342 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3345 switch(token.type) {
3346 /* type qualifiers */
3347 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3348 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3349 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3350 /* microsoft extended type modifiers */
3351 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3352 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3353 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3354 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3355 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3363 static declaration_t *parse_identifier_list(void)
3365 declaration_t *declarations = NULL;
3366 declaration_t *last_declaration = NULL;
3368 declaration_t *const declaration = allocate_declaration_zero();
3369 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3370 declaration->source_position = token.source_position;
3371 declaration->symbol = token.v.symbol;
3374 if (last_declaration != NULL) {
3375 last_declaration->next = declaration;
3377 declarations = declaration;
3379 last_declaration = declaration;
3381 if (token.type != ',') {
3385 } while(token.type == T_IDENTIFIER);
3387 return declarations;
3390 static void semantic_parameter(declaration_t *declaration)
3392 /* TODO: improve error messages */
3394 if (declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3395 errorf(HERE, "typedef not allowed in parameter list");
3396 } else if (declaration->declared_storage_class != STORAGE_CLASS_NONE
3397 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3398 errorf(HERE, "parameter may only have none or register storage class");
3401 type_t *const orig_type = declaration->type;
3402 type_t * type = skip_typeref(orig_type);
3404 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3405 * into a pointer. § 6.7.5.3 (7) */
3406 if (is_type_array(type)) {
3407 type_t *const element_type = type->array.element_type;
3409 type = make_pointer_type(element_type, type->base.qualifiers);
3411 declaration->type = type;
3414 if (is_type_incomplete(type)) {
3415 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3416 orig_type, declaration->symbol);
3420 static declaration_t *parse_parameter(void)
3422 declaration_specifiers_t specifiers;
3423 memset(&specifiers, 0, sizeof(specifiers));
3425 parse_declaration_specifiers(&specifiers);
3427 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3432 static declaration_t *parse_parameters(function_type_t *type)
3434 declaration_t *declarations = NULL;
3437 add_anchor_token(')');
3438 int saved_comma_state = save_and_reset_anchor_state(',');
3440 if (token.type == T_IDENTIFIER) {
3441 symbol_t *symbol = token.v.symbol;
3442 if (!is_typedef_symbol(symbol)) {
3443 type->kr_style_parameters = true;
3444 declarations = parse_identifier_list();
3445 goto parameters_finished;
3449 if (token.type == ')') {
3450 type->unspecified_parameters = 1;
3451 goto parameters_finished;
3454 declaration_t *declaration;
3455 declaration_t *last_declaration = NULL;
3456 function_parameter_t *parameter;
3457 function_parameter_t *last_parameter = NULL;
3460 switch(token.type) {
3464 goto parameters_finished;
3467 case T___extension__:
3469 declaration = parse_parameter();
3471 /* func(void) is not a parameter */
3472 if (last_parameter == NULL
3473 && token.type == ')'
3474 && declaration->symbol == NULL
3475 && skip_typeref(declaration->type) == type_void) {
3476 goto parameters_finished;
3478 semantic_parameter(declaration);
3480 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3481 memset(parameter, 0, sizeof(parameter[0]));
3482 parameter->type = declaration->type;
3484 if (last_parameter != NULL) {
3485 last_declaration->next = declaration;
3486 last_parameter->next = parameter;
3488 type->parameters = parameter;
3489 declarations = declaration;
3491 last_parameter = parameter;
3492 last_declaration = declaration;
3496 goto parameters_finished;
3498 if (token.type != ',') {
3499 goto parameters_finished;
3505 parameters_finished:
3506 rem_anchor_token(')');
3509 restore_anchor_state(',', saved_comma_state);
3510 return declarations;
3513 restore_anchor_state(',', saved_comma_state);
3522 } construct_type_kind_t;
3524 typedef struct construct_type_t construct_type_t;
3525 struct construct_type_t {
3526 construct_type_kind_t kind;
3527 construct_type_t *next;
3530 typedef struct parsed_pointer_t parsed_pointer_t;
3531 struct parsed_pointer_t {
3532 construct_type_t construct_type;
3533 type_qualifiers_t type_qualifiers;
3536 typedef struct construct_function_type_t construct_function_type_t;
3537 struct construct_function_type_t {
3538 construct_type_t construct_type;
3539 type_t *function_type;
3542 typedef struct parsed_array_t parsed_array_t;
3543 struct parsed_array_t {
3544 construct_type_t construct_type;
3545 type_qualifiers_t type_qualifiers;
3551 typedef struct construct_base_type_t construct_base_type_t;
3552 struct construct_base_type_t {
3553 construct_type_t construct_type;
3557 static construct_type_t *parse_pointer_declarator(void)
3561 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3562 memset(pointer, 0, sizeof(pointer[0]));
3563 pointer->construct_type.kind = CONSTRUCT_POINTER;
3564 pointer->type_qualifiers = parse_type_qualifiers();
3566 return (construct_type_t*) pointer;
3569 static construct_type_t *parse_array_declarator(void)
3572 add_anchor_token(']');
3574 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3575 memset(array, 0, sizeof(array[0]));
3576 array->construct_type.kind = CONSTRUCT_ARRAY;
3578 if (token.type == T_static) {
3579 array->is_static = true;
3583 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3584 if (type_qualifiers != 0) {
3585 if (token.type == T_static) {
3586 array->is_static = true;
3590 array->type_qualifiers = type_qualifiers;
3592 if (token.type == '*' && look_ahead(1)->type == ']') {
3593 array->is_variable = true;
3595 } else if (token.type != ']') {
3596 array->size = parse_assignment_expression();
3599 rem_anchor_token(']');
3602 return (construct_type_t*) array;
3607 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3610 if (declaration != NULL) {
3611 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3613 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3616 declaration_t *parameters = parse_parameters(&type->function);
3617 if (declaration != NULL) {
3618 declaration->scope.declarations = parameters;
3621 construct_function_type_t *construct_function_type =
3622 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3623 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3624 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3625 construct_function_type->function_type = type;
3627 return (construct_type_t*) construct_function_type;
3630 static void fix_declaration_type(declaration_t *declaration)
3632 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3633 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3635 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3636 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3638 if (declaration->type->base.modifiers == type_modifiers)
3641 type_t *copy = duplicate_type(declaration->type);
3642 copy->base.modifiers = type_modifiers;
3644 type_t *result = typehash_insert(copy);
3645 if (result != copy) {
3646 obstack_free(type_obst, copy);
3649 declaration->type = result;
3652 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3653 bool may_be_abstract)
3655 /* construct a single linked list of construct_type_t's which describe
3656 * how to construct the final declarator type */
3657 construct_type_t *first = NULL;
3658 construct_type_t *last = NULL;
3659 gnu_attribute_t *attributes = NULL;
3661 decl_modifiers_t modifiers = parse_attributes(&attributes);
3664 while(token.type == '*') {
3665 construct_type_t *type = parse_pointer_declarator();
3675 /* TODO: find out if this is correct */
3676 modifiers |= parse_attributes(&attributes);
3679 construct_type_t *inner_types = NULL;
3681 switch(token.type) {
3683 if (declaration == NULL) {
3684 errorf(HERE, "no identifier expected in typename");
3686 declaration->symbol = token.v.symbol;
3687 declaration->source_position = token.source_position;
3693 add_anchor_token(')');
3694 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3695 rem_anchor_token(')');
3699 if (may_be_abstract)
3701 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3702 /* avoid a loop in the outermost scope, because eat_statement doesn't
3704 if (token.type == '}' && current_function == NULL) {
3712 construct_type_t *p = last;
3715 construct_type_t *type;
3716 switch(token.type) {
3718 type = parse_function_declarator(declaration);
3721 type = parse_array_declarator();
3724 goto declarator_finished;
3727 /* insert in the middle of the list (behind p) */
3729 type->next = p->next;
3740 declarator_finished:
3741 /* append inner_types at the end of the list, we don't to set last anymore
3742 * as it's not needed anymore */
3744 assert(first == NULL);
3745 first = inner_types;
3747 last->next = inner_types;
3755 static void parse_declaration_attributes(declaration_t *declaration)
3757 gnu_attribute_t *attributes = NULL;
3758 decl_modifiers_t modifiers = parse_attributes(&attributes);
3760 if (declaration == NULL)
3763 declaration->modifiers |= modifiers;
3764 /* check if we have these stupid mode attributes... */
3765 type_t *old_type = declaration->type;
3766 if (old_type == NULL)
3769 gnu_attribute_t *attribute = attributes;
3770 for ( ; attribute != NULL; attribute = attribute->next) {
3771 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3774 atomic_type_kind_t akind = attribute->u.akind;
3775 if (!is_type_signed(old_type)) {
3777 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3778 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3779 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3780 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3782 panic("invalid akind in mode attribute");
3786 = make_atomic_type(akind, old_type->base.qualifiers);
3790 static type_t *construct_declarator_type(construct_type_t *construct_list,
3793 construct_type_t *iter = construct_list;
3794 for( ; iter != NULL; iter = iter->next) {
3795 switch(iter->kind) {
3796 case CONSTRUCT_INVALID:
3797 internal_errorf(HERE, "invalid type construction found");
3798 case CONSTRUCT_FUNCTION: {
3799 construct_function_type_t *construct_function_type
3800 = (construct_function_type_t*) iter;
3802 type_t *function_type = construct_function_type->function_type;
3804 function_type->function.return_type = type;
3806 type_t *skipped_return_type = skip_typeref(type);
3807 if (is_type_function(skipped_return_type)) {
3808 errorf(HERE, "function returning function is not allowed");
3809 type = type_error_type;
3810 } else if (is_type_array(skipped_return_type)) {
3811 errorf(HERE, "function returning array is not allowed");
3812 type = type_error_type;
3814 type = function_type;
3819 case CONSTRUCT_POINTER: {
3820 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3821 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3822 pointer_type->pointer.points_to = type;
3823 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3825 type = pointer_type;
3829 case CONSTRUCT_ARRAY: {
3830 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3831 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3833 expression_t *size_expression = parsed_array->size;
3834 if (size_expression != NULL) {
3836 = create_implicit_cast(size_expression, type_size_t);
3839 array_type->base.qualifiers = parsed_array->type_qualifiers;
3840 array_type->array.element_type = type;
3841 array_type->array.is_static = parsed_array->is_static;
3842 array_type->array.is_variable = parsed_array->is_variable;
3843 array_type->array.size_expression = size_expression;
3845 if (size_expression != NULL) {
3846 if (is_constant_expression(size_expression)) {
3847 array_type->array.size_constant = true;
3848 array_type->array.size
3849 = fold_constant(size_expression);
3851 array_type->array.is_vla = true;
3855 type_t *skipped_type = skip_typeref(type);
3856 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3857 errorf(HERE, "array of void is not allowed");
3858 type = type_error_type;
3866 type_t *hashed_type = typehash_insert(type);
3867 if (hashed_type != type) {
3868 /* the function type was constructed earlier freeing it here will
3869 * destroy other types... */
3870 if (iter->kind != CONSTRUCT_FUNCTION) {
3880 static declaration_t *parse_declarator(
3881 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3883 declaration_t *const declaration = allocate_declaration_zero();
3884 declaration->declared_storage_class = specifiers->declared_storage_class;
3885 declaration->modifiers = specifiers->modifiers;
3886 declaration->deprecated = specifiers->deprecated;
3887 declaration->deprecated_string = specifiers->deprecated_string;
3888 declaration->get_property_sym = specifiers->get_property_sym;
3889 declaration->put_property_sym = specifiers->put_property_sym;
3890 declaration->is_inline = specifiers->is_inline;
3892 declaration->storage_class = specifiers->declared_storage_class;
3893 if (declaration->storage_class == STORAGE_CLASS_NONE
3894 && scope != global_scope) {
3895 declaration->storage_class = STORAGE_CLASS_AUTO;
3898 if (specifiers->alignment != 0) {
3899 /* TODO: add checks here */
3900 declaration->alignment = specifiers->alignment;
3903 construct_type_t *construct_type
3904 = parse_inner_declarator(declaration, may_be_abstract);
3905 type_t *const type = specifiers->type;
3906 declaration->type = construct_declarator_type(construct_type, type);
3908 parse_declaration_attributes(declaration);
3910 fix_declaration_type(declaration);
3912 if (construct_type != NULL) {
3913 obstack_free(&temp_obst, construct_type);
3919 static type_t *parse_abstract_declarator(type_t *base_type)
3921 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3923 type_t *result = construct_declarator_type(construct_type, base_type);
3924 if (construct_type != NULL) {
3925 obstack_free(&temp_obst, construct_type);
3931 static declaration_t *append_declaration(declaration_t* const declaration)
3933 if (last_declaration != NULL) {
3934 last_declaration->next = declaration;
3936 scope->declarations = declaration;
3938 last_declaration = declaration;
3943 * Check if the declaration of main is suspicious. main should be a
3944 * function with external linkage, returning int, taking either zero
3945 * arguments, two, or three arguments of appropriate types, ie.
3947 * int main([ int argc, char **argv [, char **env ] ]).
3949 * @param decl the declaration to check
3950 * @param type the function type of the declaration
3952 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3954 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3955 warningf(&decl->source_position,
3956 "'main' is normally a non-static function");
3958 if (skip_typeref(func_type->return_type) != type_int) {
3959 warningf(&decl->source_position,
3960 "return type of 'main' should be 'int', but is '%T'",
3961 func_type->return_type);
3963 const function_parameter_t *parm = func_type->parameters;
3965 type_t *const first_type = parm->type;
3966 if (!types_compatible(skip_typeref(first_type), type_int)) {
3967 warningf(&decl->source_position,
3968 "first argument of 'main' should be 'int', but is '%T'", first_type);
3972 type_t *const second_type = parm->type;
3973 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3974 warningf(&decl->source_position,
3975 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3979 type_t *const third_type = parm->type;
3980 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3981 warningf(&decl->source_position,
3982 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3986 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3990 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3996 * Check if a symbol is the equal to "main".
3998 static bool is_sym_main(const symbol_t *const sym)
4000 return strcmp(sym->string, "main") == 0;
4003 static declaration_t *internal_record_declaration(
4004 declaration_t *const declaration,
4005 const bool is_function_definition)
4007 const symbol_t *const symbol = declaration->symbol;
4008 const namespace_t namespc = (namespace_t)declaration->namespc;
4010 assert(declaration->symbol != NULL);
4011 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4013 type_t *const orig_type = declaration->type;
4014 type_t *const type = skip_typeref(orig_type);
4015 if (is_type_function(type) &&
4016 type->function.unspecified_parameters &&
4017 warning.strict_prototypes &&
4018 previous_declaration == NULL) {
4019 warningf(&declaration->source_position,
4020 "function declaration '%#T' is not a prototype",
4021 orig_type, declaration->symbol);
4024 if (is_function_definition && warning.main && is_sym_main(symbol)) {
4025 check_type_of_main(declaration, &type->function);
4028 assert(declaration != previous_declaration);
4029 if (previous_declaration != NULL
4030 && previous_declaration->parent_scope == scope) {
4031 /* can happen for K&R style declarations */
4032 if (previous_declaration->type == NULL) {
4033 previous_declaration->type = declaration->type;
4036 const type_t *prev_type = skip_typeref(previous_declaration->type);
4037 if (!types_compatible(type, prev_type)) {
4038 errorf(&declaration->source_position,
4039 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4040 orig_type, symbol, previous_declaration->type, symbol,
4041 &previous_declaration->source_position);
4043 unsigned old_storage_class = previous_declaration->storage_class;
4044 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4045 errorf(&declaration->source_position,
4046 "redeclaration of enum entry '%Y' (declared %P)",
4047 symbol, &previous_declaration->source_position);
4048 return previous_declaration;
4051 unsigned new_storage_class = declaration->storage_class;
4053 if (is_type_incomplete(prev_type)) {
4054 previous_declaration->type = type;
4058 /* pretend no storage class means extern for function
4059 * declarations (except if the previous declaration is neither
4060 * none nor extern) */
4061 if (is_type_function(type)) {
4062 if (prev_type->function.unspecified_parameters) {
4063 previous_declaration->type = type;
4067 switch (old_storage_class) {
4068 case STORAGE_CLASS_NONE:
4069 old_storage_class = STORAGE_CLASS_EXTERN;
4072 case STORAGE_CLASS_EXTERN:
4073 if (is_function_definition) {
4074 if (warning.missing_prototypes &&
4075 prev_type->function.unspecified_parameters &&
4076 !is_sym_main(symbol)) {
4077 warningf(&declaration->source_position,
4078 "no previous prototype for '%#T'",
4081 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4082 new_storage_class = STORAGE_CLASS_EXTERN;
4091 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4092 new_storage_class == STORAGE_CLASS_EXTERN) {
4093 warn_redundant_declaration:
4094 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4095 warningf(&declaration->source_position,
4096 "redundant declaration for '%Y' (declared %P)",
4097 symbol, &previous_declaration->source_position);
4099 } else if (current_function == NULL) {
4100 if (old_storage_class != STORAGE_CLASS_STATIC &&
4101 new_storage_class == STORAGE_CLASS_STATIC) {
4102 errorf(&declaration->source_position,
4103 "static declaration of '%Y' follows non-static declaration (declared %P)",
4104 symbol, &previous_declaration->source_position);
4105 } else if (old_storage_class != STORAGE_CLASS_EXTERN
4106 && !is_function_definition) {
4107 goto warn_redundant_declaration;
4108 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4109 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4110 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4112 } else if (old_storage_class == new_storage_class) {
4113 errorf(&declaration->source_position,
4114 "redeclaration of '%Y' (declared %P)",
4115 symbol, &previous_declaration->source_position);
4117 errorf(&declaration->source_position,
4118 "redeclaration of '%Y' with different linkage (declared %P)",
4119 symbol, &previous_declaration->source_position);
4123 if (declaration->is_inline)
4124 previous_declaration->is_inline = true;
4125 return previous_declaration;
4126 } else if (is_function_definition) {
4127 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4128 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4129 warningf(&declaration->source_position,
4130 "no previous prototype for '%#T'", orig_type, symbol);
4131 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4132 warningf(&declaration->source_position,
4133 "no previous declaration for '%#T'", orig_type,
4137 } else if (warning.missing_declarations &&
4138 scope == global_scope &&
4139 !is_type_function(type) && (
4140 declaration->storage_class == STORAGE_CLASS_NONE ||
4141 declaration->storage_class == STORAGE_CLASS_THREAD
4143 warningf(&declaration->source_position,
4144 "no previous declaration for '%#T'", orig_type, symbol);
4147 assert(declaration->parent_scope == NULL);
4148 assert(scope != NULL);
4150 declaration->parent_scope = scope;
4152 environment_push(declaration);
4153 return append_declaration(declaration);
4156 static declaration_t *record_declaration(declaration_t *declaration)
4158 return internal_record_declaration(declaration, false);
4161 static declaration_t *record_function_definition(declaration_t *declaration)
4163 return internal_record_declaration(declaration, true);
4166 static void parser_error_multiple_definition(declaration_t *declaration,
4167 const source_position_t *source_position)
4169 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4170 declaration->symbol, &declaration->source_position);
4173 static bool is_declaration_specifier(const token_t *token,
4174 bool only_specifiers_qualifiers)
4176 switch(token->type) {
4181 return is_typedef_symbol(token->v.symbol);
4183 case T___extension__:
4185 return !only_specifiers_qualifiers;
4192 static void parse_init_declarator_rest(declaration_t *declaration)
4196 type_t *orig_type = declaration->type;
4197 type_t *type = skip_typeref(orig_type);
4199 if (declaration->init.initializer != NULL) {
4200 parser_error_multiple_definition(declaration, HERE);
4203 bool must_be_constant = false;
4204 if (declaration->storage_class == STORAGE_CLASS_STATIC
4205 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4206 || declaration->parent_scope == global_scope) {
4207 must_be_constant = true;
4210 parse_initializer_env_t env;
4211 env.type = orig_type;
4212 env.must_be_constant = must_be_constant;
4213 env.declaration = declaration;
4215 initializer_t *initializer = parse_initializer(&env);
4217 if (env.type != orig_type) {
4218 orig_type = env.type;
4219 type = skip_typeref(orig_type);
4220 declaration->type = env.type;
4223 if (is_type_function(type)) {
4224 errorf(&declaration->source_position,
4225 "initializers not allowed for function types at declator '%Y' (type '%T')",
4226 declaration->symbol, orig_type);
4228 declaration->init.initializer = initializer;
4232 /* parse rest of a declaration without any declarator */
4233 static void parse_anonymous_declaration_rest(
4234 const declaration_specifiers_t *specifiers,
4235 parsed_declaration_func finished_declaration)
4239 declaration_t *const declaration = allocate_declaration_zero();
4240 declaration->type = specifiers->type;
4241 declaration->declared_storage_class = specifiers->declared_storage_class;
4242 declaration->source_position = specifiers->source_position;
4243 declaration->modifiers = specifiers->modifiers;
4245 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4246 warningf(&declaration->source_position,
4247 "useless storage class in empty declaration");
4249 declaration->storage_class = STORAGE_CLASS_NONE;
4251 type_t *type = declaration->type;
4252 switch (type->kind) {
4253 case TYPE_COMPOUND_STRUCT:
4254 case TYPE_COMPOUND_UNION: {
4255 if (type->compound.declaration->symbol == NULL) {
4256 warningf(&declaration->source_position,
4257 "unnamed struct/union that defines no instances");
4266 warningf(&declaration->source_position, "empty declaration");
4270 finished_declaration(declaration);
4273 static void parse_declaration_rest(declaration_t *ndeclaration,
4274 const declaration_specifiers_t *specifiers,
4275 parsed_declaration_func finished_declaration)
4277 add_anchor_token(';');
4278 add_anchor_token('=');
4279 add_anchor_token(',');
4281 declaration_t *declaration = finished_declaration(ndeclaration);
4283 type_t *orig_type = declaration->type;
4284 type_t *type = skip_typeref(orig_type);
4286 if (type->kind != TYPE_FUNCTION &&
4287 declaration->is_inline &&
4288 is_type_valid(type)) {
4289 warningf(&declaration->source_position,
4290 "variable '%Y' declared 'inline'\n", declaration->symbol);
4293 if (token.type == '=') {
4294 parse_init_declarator_rest(declaration);
4297 if (token.type != ',')
4301 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4306 rem_anchor_token(';');
4307 rem_anchor_token('=');
4308 rem_anchor_token(',');
4311 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4313 symbol_t *symbol = declaration->symbol;
4314 if (symbol == NULL) {
4315 errorf(HERE, "anonymous declaration not valid as function parameter");
4318 namespace_t namespc = (namespace_t) declaration->namespc;
4319 if (namespc != NAMESPACE_NORMAL) {
4320 return record_declaration(declaration);
4323 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4324 if (previous_declaration == NULL ||
4325 previous_declaration->parent_scope != scope) {
4326 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4331 if (previous_declaration->type == NULL) {
4332 previous_declaration->type = declaration->type;
4333 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4334 previous_declaration->storage_class = declaration->storage_class;
4335 previous_declaration->parent_scope = scope;
4336 return previous_declaration;
4338 return record_declaration(declaration);
4342 static void parse_declaration(parsed_declaration_func finished_declaration)
4344 declaration_specifiers_t specifiers;
4345 memset(&specifiers, 0, sizeof(specifiers));
4346 parse_declaration_specifiers(&specifiers);
4348 if (token.type == ';') {
4349 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4351 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4352 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4356 static type_t *get_default_promoted_type(type_t *orig_type)
4358 type_t *result = orig_type;
4360 type_t *type = skip_typeref(orig_type);
4361 if (is_type_integer(type)) {
4362 result = promote_integer(type);
4363 } else if (type == type_float) {
4364 result = type_double;
4370 static void parse_kr_declaration_list(declaration_t *declaration)
4372 type_t *type = skip_typeref(declaration->type);
4373 if (!is_type_function(type))
4376 if (!type->function.kr_style_parameters)
4379 /* push function parameters */
4380 int top = environment_top();
4381 scope_t *last_scope = scope;
4382 set_scope(&declaration->scope);
4384 declaration_t *parameter = declaration->scope.declarations;
4385 for ( ; parameter != NULL; parameter = parameter->next) {
4386 assert(parameter->parent_scope == NULL);
4387 parameter->parent_scope = scope;
4388 environment_push(parameter);
4391 /* parse declaration list */
4392 while (is_declaration_specifier(&token, false)) {
4393 parse_declaration(finished_kr_declaration);
4396 /* pop function parameters */
4397 assert(scope == &declaration->scope);
4398 set_scope(last_scope);
4399 environment_pop_to(top);
4401 /* update function type */
4402 type_t *new_type = duplicate_type(type);
4404 function_parameter_t *parameters = NULL;
4405 function_parameter_t *last_parameter = NULL;
4407 declaration_t *parameter_declaration = declaration->scope.declarations;
4408 for( ; parameter_declaration != NULL;
4409 parameter_declaration = parameter_declaration->next) {
4410 type_t *parameter_type = parameter_declaration->type;
4411 if (parameter_type == NULL) {
4413 errorf(HERE, "no type specified for function parameter '%Y'",
4414 parameter_declaration->symbol);
4416 if (warning.implicit_int) {
4417 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4418 parameter_declaration->symbol);
4420 parameter_type = type_int;
4421 parameter_declaration->type = parameter_type;
4425 semantic_parameter(parameter_declaration);
4426 parameter_type = parameter_declaration->type;
4429 * we need the default promoted types for the function type
4431 parameter_type = get_default_promoted_type(parameter_type);
4433 function_parameter_t *function_parameter
4434 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4435 memset(function_parameter, 0, sizeof(function_parameter[0]));
4437 function_parameter->type = parameter_type;
4438 if (last_parameter != NULL) {
4439 last_parameter->next = function_parameter;
4441 parameters = function_parameter;
4443 last_parameter = function_parameter;
4446 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4448 new_type->function.parameters = parameters;
4449 new_type->function.unspecified_parameters = true;
4451 type = typehash_insert(new_type);
4452 if (type != new_type) {
4453 obstack_free(type_obst, new_type);
4456 declaration->type = type;
4459 static bool first_err = true;
4462 * When called with first_err set, prints the name of the current function,
4465 static void print_in_function(void) {
4468 diagnosticf("%s: In function '%Y':\n",
4469 current_function->source_position.input_name,
4470 current_function->symbol);
4475 * Check if all labels are defined in the current function.
4476 * Check if all labels are used in the current function.
4478 static void check_labels(void)
4480 for (const goto_statement_t *goto_statement = goto_first;
4481 goto_statement != NULL;
4482 goto_statement = goto_statement->next) {
4483 declaration_t *label = goto_statement->label;
4486 if (label->source_position.input_name == NULL) {
4487 print_in_function();
4488 errorf(&goto_statement->base.source_position,
4489 "label '%Y' used but not defined", label->symbol);
4492 goto_first = goto_last = NULL;
4494 if (warning.unused_label) {
4495 for (const label_statement_t *label_statement = label_first;
4496 label_statement != NULL;
4497 label_statement = label_statement->next) {
4498 const declaration_t *label = label_statement->label;
4500 if (! label->used) {
4501 print_in_function();
4502 warningf(&label_statement->base.source_position,
4503 "label '%Y' defined but not used", label->symbol);
4507 label_first = label_last = NULL;
4511 * Check declarations of current_function for unused entities.
4513 static void check_declarations(void)
4515 if (warning.unused_parameter) {
4516 const scope_t *scope = ¤t_function->scope;
4518 const declaration_t *parameter = scope->declarations;
4519 for (; parameter != NULL; parameter = parameter->next) {
4520 if (! parameter->used) {
4521 print_in_function();
4522 warningf(¶meter->source_position,
4523 "unused parameter '%Y'", parameter->symbol);
4527 if (warning.unused_variable) {
4531 static void parse_external_declaration(void)
4533 /* function-definitions and declarations both start with declaration
4535 declaration_specifiers_t specifiers;
4536 memset(&specifiers, 0, sizeof(specifiers));
4538 add_anchor_token(';');
4539 parse_declaration_specifiers(&specifiers);
4540 rem_anchor_token(';');
4542 /* must be a declaration */
4543 if (token.type == ';') {
4544 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4548 add_anchor_token(',');
4549 add_anchor_token('=');
4550 rem_anchor_token(';');
4552 /* declarator is common to both function-definitions and declarations */
4553 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4555 rem_anchor_token(',');
4556 rem_anchor_token('=');
4557 rem_anchor_token(';');
4559 /* must be a declaration */
4560 if (token.type == ',' || token.type == '=' || token.type == ';') {
4561 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4565 /* must be a function definition */
4566 parse_kr_declaration_list(ndeclaration);
4568 if (token.type != '{') {
4569 parse_error_expected("while parsing function definition", '{', NULL);
4570 eat_until_matching_token(';');
4574 type_t *type = ndeclaration->type;
4576 /* note that we don't skip typerefs: the standard doesn't allow them here
4577 * (so we can't use is_type_function here) */
4578 if (type->kind != TYPE_FUNCTION) {
4579 if (is_type_valid(type)) {
4580 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4581 type, ndeclaration->symbol);
4587 /* § 6.7.5.3 (14) a function definition with () means no
4588 * parameters (and not unspecified parameters) */
4589 if (type->function.unspecified_parameters
4590 && type->function.parameters == NULL
4591 && !type->function.kr_style_parameters) {
4592 type_t *duplicate = duplicate_type(type);
4593 duplicate->function.unspecified_parameters = false;
4595 type = typehash_insert(duplicate);
4596 if (type != duplicate) {
4597 obstack_free(type_obst, duplicate);
4599 ndeclaration->type = type;
4602 declaration_t *const declaration = record_function_definition(ndeclaration);
4603 if (ndeclaration != declaration) {
4604 declaration->scope = ndeclaration->scope;
4606 type = skip_typeref(declaration->type);
4608 /* push function parameters and switch scope */
4609 int top = environment_top();
4610 scope_t *last_scope = scope;
4611 set_scope(&declaration->scope);
4613 declaration_t *parameter = declaration->scope.declarations;
4614 for( ; parameter != NULL; parameter = parameter->next) {
4615 if (parameter->parent_scope == &ndeclaration->scope) {
4616 parameter->parent_scope = scope;
4618 assert(parameter->parent_scope == NULL
4619 || parameter->parent_scope == scope);
4620 parameter->parent_scope = scope;
4621 if (parameter->symbol == NULL) {
4622 errorf(&ndeclaration->source_position, "parameter name omitted");
4625 environment_push(parameter);
4628 if (declaration->init.statement != NULL) {
4629 parser_error_multiple_definition(declaration, HERE);
4631 goto end_of_parse_external_declaration;
4633 /* parse function body */
4634 int label_stack_top = label_top();
4635 declaration_t *old_current_function = current_function;
4636 current_function = declaration;
4638 declaration->init.statement = parse_compound_statement(false);
4641 check_declarations();
4643 assert(current_function == declaration);
4644 current_function = old_current_function;
4645 label_pop_to(label_stack_top);
4648 end_of_parse_external_declaration:
4649 assert(scope == &declaration->scope);
4650 set_scope(last_scope);
4651 environment_pop_to(top);
4654 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4655 source_position_t *source_position)
4657 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4659 type->bitfield.base_type = base_type;
4660 type->bitfield.size = size;
4665 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4668 declaration_t *iter = compound_declaration->scope.declarations;
4669 for( ; iter != NULL; iter = iter->next) {
4670 if (iter->namespc != NAMESPACE_NORMAL)
4673 if (iter->symbol == NULL) {
4674 type_t *type = skip_typeref(iter->type);
4675 if (is_type_compound(type)) {
4676 declaration_t *result
4677 = find_compound_entry(type->compound.declaration, symbol);
4684 if (iter->symbol == symbol) {
4692 static void parse_compound_declarators(declaration_t *struct_declaration,
4693 const declaration_specifiers_t *specifiers)
4695 declaration_t *last_declaration = struct_declaration->scope.declarations;
4696 if (last_declaration != NULL) {
4697 while(last_declaration->next != NULL) {
4698 last_declaration = last_declaration->next;
4703 declaration_t *declaration;
4705 if (token.type == ':') {
4706 source_position_t source_position = *HERE;
4709 type_t *base_type = specifiers->type;
4710 expression_t *size = parse_constant_expression();
4712 if (!is_type_integer(skip_typeref(base_type))) {
4713 errorf(HERE, "bitfield base type '%T' is not an integer type",
4717 type_t *type = make_bitfield_type(base_type, size, &source_position);
4719 declaration = allocate_declaration_zero();
4720 declaration->namespc = NAMESPACE_NORMAL;
4721 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4722 declaration->storage_class = STORAGE_CLASS_NONE;
4723 declaration->source_position = source_position;
4724 declaration->modifiers = specifiers->modifiers;
4725 declaration->type = type;
4727 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4729 type_t *orig_type = declaration->type;
4730 type_t *type = skip_typeref(orig_type);
4732 if (token.type == ':') {
4733 source_position_t source_position = *HERE;
4735 expression_t *size = parse_constant_expression();
4737 if (!is_type_integer(type)) {
4738 errorf(HERE, "bitfield base type '%T' is not an "
4739 "integer type", orig_type);
4742 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4743 declaration->type = bitfield_type;
4745 /* TODO we ignore arrays for now... what is missing is a check
4746 * that they're at the end of the struct */
4747 if (is_type_incomplete(type) && !is_type_array(type)) {
4749 "compound member '%Y' has incomplete type '%T'",
4750 declaration->symbol, orig_type);
4751 } else if (is_type_function(type)) {
4752 errorf(HERE, "compound member '%Y' must not have function "
4753 "type '%T'", declaration->symbol, orig_type);
4758 /* make sure we don't define a symbol multiple times */
4759 symbol_t *symbol = declaration->symbol;
4760 if (symbol != NULL) {
4761 declaration_t *prev_decl
4762 = find_compound_entry(struct_declaration, symbol);
4764 if (prev_decl != NULL) {
4765 assert(prev_decl->symbol == symbol);
4766 errorf(&declaration->source_position,
4767 "multiple declarations of symbol '%Y' (declared %P)",
4768 symbol, &prev_decl->source_position);
4772 /* append declaration */
4773 if (last_declaration != NULL) {
4774 last_declaration->next = declaration;
4776 struct_declaration->scope.declarations = declaration;
4778 last_declaration = declaration;
4780 if (token.type != ',')
4790 static void parse_compound_type_entries(declaration_t *compound_declaration)
4793 add_anchor_token('}');
4795 while(token.type != '}' && token.type != T_EOF) {
4796 declaration_specifiers_t specifiers;
4797 memset(&specifiers, 0, sizeof(specifiers));
4798 parse_declaration_specifiers(&specifiers);
4800 parse_compound_declarators(compound_declaration, &specifiers);
4802 rem_anchor_token('}');
4804 if (token.type == T_EOF) {
4805 errorf(HERE, "EOF while parsing struct");
4810 static type_t *parse_typename(void)
4812 declaration_specifiers_t specifiers;
4813 memset(&specifiers, 0, sizeof(specifiers));
4814 parse_declaration_specifiers(&specifiers);
4815 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4816 /* TODO: improve error message, user does probably not know what a
4817 * storage class is...
4819 errorf(HERE, "typename may not have a storage class");
4822 type_t *result = parse_abstract_declarator(specifiers.type);
4830 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4831 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4832 expression_t *left);
4834 typedef struct expression_parser_function_t expression_parser_function_t;
4835 struct expression_parser_function_t {
4836 unsigned precedence;
4837 parse_expression_function parser;
4838 unsigned infix_precedence;
4839 parse_expression_infix_function infix_parser;
4842 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4845 * Prints an error message if an expression was expected but not read
4847 static expression_t *expected_expression_error(void)
4849 /* skip the error message if the error token was read */
4850 if (token.type != T_ERROR) {
4851 errorf(HERE, "expected expression, got token '%K'", &token);
4855 return create_invalid_expression();
4859 * Parse a string constant.
4861 static expression_t *parse_string_const(void)
4864 if (token.type == T_STRING_LITERAL) {
4865 string_t res = token.v.string;
4867 while (token.type == T_STRING_LITERAL) {
4868 res = concat_strings(&res, &token.v.string);
4871 if (token.type != T_WIDE_STRING_LITERAL) {
4872 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4873 /* note: that we use type_char_ptr here, which is already the
4874 * automatic converted type. revert_automatic_type_conversion
4875 * will construct the array type */
4876 cnst->base.type = type_char_ptr;
4877 cnst->string.value = res;
4881 wres = concat_string_wide_string(&res, &token.v.wide_string);
4883 wres = token.v.wide_string;
4888 switch (token.type) {
4889 case T_WIDE_STRING_LITERAL:
4890 wres = concat_wide_strings(&wres, &token.v.wide_string);
4893 case T_STRING_LITERAL:
4894 wres = concat_wide_string_string(&wres, &token.v.string);
4898 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4899 cnst->base.type = type_wchar_t_ptr;
4900 cnst->wide_string.value = wres;
4909 * Parse an integer constant.
4911 static expression_t *parse_int_const(void)
4913 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4914 cnst->base.source_position = *HERE;
4915 cnst->base.type = token.datatype;
4916 cnst->conste.v.int_value = token.v.intvalue;
4924 * Parse a character constant.
4926 static expression_t *parse_character_constant(void)
4928 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4930 cnst->base.source_position = *HERE;
4931 cnst->base.type = token.datatype;
4932 cnst->conste.v.character = token.v.string;
4934 if (cnst->conste.v.character.size != 1) {
4935 if (warning.multichar && (c_mode & _GNUC)) {
4937 warningf(HERE, "multi-character character constant");
4939 errorf(HERE, "more than 1 characters in character constant");
4948 * Parse a wide character constant.
4950 static expression_t *parse_wide_character_constant(void)
4952 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4954 cnst->base.source_position = *HERE;
4955 cnst->base.type = token.datatype;
4956 cnst->conste.v.wide_character = token.v.wide_string;
4958 if (cnst->conste.v.wide_character.size != 1) {
4959 if (warning.multichar && (c_mode & _GNUC)) {
4961 warningf(HERE, "multi-character character constant");
4963 errorf(HERE, "more than 1 characters in character constant");
4972 * Parse a float constant.
4974 static expression_t *parse_float_const(void)
4976 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4977 cnst->base.type = token.datatype;
4978 cnst->conste.v.float_value = token.v.floatvalue;
4985 static declaration_t *create_implicit_function(symbol_t *symbol,
4986 const source_position_t *source_position)
4988 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4989 ntype->function.return_type = type_int;
4990 ntype->function.unspecified_parameters = true;
4992 type_t *type = typehash_insert(ntype);
4993 if (type != ntype) {
4997 declaration_t *const declaration = allocate_declaration_zero();
4998 declaration->storage_class = STORAGE_CLASS_EXTERN;
4999 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5000 declaration->type = type;
5001 declaration->symbol = symbol;
5002 declaration->source_position = *source_position;
5004 bool strict_prototypes_old = warning.strict_prototypes;
5005 warning.strict_prototypes = false;
5006 record_declaration(declaration);
5007 warning.strict_prototypes = strict_prototypes_old;
5013 * Creates a return_type (func)(argument_type) function type if not
5016 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5017 type_t *argument_type2)
5019 function_parameter_t *parameter2
5020 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5021 memset(parameter2, 0, sizeof(parameter2[0]));
5022 parameter2->type = argument_type2;
5024 function_parameter_t *parameter1
5025 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5026 memset(parameter1, 0, sizeof(parameter1[0]));
5027 parameter1->type = argument_type1;
5028 parameter1->next = parameter2;
5030 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5031 type->function.return_type = return_type;
5032 type->function.parameters = parameter1;
5034 type_t *result = typehash_insert(type);
5035 if (result != type) {
5043 * Creates a return_type (func)(argument_type) function type if not
5046 * @param return_type the return type
5047 * @param argument_type the argument type
5049 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5051 function_parameter_t *parameter
5052 = obstack_alloc(type_obst, sizeof(parameter[0]));
5053 memset(parameter, 0, sizeof(parameter[0]));
5054 parameter->type = argument_type;
5056 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5057 type->function.return_type = return_type;
5058 type->function.parameters = parameter;
5060 type_t *result = typehash_insert(type);
5061 if (result != type) {
5068 static type_t *make_function_0_type(type_t *return_type)
5070 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5071 type->function.return_type = return_type;
5072 type->function.parameters = NULL;
5074 type_t *result = typehash_insert(type);
5075 if (result != type) {
5083 * Creates a function type for some function like builtins.
5085 * @param symbol the symbol describing the builtin
5087 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5089 switch(symbol->ID) {
5090 case T___builtin_alloca:
5091 return make_function_1_type(type_void_ptr, type_size_t);
5092 case T___builtin_huge_val:
5093 return make_function_0_type(type_double);
5094 case T___builtin_nan:
5095 return make_function_1_type(type_double, type_char_ptr);
5096 case T___builtin_nanf:
5097 return make_function_1_type(type_float, type_char_ptr);
5098 case T___builtin_nand:
5099 return make_function_1_type(type_long_double, type_char_ptr);
5100 case T___builtin_va_end:
5101 return make_function_1_type(type_void, type_valist);
5102 case T___builtin_expect:
5103 return make_function_2_type(type_long, type_long, type_long);
5105 internal_errorf(HERE, "not implemented builtin symbol found");
5110 * Performs automatic type cast as described in § 6.3.2.1.
5112 * @param orig_type the original type
5114 static type_t *automatic_type_conversion(type_t *orig_type)
5116 type_t *type = skip_typeref(orig_type);
5117 if (is_type_array(type)) {
5118 array_type_t *array_type = &type->array;
5119 type_t *element_type = array_type->element_type;
5120 unsigned qualifiers = array_type->base.qualifiers;
5122 return make_pointer_type(element_type, qualifiers);
5125 if (is_type_function(type)) {
5126 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5133 * reverts the automatic casts of array to pointer types and function
5134 * to function-pointer types as defined § 6.3.2.1
5136 type_t *revert_automatic_type_conversion(const expression_t *expression)
5138 switch (expression->kind) {
5139 case EXPR_REFERENCE: return expression->reference.declaration->type;
5140 case EXPR_SELECT: return expression->select.compound_entry->type;
5142 case EXPR_UNARY_DEREFERENCE: {
5143 const expression_t *const value = expression->unary.value;
5144 type_t *const type = skip_typeref(value->base.type);
5145 assert(is_type_pointer(type));
5146 return type->pointer.points_to;
5149 case EXPR_BUILTIN_SYMBOL:
5150 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5152 case EXPR_ARRAY_ACCESS: {
5153 const expression_t *array_ref = expression->array_access.array_ref;
5154 type_t *type_left = skip_typeref(array_ref->base.type);
5155 if (!is_type_valid(type_left))
5157 assert(is_type_pointer(type_left));
5158 return type_left->pointer.points_to;
5161 case EXPR_STRING_LITERAL: {
5162 size_t size = expression->string.value.size;
5163 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5166 case EXPR_WIDE_STRING_LITERAL: {
5167 size_t size = expression->wide_string.value.size;
5168 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5171 case EXPR_COMPOUND_LITERAL:
5172 return expression->compound_literal.type;
5177 return expression->base.type;
5180 static expression_t *parse_reference(void)
5182 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5184 reference_expression_t *ref = &expression->reference;
5185 symbol_t *const symbol = token.v.symbol;
5187 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5189 source_position_t source_position = token.source_position;
5192 if (declaration == NULL) {
5193 if (! strict_mode && token.type == '(') {
5194 /* an implicitly defined function */
5195 if (warning.implicit_function_declaration) {
5196 warningf(HERE, "implicit declaration of function '%Y'",
5200 declaration = create_implicit_function(symbol,
5203 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5204 return create_invalid_expression();
5208 type_t *type = declaration->type;
5210 /* we always do the auto-type conversions; the & and sizeof parser contains
5211 * code to revert this! */
5212 type = automatic_type_conversion(type);
5214 ref->declaration = declaration;
5215 ref->base.type = type;
5217 /* this declaration is used */
5218 declaration->used = true;
5220 /* check for deprecated functions */
5221 if (declaration->deprecated != 0) {
5222 const char *prefix = "";
5223 if (is_type_function(declaration->type))
5224 prefix = "function ";
5226 if (declaration->deprecated_string != NULL) {
5227 warningf(&source_position,
5228 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5229 declaration->deprecated_string);
5231 warningf(&source_position,
5232 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5239 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5243 /* TODO check if explicit cast is allowed and issue warnings/errors */
5246 static expression_t *parse_compound_literal(type_t *type)
5248 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5250 parse_initializer_env_t env;
5252 env.declaration = NULL;
5253 env.must_be_constant = false;
5254 initializer_t *initializer = parse_initializer(&env);
5257 expression->compound_literal.initializer = initializer;
5258 expression->compound_literal.type = type;
5259 expression->base.type = automatic_type_conversion(type);
5265 * Parse a cast expression.
5267 static expression_t *parse_cast(void)
5269 source_position_t source_position = token.source_position;
5271 type_t *type = parse_typename();
5273 /* matching add_anchor_token() is at call site */
5274 rem_anchor_token(')');
5277 if (token.type == '{') {
5278 return parse_compound_literal(type);
5281 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5282 cast->base.source_position = source_position;
5284 expression_t *value = parse_sub_expression(20);
5286 check_cast_allowed(value, type);
5288 cast->base.type = type;
5289 cast->unary.value = value;
5293 return create_invalid_expression();
5297 * Parse a statement expression.
5299 static expression_t *parse_statement_expression(void)
5301 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5303 statement_t *statement = parse_compound_statement(true);
5304 expression->statement.statement = statement;
5305 expression->base.source_position = statement->base.source_position;
5307 /* find last statement and use its type */
5308 type_t *type = type_void;
5309 const statement_t *stmt = statement->compound.statements;
5311 while (stmt->base.next != NULL)
5312 stmt = stmt->base.next;
5314 if (stmt->kind == STATEMENT_EXPRESSION) {
5315 type = stmt->expression.expression->base.type;
5318 warningf(&expression->base.source_position, "empty statement expression ({})");
5320 expression->base.type = type;
5326 return create_invalid_expression();
5330 * Parse a braced expression.
5332 static expression_t *parse_brace_expression(void)
5335 add_anchor_token(')');
5337 switch(token.type) {
5339 /* gcc extension: a statement expression */
5340 return parse_statement_expression();
5344 return parse_cast();
5346 if (is_typedef_symbol(token.v.symbol)) {
5347 return parse_cast();
5351 expression_t *result = parse_expression();
5352 rem_anchor_token(')');
5357 return create_invalid_expression();
5360 static expression_t *parse_function_keyword(void)
5365 if (current_function == NULL) {
5366 errorf(HERE, "'__func__' used outside of a function");
5369 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5370 expression->base.type = type_char_ptr;
5371 expression->funcname.kind = FUNCNAME_FUNCTION;
5376 static expression_t *parse_pretty_function_keyword(void)
5378 eat(T___PRETTY_FUNCTION__);
5380 if (current_function == NULL) {
5381 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5384 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5385 expression->base.type = type_char_ptr;
5386 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5391 static expression_t *parse_funcsig_keyword(void)
5395 if (current_function == NULL) {
5396 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5399 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5400 expression->base.type = type_char_ptr;
5401 expression->funcname.kind = FUNCNAME_FUNCSIG;
5406 static expression_t *parse_funcdname_keyword(void)
5408 eat(T___FUNCDNAME__);
5410 if (current_function == NULL) {
5411 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5414 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5415 expression->base.type = type_char_ptr;
5416 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5421 static designator_t *parse_designator(void)
5423 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5424 result->source_position = *HERE;
5426 if (token.type != T_IDENTIFIER) {
5427 parse_error_expected("while parsing member designator",
5428 T_IDENTIFIER, NULL);
5431 result->symbol = token.v.symbol;
5434 designator_t *last_designator = result;
5436 if (token.type == '.') {
5438 if (token.type != T_IDENTIFIER) {
5439 parse_error_expected("while parsing member designator",
5440 T_IDENTIFIER, NULL);
5443 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5444 designator->source_position = *HERE;
5445 designator->symbol = token.v.symbol;
5448 last_designator->next = designator;
5449 last_designator = designator;
5452 if (token.type == '[') {
5454 add_anchor_token(']');
5455 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5456 designator->source_position = *HERE;
5457 designator->array_index = parse_expression();
5458 rem_anchor_token(']');
5460 if (designator->array_index == NULL) {
5464 last_designator->next = designator;
5465 last_designator = designator;
5477 * Parse the __builtin_offsetof() expression.
5479 static expression_t *parse_offsetof(void)
5481 eat(T___builtin_offsetof);
5483 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5484 expression->base.type = type_size_t;
5487 add_anchor_token(',');
5488 type_t *type = parse_typename();
5489 rem_anchor_token(',');
5491 add_anchor_token(')');
5492 designator_t *designator = parse_designator();
5493 rem_anchor_token(')');
5496 expression->offsetofe.type = type;
5497 expression->offsetofe.designator = designator;
5500 memset(&path, 0, sizeof(path));
5501 path.top_type = type;
5502 path.path = NEW_ARR_F(type_path_entry_t, 0);
5504 descend_into_subtype(&path);
5506 if (!walk_designator(&path, designator, true)) {
5507 return create_invalid_expression();
5510 DEL_ARR_F(path.path);
5514 return create_invalid_expression();
5518 * Parses a _builtin_va_start() expression.
5520 static expression_t *parse_va_start(void)
5522 eat(T___builtin_va_start);
5524 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5527 add_anchor_token(',');
5528 expression->va_starte.ap = parse_assignment_expression();
5529 rem_anchor_token(',');
5531 expression_t *const expr = parse_assignment_expression();
5532 if (expr->kind == EXPR_REFERENCE) {
5533 declaration_t *const decl = expr->reference.declaration;
5535 return create_invalid_expression();
5536 if (decl->parent_scope == ¤t_function->scope &&
5537 decl->next == NULL) {
5538 expression->va_starte.parameter = decl;
5543 errorf(&expr->base.source_position,
5544 "second argument of 'va_start' must be last parameter of the current function");
5546 return create_invalid_expression();
5550 * Parses a _builtin_va_arg() expression.
5552 static expression_t *parse_va_arg(void)
5554 eat(T___builtin_va_arg);
5556 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5559 expression->va_arge.ap = parse_assignment_expression();
5561 expression->base.type = parse_typename();
5566 return create_invalid_expression();
5569 static expression_t *parse_builtin_symbol(void)
5571 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5573 symbol_t *symbol = token.v.symbol;
5575 expression->builtin_symbol.symbol = symbol;
5578 type_t *type = get_builtin_symbol_type(symbol);
5579 type = automatic_type_conversion(type);
5581 expression->base.type = type;
5586 * Parses a __builtin_constant() expression.
5588 static expression_t *parse_builtin_constant(void)
5590 eat(T___builtin_constant_p);
5592 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5595 add_anchor_token(')');
5596 expression->builtin_constant.value = parse_assignment_expression();
5597 rem_anchor_token(')');
5599 expression->base.type = type_int;
5603 return create_invalid_expression();
5607 * Parses a __builtin_prefetch() expression.
5609 static expression_t *parse_builtin_prefetch(void)
5611 eat(T___builtin_prefetch);
5613 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5616 add_anchor_token(')');
5617 expression->builtin_prefetch.adr = parse_assignment_expression();
5618 if (token.type == ',') {
5620 expression->builtin_prefetch.rw = parse_assignment_expression();
5622 if (token.type == ',') {
5624 expression->builtin_prefetch.locality = parse_assignment_expression();
5626 rem_anchor_token(')');
5628 expression->base.type = type_void;
5632 return create_invalid_expression();
5636 * Parses a __builtin_is_*() compare expression.
5638 static expression_t *parse_compare_builtin(void)
5640 expression_t *expression;
5642 switch(token.type) {
5643 case T___builtin_isgreater:
5644 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5646 case T___builtin_isgreaterequal:
5647 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5649 case T___builtin_isless:
5650 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5652 case T___builtin_islessequal:
5653 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5655 case T___builtin_islessgreater:
5656 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5658 case T___builtin_isunordered:
5659 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5662 internal_errorf(HERE, "invalid compare builtin found");
5665 expression->base.source_position = *HERE;
5669 expression->binary.left = parse_assignment_expression();
5671 expression->binary.right = parse_assignment_expression();
5674 type_t *const orig_type_left = expression->binary.left->base.type;
5675 type_t *const orig_type_right = expression->binary.right->base.type;
5677 type_t *const type_left = skip_typeref(orig_type_left);
5678 type_t *const type_right = skip_typeref(orig_type_right);
5679 if (!is_type_float(type_left) && !is_type_float(type_right)) {
5680 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5681 type_error_incompatible("invalid operands in comparison",
5682 &expression->base.source_position, orig_type_left, orig_type_right);
5685 semantic_comparison(&expression->binary);
5690 return create_invalid_expression();
5695 * Parses a __builtin_expect() expression.
5697 static expression_t *parse_builtin_expect(void)
5699 eat(T___builtin_expect);
5701 expression_t *expression
5702 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5705 expression->binary.left = parse_assignment_expression();
5707 expression->binary.right = parse_constant_expression();
5710 expression->base.type = expression->binary.left->base.type;
5714 return create_invalid_expression();
5719 * Parses a MS assume() expression.
5721 static expression_t *parse_assume(void) {
5724 expression_t *expression
5725 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5728 add_anchor_token(')');
5729 expression->unary.value = parse_assignment_expression();
5730 rem_anchor_token(')');
5733 expression->base.type = type_void;
5736 return create_invalid_expression();
5740 * Parse a microsoft __noop expression.
5742 static expression_t *parse_noop_expression(void) {
5743 source_position_t source_position = *HERE;
5746 if (token.type == '(') {
5747 /* parse arguments */
5749 add_anchor_token(')');
5750 add_anchor_token(',');
5752 if (token.type != ')') {
5754 (void)parse_assignment_expression();
5755 if (token.type != ',')
5761 rem_anchor_token(',');
5762 rem_anchor_token(')');
5765 /* the result is a (int)0 */
5766 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5767 cnst->base.source_position = source_position;
5768 cnst->base.type = type_int;
5769 cnst->conste.v.int_value = 0;
5770 cnst->conste.is_ms_noop = true;
5775 return create_invalid_expression();
5779 * Parses a primary expression.
5781 static expression_t *parse_primary_expression(void)
5783 switch (token.type) {
5784 case T_INTEGER: return parse_int_const();
5785 case T_CHARACTER_CONSTANT: return parse_character_constant();
5786 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5787 case T_FLOATINGPOINT: return parse_float_const();
5788 case T_STRING_LITERAL:
5789 case T_WIDE_STRING_LITERAL: return parse_string_const();
5790 case T_IDENTIFIER: return parse_reference();
5791 case T___FUNCTION__:
5792 case T___func__: return parse_function_keyword();
5793 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5794 case T___FUNCSIG__: return parse_funcsig_keyword();
5795 case T___FUNCDNAME__: return parse_funcdname_keyword();
5796 case T___builtin_offsetof: return parse_offsetof();
5797 case T___builtin_va_start: return parse_va_start();
5798 case T___builtin_va_arg: return parse_va_arg();
5799 case T___builtin_expect:
5800 case T___builtin_alloca:
5801 case T___builtin_nan:
5802 case T___builtin_nand:
5803 case T___builtin_nanf:
5804 case T___builtin_huge_val:
5805 case T___builtin_va_end: return parse_builtin_symbol();
5806 case T___builtin_isgreater:
5807 case T___builtin_isgreaterequal:
5808 case T___builtin_isless:
5809 case T___builtin_islessequal:
5810 case T___builtin_islessgreater:
5811 case T___builtin_isunordered: return parse_compare_builtin();
5812 case T___builtin_constant_p: return parse_builtin_constant();
5813 case T___builtin_prefetch: return parse_builtin_prefetch();
5814 case T__assume: return parse_assume();
5816 case '(': return parse_brace_expression();
5817 case T___noop: return parse_noop_expression();
5820 errorf(HERE, "unexpected token %K, expected an expression", &token);
5821 return create_invalid_expression();
5825 * Check if the expression has the character type and issue a warning then.
5827 static void check_for_char_index_type(const expression_t *expression) {
5828 type_t *const type = expression->base.type;
5829 const type_t *const base_type = skip_typeref(type);
5831 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5832 warning.char_subscripts) {
5833 warningf(&expression->base.source_position,
5834 "array subscript has type '%T'", type);
5838 static expression_t *parse_array_expression(unsigned precedence,
5844 add_anchor_token(']');
5846 expression_t *inside = parse_expression();
5848 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5850 array_access_expression_t *array_access = &expression->array_access;
5852 type_t *const orig_type_left = left->base.type;
5853 type_t *const orig_type_inside = inside->base.type;
5855 type_t *const type_left = skip_typeref(orig_type_left);
5856 type_t *const type_inside = skip_typeref(orig_type_inside);
5858 type_t *return_type;
5859 if (is_type_pointer(type_left)) {
5860 return_type = type_left->pointer.points_to;
5861 array_access->array_ref = left;
5862 array_access->index = inside;
5863 check_for_char_index_type(inside);
5864 } else if (is_type_pointer(type_inside)) {
5865 return_type = type_inside->pointer.points_to;
5866 array_access->array_ref = inside;
5867 array_access->index = left;
5868 array_access->flipped = true;
5869 check_for_char_index_type(left);
5871 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5873 "array access on object with non-pointer types '%T', '%T'",
5874 orig_type_left, orig_type_inside);
5876 return_type = type_error_type;
5877 array_access->array_ref = create_invalid_expression();
5880 rem_anchor_token(']');
5881 if (token.type != ']') {
5882 parse_error_expected("Problem while parsing array access", ']', NULL);
5887 return_type = automatic_type_conversion(return_type);
5888 expression->base.type = return_type;
5893 static expression_t *parse_typeprop(expression_kind_t const kind,
5894 source_position_t const pos,
5895 unsigned const precedence)
5897 expression_t *tp_expression = allocate_expression_zero(kind);
5898 tp_expression->base.type = type_size_t;
5899 tp_expression->base.source_position = pos;
5901 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5903 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5905 add_anchor_token(')');
5906 type_t* const orig_type = parse_typename();
5907 tp_expression->typeprop.type = orig_type;
5909 type_t const* const type = skip_typeref(orig_type);
5910 char const* const wrong_type =
5911 is_type_incomplete(type) ? "incomplete" :
5912 type->kind == TYPE_FUNCTION ? "function designator" :
5913 type->kind == TYPE_BITFIELD ? "bitfield" :
5915 if (wrong_type != NULL) {
5916 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5917 what, wrong_type, type);
5920 rem_anchor_token(')');
5923 expression_t *expression = parse_sub_expression(precedence);
5925 type_t* const orig_type = revert_automatic_type_conversion(expression);
5926 expression->base.type = orig_type;
5928 type_t const* const type = skip_typeref(orig_type);
5929 char const* const wrong_type =
5930 is_type_incomplete(type) ? "incomplete" :
5931 type->kind == TYPE_FUNCTION ? "function designator" :
5932 type->kind == TYPE_BITFIELD ? "bitfield" :
5934 if (wrong_type != NULL) {
5935 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5938 tp_expression->typeprop.type = expression->base.type;
5939 tp_expression->typeprop.tp_expression = expression;
5942 return tp_expression;
5944 return create_invalid_expression();
5947 static expression_t *parse_sizeof(unsigned precedence)
5949 source_position_t pos = *HERE;
5951 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5954 static expression_t *parse_alignof(unsigned precedence)
5956 source_position_t pos = *HERE;
5958 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5961 static expression_t *parse_select_expression(unsigned precedence,
5962 expression_t *compound)
5965 assert(token.type == '.' || token.type == T_MINUSGREATER);
5967 bool is_pointer = (token.type == T_MINUSGREATER);
5970 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5971 select->select.compound = compound;
5973 if (token.type != T_IDENTIFIER) {
5974 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5977 symbol_t *symbol = token.v.symbol;
5978 select->select.symbol = symbol;
5981 type_t *const orig_type = compound->base.type;
5982 type_t *const type = skip_typeref(orig_type);
5984 type_t *type_left = type;
5986 if (!is_type_pointer(type)) {
5987 if (is_type_valid(type)) {
5988 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5990 return create_invalid_expression();
5992 type_left = type->pointer.points_to;
5994 type_left = skip_typeref(type_left);
5996 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5997 type_left->kind != TYPE_COMPOUND_UNION) {
5998 if (is_type_valid(type_left)) {
5999 errorf(HERE, "request for member '%Y' in something not a struct or "
6000 "union, but '%T'", symbol, type_left);
6002 return create_invalid_expression();
6005 declaration_t *const declaration = type_left->compound.declaration;
6007 if (!declaration->init.complete) {
6008 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6010 return create_invalid_expression();
6013 declaration_t *iter = find_compound_entry(declaration, symbol);
6015 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6016 return create_invalid_expression();
6019 /* we always do the auto-type conversions; the & and sizeof parser contains
6020 * code to revert this! */
6021 type_t *expression_type = automatic_type_conversion(iter->type);
6023 select->select.compound_entry = iter;
6024 select->base.type = expression_type;
6026 type_t *skipped = skip_typeref(iter->type);
6027 if (skipped->kind == TYPE_BITFIELD) {
6028 select->base.type = skipped->bitfield.base_type;
6034 static void check_call_argument(const function_parameter_t *parameter,
6035 call_argument_t *argument)
6037 type_t *expected_type = parameter->type;
6038 type_t *expected_type_skip = skip_typeref(expected_type);
6039 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6040 expression_t *arg_expr = argument->expression;
6042 /* handle transparent union gnu extension */
6043 if (is_type_union(expected_type_skip)
6044 && (expected_type_skip->base.modifiers
6045 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6046 declaration_t *union_decl = expected_type_skip->compound.declaration;
6048 declaration_t *declaration = union_decl->scope.declarations;
6049 type_t *best_type = NULL;
6050 for ( ; declaration != NULL; declaration = declaration->next) {
6051 type_t *decl_type = declaration->type;
6052 error = semantic_assign(decl_type, arg_expr);
6053 if (error == ASSIGN_ERROR_INCOMPATIBLE
6054 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6057 if (error == ASSIGN_SUCCESS) {
6058 best_type = decl_type;
6059 } else if (best_type == NULL) {
6060 best_type = decl_type;
6064 if (best_type != NULL) {
6065 expected_type = best_type;
6069 error = semantic_assign(expected_type, arg_expr);
6070 argument->expression = create_implicit_cast(argument->expression,
6073 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6074 report_assign_error(error, expected_type, arg_expr, "function call",
6075 &arg_expr->base.source_position);
6079 * Parse a call expression, ie. expression '( ... )'.
6081 * @param expression the function address
6083 static expression_t *parse_call_expression(unsigned precedence,
6084 expression_t *expression)
6087 expression_t *result = allocate_expression_zero(EXPR_CALL);
6088 result->base.source_position = expression->base.source_position;
6090 call_expression_t *call = &result->call;
6091 call->function = expression;
6093 type_t *const orig_type = expression->base.type;
6094 type_t *const type = skip_typeref(orig_type);
6096 function_type_t *function_type = NULL;
6097 if (is_type_pointer(type)) {
6098 type_t *const to_type = skip_typeref(type->pointer.points_to);
6100 if (is_type_function(to_type)) {
6101 function_type = &to_type->function;
6102 call->base.type = function_type->return_type;
6106 if (function_type == NULL && is_type_valid(type)) {
6107 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6110 /* parse arguments */
6112 add_anchor_token(')');
6113 add_anchor_token(',');
6115 if (token.type != ')') {
6116 call_argument_t *last_argument = NULL;
6119 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6121 argument->expression = parse_assignment_expression();
6122 if (last_argument == NULL) {
6123 call->arguments = argument;
6125 last_argument->next = argument;
6127 last_argument = argument;
6129 if (token.type != ',')
6134 rem_anchor_token(',');
6135 rem_anchor_token(')');
6138 if (function_type == NULL)
6141 function_parameter_t *parameter = function_type->parameters;
6142 call_argument_t *argument = call->arguments;
6143 if (!function_type->unspecified_parameters) {
6144 for( ; parameter != NULL && argument != NULL;
6145 parameter = parameter->next, argument = argument->next) {
6146 check_call_argument(parameter, argument);
6149 if (parameter != NULL) {
6150 errorf(HERE, "too few arguments to function '%E'", expression);
6151 } else if (argument != NULL && !function_type->variadic) {
6152 errorf(HERE, "too many arguments to function '%E'", expression);
6156 /* do default promotion */
6157 for( ; argument != NULL; argument = argument->next) {
6158 type_t *type = argument->expression->base.type;
6160 type = get_default_promoted_type(type);
6162 argument->expression
6163 = create_implicit_cast(argument->expression, type);
6166 check_format(&result->call);
6170 return create_invalid_expression();
6173 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6175 static bool same_compound_type(const type_t *type1, const type_t *type2)
6178 is_type_compound(type1) &&
6179 type1->kind == type2->kind &&
6180 type1->compound.declaration == type2->compound.declaration;
6184 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6186 * @param expression the conditional expression
6188 static expression_t *parse_conditional_expression(unsigned precedence,
6189 expression_t *expression)
6192 add_anchor_token(':');
6194 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6196 conditional_expression_t *conditional = &result->conditional;
6197 conditional->condition = expression;
6200 type_t *const condition_type_orig = expression->base.type;
6201 type_t *const condition_type = skip_typeref(condition_type_orig);
6202 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6203 type_error("expected a scalar type in conditional condition",
6204 &expression->base.source_position, condition_type_orig);
6207 expression_t *true_expression = parse_expression();
6208 rem_anchor_token(':');
6210 expression_t *false_expression = parse_sub_expression(precedence);
6212 type_t *const orig_true_type = true_expression->base.type;
6213 type_t *const orig_false_type = false_expression->base.type;
6214 type_t *const true_type = skip_typeref(orig_true_type);
6215 type_t *const false_type = skip_typeref(orig_false_type);
6218 type_t *result_type;
6219 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6220 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6221 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6222 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6223 warningf(&expression->base.source_position,
6224 "ISO C forbids conditional expression with only one void side");
6226 result_type = type_void;
6227 } else if (is_type_arithmetic(true_type)
6228 && is_type_arithmetic(false_type)) {
6229 result_type = semantic_arithmetic(true_type, false_type);
6231 true_expression = create_implicit_cast(true_expression, result_type);
6232 false_expression = create_implicit_cast(false_expression, result_type);
6234 conditional->true_expression = true_expression;
6235 conditional->false_expression = false_expression;
6236 conditional->base.type = result_type;
6237 } else if (same_compound_type(true_type, false_type)) {
6238 /* just take 1 of the 2 types */
6239 result_type = true_type;
6240 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6241 type_t *pointer_type;
6243 expression_t *other_expression;
6244 if (is_type_pointer(true_type) &&
6245 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6246 pointer_type = true_type;
6247 other_type = false_type;
6248 other_expression = false_expression;
6250 pointer_type = false_type;
6251 other_type = true_type;
6252 other_expression = true_expression;
6255 if (is_null_pointer_constant(other_expression)) {
6256 result_type = pointer_type;
6257 } else if (is_type_pointer(other_type)) {
6258 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6259 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6262 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6263 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6265 } else if (types_compatible(get_unqualified_type(to1),
6266 get_unqualified_type(to2))) {
6269 warningf(&expression->base.source_position,
6270 "pointer types '%T' and '%T' in conditional expression are incompatible",
6271 true_type, false_type);
6275 type_t *const copy = duplicate_type(to);
6276 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6278 type_t *const type = typehash_insert(copy);
6282 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6283 } else if (is_type_integer(other_type)) {
6284 warningf(&expression->base.source_position,
6285 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6286 result_type = pointer_type;
6288 type_error_incompatible("while parsing conditional",
6289 &expression->base.source_position, true_type, false_type);
6290 result_type = type_error_type;
6293 /* TODO: one pointer to void*, other some pointer */
6295 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6296 type_error_incompatible("while parsing conditional",
6297 &expression->base.source_position, true_type,
6300 result_type = type_error_type;
6303 conditional->true_expression
6304 = create_implicit_cast(true_expression, result_type);
6305 conditional->false_expression
6306 = create_implicit_cast(false_expression, result_type);
6307 conditional->base.type = result_type;
6310 return create_invalid_expression();
6314 * Parse an extension expression.
6316 static expression_t *parse_extension(unsigned precedence)
6318 eat(T___extension__);
6320 /* TODO enable extensions */
6321 expression_t *expression = parse_sub_expression(precedence);
6322 /* TODO disable extensions */
6327 * Parse a __builtin_classify_type() expression.
6329 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6331 eat(T___builtin_classify_type);
6333 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6334 result->base.type = type_int;
6337 add_anchor_token(')');
6338 expression_t *expression = parse_sub_expression(precedence);
6339 rem_anchor_token(')');
6341 result->classify_type.type_expression = expression;
6345 return create_invalid_expression();
6348 static void check_pointer_arithmetic(const source_position_t *source_position,
6349 type_t *pointer_type,
6350 type_t *orig_pointer_type)
6352 type_t *points_to = pointer_type->pointer.points_to;
6353 points_to = skip_typeref(points_to);
6355 if (is_type_incomplete(points_to) &&
6357 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6358 errorf(source_position,
6359 "arithmetic with pointer to incomplete type '%T' not allowed",
6361 } else if (is_type_function(points_to)) {
6362 errorf(source_position,
6363 "arithmetic with pointer to function type '%T' not allowed",
6368 static void semantic_incdec(unary_expression_t *expression)
6370 type_t *const orig_type = expression->value->base.type;
6371 type_t *const type = skip_typeref(orig_type);
6372 if (is_type_pointer(type)) {
6373 check_pointer_arithmetic(&expression->base.source_position,
6375 } else if (!is_type_real(type) && is_type_valid(type)) {
6376 /* TODO: improve error message */
6377 errorf(HERE, "operation needs an arithmetic or pointer type");
6379 expression->base.type = orig_type;
6382 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6384 type_t *const orig_type = expression->value->base.type;
6385 type_t *const type = skip_typeref(orig_type);
6386 if (!is_type_arithmetic(type)) {
6387 if (is_type_valid(type)) {
6388 /* TODO: improve error message */
6389 errorf(HERE, "operation needs an arithmetic type");
6394 expression->base.type = orig_type;
6397 static void semantic_unexpr_scalar(unary_expression_t *expression)
6399 type_t *const orig_type = expression->value->base.type;
6400 type_t *const type = skip_typeref(orig_type);
6401 if (!is_type_scalar(type)) {
6402 if (is_type_valid(type)) {
6403 errorf(HERE, "operand of ! must be of scalar type");
6408 expression->base.type = orig_type;
6411 static void semantic_unexpr_integer(unary_expression_t *expression)
6413 type_t *const orig_type = expression->value->base.type;
6414 type_t *const type = skip_typeref(orig_type);
6415 if (!is_type_integer(type)) {
6416 if (is_type_valid(type)) {
6417 errorf(HERE, "operand of ~ must be of integer type");
6422 expression->base.type = orig_type;
6425 static void semantic_dereference(unary_expression_t *expression)
6427 type_t *const orig_type = expression->value->base.type;
6428 type_t *const type = skip_typeref(orig_type);
6429 if (!is_type_pointer(type)) {
6430 if (is_type_valid(type)) {
6431 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6436 type_t *result_type = type->pointer.points_to;
6437 result_type = automatic_type_conversion(result_type);
6438 expression->base.type = result_type;
6441 static void set_address_taken(expression_t *expression, bool may_be_register)
6443 if (expression->kind != EXPR_REFERENCE)
6446 declaration_t *const declaration = expression->reference.declaration;
6447 /* happens for parse errors */
6448 if (declaration == NULL)
6451 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6452 errorf(&expression->base.source_position,
6453 "address of register variable '%Y' requested",
6454 declaration->symbol);
6456 declaration->address_taken = 1;
6461 * Check the semantic of the address taken expression.
6463 static void semantic_take_addr(unary_expression_t *expression)
6465 expression_t *value = expression->value;
6466 value->base.type = revert_automatic_type_conversion(value);
6468 type_t *orig_type = value->base.type;
6469 if (!is_type_valid(orig_type))
6472 set_address_taken(value, false);
6474 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6477 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6478 static expression_t *parse_##unexpression_type(unsigned precedence) \
6482 expression_t *unary_expression \
6483 = allocate_expression_zero(unexpression_type); \
6484 unary_expression->base.source_position = *HERE; \
6485 unary_expression->unary.value = parse_sub_expression(precedence); \
6487 sfunc(&unary_expression->unary); \
6489 return unary_expression; \
6492 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6493 semantic_unexpr_arithmetic)
6494 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6495 semantic_unexpr_arithmetic)
6496 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6497 semantic_unexpr_scalar)
6498 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6499 semantic_dereference)
6500 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6502 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6503 semantic_unexpr_integer)
6504 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6506 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6509 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6511 static expression_t *parse_##unexpression_type(unsigned precedence, \
6512 expression_t *left) \
6514 (void) precedence; \
6517 expression_t *unary_expression \
6518 = allocate_expression_zero(unexpression_type); \
6519 unary_expression->unary.value = left; \
6521 sfunc(&unary_expression->unary); \
6523 return unary_expression; \
6526 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6527 EXPR_UNARY_POSTFIX_INCREMENT,
6529 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6530 EXPR_UNARY_POSTFIX_DECREMENT,
6533 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6535 /* TODO: handle complex + imaginary types */
6537 /* § 6.3.1.8 Usual arithmetic conversions */
6538 if (type_left == type_long_double || type_right == type_long_double) {
6539 return type_long_double;
6540 } else if (type_left == type_double || type_right == type_double) {
6542 } else if (type_left == type_float || type_right == type_float) {
6546 type_right = promote_integer(type_right);
6547 type_left = promote_integer(type_left);
6549 if (type_left == type_right)
6552 bool signed_left = is_type_signed(type_left);
6553 bool signed_right = is_type_signed(type_right);
6554 int rank_left = get_rank(type_left);
6555 int rank_right = get_rank(type_right);
6556 if (rank_left < rank_right) {
6557 if (signed_left == signed_right || !signed_right) {
6563 if (signed_left == signed_right || !signed_left) {
6572 * Check the semantic restrictions for a binary expression.
6574 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6576 expression_t *const left = expression->left;
6577 expression_t *const right = expression->right;
6578 type_t *const orig_type_left = left->base.type;
6579 type_t *const orig_type_right = right->base.type;
6580 type_t *const type_left = skip_typeref(orig_type_left);
6581 type_t *const type_right = skip_typeref(orig_type_right);
6583 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6584 /* TODO: improve error message */
6585 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6586 errorf(HERE, "operation needs arithmetic types");
6591 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6592 expression->left = create_implicit_cast(left, arithmetic_type);
6593 expression->right = create_implicit_cast(right, arithmetic_type);
6594 expression->base.type = arithmetic_type;
6597 static void semantic_shift_op(binary_expression_t *expression)
6599 expression_t *const left = expression->left;
6600 expression_t *const right = expression->right;
6601 type_t *const orig_type_left = left->base.type;
6602 type_t *const orig_type_right = right->base.type;
6603 type_t * type_left = skip_typeref(orig_type_left);
6604 type_t * type_right = skip_typeref(orig_type_right);
6606 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
6607 /* TODO: improve error message */
6608 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6609 errorf(HERE, "operation needs integer types");
6614 type_left = promote_integer(type_left);
6615 type_right = promote_integer(type_right);
6617 expression->left = create_implicit_cast(left, type_left);
6618 expression->right = create_implicit_cast(right, type_right);
6619 expression->base.type = type_left;
6622 static void semantic_add(binary_expression_t *expression)
6624 expression_t *const left = expression->left;
6625 expression_t *const right = expression->right;
6626 type_t *const orig_type_left = left->base.type;
6627 type_t *const orig_type_right = right->base.type;
6628 type_t *const type_left = skip_typeref(orig_type_left);
6629 type_t *const type_right = skip_typeref(orig_type_right);
6632 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6633 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6634 expression->left = create_implicit_cast(left, arithmetic_type);
6635 expression->right = create_implicit_cast(right, arithmetic_type);
6636 expression->base.type = arithmetic_type;
6638 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6639 check_pointer_arithmetic(&expression->base.source_position,
6640 type_left, orig_type_left);
6641 expression->base.type = type_left;
6642 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6643 check_pointer_arithmetic(&expression->base.source_position,
6644 type_right, orig_type_right);
6645 expression->base.type = type_right;
6646 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6647 errorf(&expression->base.source_position,
6648 "invalid operands to binary + ('%T', '%T')",
6649 orig_type_left, orig_type_right);
6653 static void semantic_sub(binary_expression_t *expression)
6655 expression_t *const left = expression->left;
6656 expression_t *const right = expression->right;
6657 type_t *const orig_type_left = left->base.type;
6658 type_t *const orig_type_right = right->base.type;
6659 type_t *const type_left = skip_typeref(orig_type_left);
6660 type_t *const type_right = skip_typeref(orig_type_right);
6663 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6664 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6665 expression->left = create_implicit_cast(left, arithmetic_type);
6666 expression->right = create_implicit_cast(right, arithmetic_type);
6667 expression->base.type = arithmetic_type;
6669 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6670 check_pointer_arithmetic(&expression->base.source_position,
6671 type_left, orig_type_left);
6672 expression->base.type = type_left;
6673 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6674 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6675 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6676 if (!types_compatible(unqual_left, unqual_right)) {
6677 errorf(&expression->base.source_position,
6678 "subtracting pointers to incompatible types '%T' and '%T'",
6679 orig_type_left, orig_type_right);
6680 } else if (!is_type_object(unqual_left)) {
6681 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6682 warningf(&expression->base.source_position,
6683 "subtracting pointers to void");
6685 errorf(&expression->base.source_position,
6686 "subtracting pointers to non-object types '%T'",
6690 expression->base.type = type_ptrdiff_t;
6691 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6692 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6693 orig_type_left, orig_type_right);
6698 * Check the semantics of comparison expressions.
6700 * @param expression The expression to check.
6702 static void semantic_comparison(binary_expression_t *expression)
6704 expression_t *left = expression->left;
6705 expression_t *right = expression->right;
6706 type_t *orig_type_left = left->base.type;
6707 type_t *orig_type_right = right->base.type;
6709 type_t *type_left = skip_typeref(orig_type_left);
6710 type_t *type_right = skip_typeref(orig_type_right);
6712 /* TODO non-arithmetic types */
6713 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6714 /* test for signed vs unsigned compares */
6715 if (warning.sign_compare &&
6716 (expression->base.kind != EXPR_BINARY_EQUAL &&
6717 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6718 (is_type_signed(type_left) != is_type_signed(type_right))) {
6720 /* check if 1 of the operands is a constant, in this case we just
6721 * check wether we can safely represent the resulting constant in
6722 * the type of the other operand. */
6723 expression_t *const_expr = NULL;
6724 expression_t *other_expr = NULL;
6726 if (is_constant_expression(left)) {
6729 } else if (is_constant_expression(right)) {
6734 if (const_expr != NULL) {
6735 type_t *other_type = skip_typeref(other_expr->base.type);
6736 long val = fold_constant(const_expr);
6737 /* TODO: check if val can be represented by other_type */
6741 warningf(&expression->base.source_position,
6742 "comparison between signed and unsigned");
6744 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6745 expression->left = create_implicit_cast(left, arithmetic_type);
6746 expression->right = create_implicit_cast(right, arithmetic_type);
6747 expression->base.type = arithmetic_type;
6748 if (warning.float_equal &&
6749 (expression->base.kind == EXPR_BINARY_EQUAL ||
6750 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6751 is_type_float(arithmetic_type)) {
6752 warningf(&expression->base.source_position,
6753 "comparing floating point with == or != is unsafe");
6755 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6756 /* TODO check compatibility */
6757 } else if (is_type_pointer(type_left)) {
6758 expression->right = create_implicit_cast(right, type_left);
6759 } else if (is_type_pointer(type_right)) {
6760 expression->left = create_implicit_cast(left, type_right);
6761 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6762 type_error_incompatible("invalid operands in comparison",
6763 &expression->base.source_position,
6764 type_left, type_right);
6766 expression->base.type = type_int;
6770 * Checks if a compound type has constant fields.
6772 static bool has_const_fields(const compound_type_t *type)
6774 const scope_t *scope = &type->declaration->scope;
6775 const declaration_t *declaration = scope->declarations;
6777 for (; declaration != NULL; declaration = declaration->next) {
6778 if (declaration->namespc != NAMESPACE_NORMAL)
6781 const type_t *decl_type = skip_typeref(declaration->type);
6782 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6789 static bool is_lvalue(const expression_t *expression)
6791 switch (expression->kind) {
6792 case EXPR_REFERENCE:
6793 case EXPR_ARRAY_ACCESS:
6795 case EXPR_UNARY_DEREFERENCE:
6803 static bool is_valid_assignment_lhs(expression_t const* const left)
6805 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6806 type_t *const type_left = skip_typeref(orig_type_left);
6808 if (!is_lvalue(left)) {
6809 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6814 if (is_type_array(type_left)) {
6815 errorf(HERE, "cannot assign to arrays ('%E')", left);
6818 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6819 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6823 if (is_type_incomplete(type_left)) {
6824 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6825 left, orig_type_left);
6828 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6829 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6830 left, orig_type_left);
6837 static void semantic_arithmetic_assign(binary_expression_t *expression)
6839 expression_t *left = expression->left;
6840 expression_t *right = expression->right;
6841 type_t *orig_type_left = left->base.type;
6842 type_t *orig_type_right = right->base.type;
6844 if (!is_valid_assignment_lhs(left))
6847 type_t *type_left = skip_typeref(orig_type_left);
6848 type_t *type_right = skip_typeref(orig_type_right);
6850 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6851 /* TODO: improve error message */
6852 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6853 errorf(HERE, "operation needs arithmetic types");
6858 /* combined instructions are tricky. We can't create an implicit cast on
6859 * the left side, because we need the uncasted form for the store.
6860 * The ast2firm pass has to know that left_type must be right_type
6861 * for the arithmetic operation and create a cast by itself */
6862 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6863 expression->right = create_implicit_cast(right, arithmetic_type);
6864 expression->base.type = type_left;
6867 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6869 expression_t *const left = expression->left;
6870 expression_t *const right = expression->right;
6871 type_t *const orig_type_left = left->base.type;
6872 type_t *const orig_type_right = right->base.type;
6873 type_t *const type_left = skip_typeref(orig_type_left);
6874 type_t *const type_right = skip_typeref(orig_type_right);
6876 if (!is_valid_assignment_lhs(left))
6879 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6880 /* combined instructions are tricky. We can't create an implicit cast on
6881 * the left side, because we need the uncasted form for the store.
6882 * The ast2firm pass has to know that left_type must be right_type
6883 * for the arithmetic operation and create a cast by itself */
6884 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6885 expression->right = create_implicit_cast(right, arithmetic_type);
6886 expression->base.type = type_left;
6887 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6888 check_pointer_arithmetic(&expression->base.source_position,
6889 type_left, orig_type_left);
6890 expression->base.type = type_left;
6891 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6892 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6897 * Check the semantic restrictions of a logical expression.
6899 static void semantic_logical_op(binary_expression_t *expression)
6901 expression_t *const left = expression->left;
6902 expression_t *const right = expression->right;
6903 type_t *const orig_type_left = left->base.type;
6904 type_t *const orig_type_right = right->base.type;
6905 type_t *const type_left = skip_typeref(orig_type_left);
6906 type_t *const type_right = skip_typeref(orig_type_right);
6908 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6909 /* TODO: improve error message */
6910 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6911 errorf(HERE, "operation needs scalar types");
6916 expression->base.type = type_int;
6920 * Check the semantic restrictions of a binary assign expression.
6922 static void semantic_binexpr_assign(binary_expression_t *expression)
6924 expression_t *left = expression->left;
6925 type_t *orig_type_left = left->base.type;
6927 type_t *type_left = revert_automatic_type_conversion(left);
6928 type_left = skip_typeref(orig_type_left);
6930 if (!is_valid_assignment_lhs(left))
6933 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6934 report_assign_error(error, orig_type_left, expression->right,
6935 "assignment", &left->base.source_position);
6936 expression->right = create_implicit_cast(expression->right, orig_type_left);
6937 expression->base.type = orig_type_left;
6941 * Determine if the outermost operation (or parts thereof) of the given
6942 * expression has no effect in order to generate a warning about this fact.
6943 * Therefore in some cases this only examines some of the operands of the
6944 * expression (see comments in the function and examples below).
6946 * f() + 23; // warning, because + has no effect
6947 * x || f(); // no warning, because x controls execution of f()
6948 * x ? y : f(); // warning, because y has no effect
6949 * (void)x; // no warning to be able to suppress the warning
6950 * This function can NOT be used for an "expression has definitely no effect"-
6952 static bool expression_has_effect(const expression_t *const expr)
6954 switch (expr->kind) {
6955 case EXPR_UNKNOWN: break;
6956 case EXPR_INVALID: return true; /* do NOT warn */
6957 case EXPR_REFERENCE: return false;
6958 /* suppress the warning for microsoft __noop operations */
6959 case EXPR_CONST: return expr->conste.is_ms_noop;
6960 case EXPR_CHARACTER_CONSTANT: return false;
6961 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6962 case EXPR_STRING_LITERAL: return false;
6963 case EXPR_WIDE_STRING_LITERAL: return false;
6966 const call_expression_t *const call = &expr->call;
6967 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6970 switch (call->function->builtin_symbol.symbol->ID) {
6971 case T___builtin_va_end: return true;
6972 default: return false;
6976 /* Generate the warning if either the left or right hand side of a
6977 * conditional expression has no effect */
6978 case EXPR_CONDITIONAL: {
6979 const conditional_expression_t *const cond = &expr->conditional;
6981 expression_has_effect(cond->true_expression) &&
6982 expression_has_effect(cond->false_expression);
6985 case EXPR_SELECT: return false;
6986 case EXPR_ARRAY_ACCESS: return false;
6987 case EXPR_SIZEOF: return false;
6988 case EXPR_CLASSIFY_TYPE: return false;
6989 case EXPR_ALIGNOF: return false;
6991 case EXPR_FUNCNAME: return false;
6992 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6993 case EXPR_BUILTIN_CONSTANT_P: return false;
6994 case EXPR_BUILTIN_PREFETCH: return true;
6995 case EXPR_OFFSETOF: return false;
6996 case EXPR_VA_START: return true;
6997 case EXPR_VA_ARG: return true;
6998 case EXPR_STATEMENT: return true; // TODO
6999 case EXPR_COMPOUND_LITERAL: return false;
7001 case EXPR_UNARY_NEGATE: return false;
7002 case EXPR_UNARY_PLUS: return false;
7003 case EXPR_UNARY_BITWISE_NEGATE: return false;
7004 case EXPR_UNARY_NOT: return false;
7005 case EXPR_UNARY_DEREFERENCE: return false;
7006 case EXPR_UNARY_TAKE_ADDRESS: return false;
7007 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7008 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7009 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7010 case EXPR_UNARY_PREFIX_DECREMENT: return true;
7012 /* Treat void casts as if they have an effect in order to being able to
7013 * suppress the warning */
7014 case EXPR_UNARY_CAST: {
7015 type_t *const type = skip_typeref(expr->base.type);
7016 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7019 case EXPR_UNARY_CAST_IMPLICIT: return true;
7020 case EXPR_UNARY_ASSUME: return true;
7022 case EXPR_BINARY_ADD: return false;
7023 case EXPR_BINARY_SUB: return false;
7024 case EXPR_BINARY_MUL: return false;
7025 case EXPR_BINARY_DIV: return false;
7026 case EXPR_BINARY_MOD: return false;
7027 case EXPR_BINARY_EQUAL: return false;
7028 case EXPR_BINARY_NOTEQUAL: return false;
7029 case EXPR_BINARY_LESS: return false;
7030 case EXPR_BINARY_LESSEQUAL: return false;
7031 case EXPR_BINARY_GREATER: return false;
7032 case EXPR_BINARY_GREATEREQUAL: return false;
7033 case EXPR_BINARY_BITWISE_AND: return false;
7034 case EXPR_BINARY_BITWISE_OR: return false;
7035 case EXPR_BINARY_BITWISE_XOR: return false;
7036 case EXPR_BINARY_SHIFTLEFT: return false;
7037 case EXPR_BINARY_SHIFTRIGHT: return false;
7038 case EXPR_BINARY_ASSIGN: return true;
7039 case EXPR_BINARY_MUL_ASSIGN: return true;
7040 case EXPR_BINARY_DIV_ASSIGN: return true;
7041 case EXPR_BINARY_MOD_ASSIGN: return true;
7042 case EXPR_BINARY_ADD_ASSIGN: return true;
7043 case EXPR_BINARY_SUB_ASSIGN: return true;
7044 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7045 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7046 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7047 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7048 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7050 /* Only examine the right hand side of && and ||, because the left hand
7051 * side already has the effect of controlling the execution of the right
7053 case EXPR_BINARY_LOGICAL_AND:
7054 case EXPR_BINARY_LOGICAL_OR:
7055 /* Only examine the right hand side of a comma expression, because the left
7056 * hand side has a separate warning */
7057 case EXPR_BINARY_COMMA:
7058 return expression_has_effect(expr->binary.right);
7060 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7061 case EXPR_BINARY_ISGREATER: return false;
7062 case EXPR_BINARY_ISGREATEREQUAL: return false;
7063 case EXPR_BINARY_ISLESS: return false;
7064 case EXPR_BINARY_ISLESSEQUAL: return false;
7065 case EXPR_BINARY_ISLESSGREATER: return false;
7066 case EXPR_BINARY_ISUNORDERED: return false;
7069 internal_errorf(HERE, "unexpected expression");
7072 static void semantic_comma(binary_expression_t *expression)
7074 if (warning.unused_value) {
7075 const expression_t *const left = expression->left;
7076 if (!expression_has_effect(left)) {
7077 warningf(&left->base.source_position,
7078 "left-hand operand of comma expression has no effect");
7081 expression->base.type = expression->right->base.type;
7084 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7085 static expression_t *parse_##binexpression_type(unsigned precedence, \
7086 expression_t *left) \
7089 source_position_t pos = *HERE; \
7091 expression_t *right = parse_sub_expression(precedence + lr); \
7093 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7094 binexpr->base.source_position = pos; \
7095 binexpr->binary.left = left; \
7096 binexpr->binary.right = right; \
7097 sfunc(&binexpr->binary); \
7102 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7103 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7104 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7105 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7106 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7107 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7108 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7109 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7110 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7112 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7113 semantic_comparison, 1)
7114 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7115 semantic_comparison, 1)
7116 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7117 semantic_comparison, 1)
7118 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7119 semantic_comparison, 1)
7121 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7122 semantic_binexpr_arithmetic, 1)
7123 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7124 semantic_binexpr_arithmetic, 1)
7125 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7126 semantic_binexpr_arithmetic, 1)
7127 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7128 semantic_logical_op, 1)
7129 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7130 semantic_logical_op, 1)
7131 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7132 semantic_shift_op, 1)
7133 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7134 semantic_shift_op, 1)
7135 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7136 semantic_arithmetic_addsubb_assign, 0)
7137 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7138 semantic_arithmetic_addsubb_assign, 0)
7139 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7140 semantic_arithmetic_assign, 0)
7141 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7142 semantic_arithmetic_assign, 0)
7143 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7144 semantic_arithmetic_assign, 0)
7145 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7146 semantic_arithmetic_assign, 0)
7147 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7148 semantic_arithmetic_assign, 0)
7149 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7150 semantic_arithmetic_assign, 0)
7151 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7152 semantic_arithmetic_assign, 0)
7153 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7154 semantic_arithmetic_assign, 0)
7156 static expression_t *parse_sub_expression(unsigned precedence)
7158 if (token.type < 0) {
7159 return expected_expression_error();
7162 expression_parser_function_t *parser
7163 = &expression_parsers[token.type];
7164 source_position_t source_position = token.source_position;
7167 if (parser->parser != NULL) {
7168 left = parser->parser(parser->precedence);
7170 left = parse_primary_expression();
7172 assert(left != NULL);
7173 left->base.source_position = source_position;
7176 if (token.type < 0) {
7177 return expected_expression_error();
7180 parser = &expression_parsers[token.type];
7181 if (parser->infix_parser == NULL)
7183 if (parser->infix_precedence < precedence)
7186 left = parser->infix_parser(parser->infix_precedence, left);
7188 assert(left != NULL);
7189 assert(left->kind != EXPR_UNKNOWN);
7190 left->base.source_position = source_position;
7197 * Parse an expression.
7199 static expression_t *parse_expression(void)
7201 return parse_sub_expression(1);
7205 * Register a parser for a prefix-like operator with given precedence.
7207 * @param parser the parser function
7208 * @param token_type the token type of the prefix token
7209 * @param precedence the precedence of the operator
7211 static void register_expression_parser(parse_expression_function parser,
7212 int token_type, unsigned precedence)
7214 expression_parser_function_t *entry = &expression_parsers[token_type];
7216 if (entry->parser != NULL) {
7217 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7218 panic("trying to register multiple expression parsers for a token");
7220 entry->parser = parser;
7221 entry->precedence = precedence;
7225 * Register a parser for an infix operator with given precedence.
7227 * @param parser the parser function
7228 * @param token_type the token type of the infix operator
7229 * @param precedence the precedence of the operator
7231 static void register_infix_parser(parse_expression_infix_function parser,
7232 int token_type, unsigned precedence)
7234 expression_parser_function_t *entry = &expression_parsers[token_type];
7236 if (entry->infix_parser != NULL) {
7237 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7238 panic("trying to register multiple infix expression parsers for a "
7241 entry->infix_parser = parser;
7242 entry->infix_precedence = precedence;
7246 * Initialize the expression parsers.
7248 static void init_expression_parsers(void)
7250 memset(&expression_parsers, 0, sizeof(expression_parsers));
7252 register_infix_parser(parse_array_expression, '[', 30);
7253 register_infix_parser(parse_call_expression, '(', 30);
7254 register_infix_parser(parse_select_expression, '.', 30);
7255 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7256 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7258 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7261 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7262 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7263 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7264 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7265 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7266 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7267 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7268 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7269 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7270 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7271 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7272 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7273 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7274 T_EXCLAMATIONMARKEQUAL, 13);
7275 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7276 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7277 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7278 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7279 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7280 register_infix_parser(parse_conditional_expression, '?', 7);
7281 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7282 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7283 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7284 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7285 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7286 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7287 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7288 T_LESSLESSEQUAL, 2);
7289 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7290 T_GREATERGREATEREQUAL, 2);
7291 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7293 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7295 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7298 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7300 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7301 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7302 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7303 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7304 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7305 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7306 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7308 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7310 register_expression_parser(parse_sizeof, T_sizeof, 25);
7311 register_expression_parser(parse_alignof, T___alignof__, 25);
7312 register_expression_parser(parse_extension, T___extension__, 25);
7313 register_expression_parser(parse_builtin_classify_type,
7314 T___builtin_classify_type, 25);
7318 * Parse a asm statement arguments specification.
7320 static asm_argument_t *parse_asm_arguments(bool is_out)
7322 asm_argument_t *result = NULL;
7323 asm_argument_t *last = NULL;
7325 while (token.type == T_STRING_LITERAL || token.type == '[') {
7326 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7327 memset(argument, 0, sizeof(argument[0]));
7329 if (token.type == '[') {
7331 if (token.type != T_IDENTIFIER) {
7332 parse_error_expected("while parsing asm argument",
7333 T_IDENTIFIER, NULL);
7336 argument->symbol = token.v.symbol;
7341 argument->constraints = parse_string_literals();
7343 expression_t *expression = parse_expression();
7344 argument->expression = expression;
7345 if (is_out && !is_lvalue(expression)) {
7346 errorf(&expression->base.source_position,
7347 "asm output argument is not an lvalue");
7351 set_address_taken(expression, true);
7354 last->next = argument;
7360 if (token.type != ',')
7371 * Parse a asm statement clobber specification.
7373 static asm_clobber_t *parse_asm_clobbers(void)
7375 asm_clobber_t *result = NULL;
7376 asm_clobber_t *last = NULL;
7378 while(token.type == T_STRING_LITERAL) {
7379 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7380 clobber->clobber = parse_string_literals();
7383 last->next = clobber;
7389 if (token.type != ',')
7398 * Parse an asm statement.
7400 static statement_t *parse_asm_statement(void)
7404 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7405 statement->base.source_position = token.source_position;
7407 asm_statement_t *asm_statement = &statement->asms;
7409 if (token.type == T_volatile) {
7411 asm_statement->is_volatile = true;
7415 add_anchor_token(')');
7416 add_anchor_token(':');
7417 asm_statement->asm_text = parse_string_literals();
7419 if (token.type != ':') {
7420 rem_anchor_token(':');
7425 asm_statement->outputs = parse_asm_arguments(true);
7426 if (token.type != ':') {
7427 rem_anchor_token(':');
7432 asm_statement->inputs = parse_asm_arguments(false);
7433 if (token.type != ':') {
7434 rem_anchor_token(':');
7437 rem_anchor_token(':');
7440 asm_statement->clobbers = parse_asm_clobbers();
7443 rem_anchor_token(')');
7448 return create_invalid_statement();
7452 * Parse a case statement.
7454 static statement_t *parse_case_statement(void)
7458 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7460 statement->base.source_position = token.source_position;
7461 statement->case_label.expression = parse_expression();
7463 if (c_mode & _GNUC) {
7464 if (token.type == T_DOTDOTDOT) {
7466 statement->case_label.end_range = parse_expression();
7472 if (! is_constant_expression(statement->case_label.expression)) {
7473 errorf(&statement->base.source_position,
7474 "case label does not reduce to an integer constant");
7476 /* TODO: check if the case label is already known */
7477 if (current_switch != NULL) {
7478 /* link all cases into the switch statement */
7479 if (current_switch->last_case == NULL) {
7480 current_switch->first_case =
7481 current_switch->last_case = &statement->case_label;
7483 current_switch->last_case->next = &statement->case_label;
7486 errorf(&statement->base.source_position,
7487 "case label not within a switch statement");
7490 statement->case_label.statement = parse_statement();
7494 return create_invalid_statement();
7498 * Finds an existing default label of a switch statement.
7500 static case_label_statement_t *
7501 find_default_label(const switch_statement_t *statement)
7503 case_label_statement_t *label = statement->first_case;
7504 for ( ; label != NULL; label = label->next) {
7505 if (label->expression == NULL)
7512 * Parse a default statement.
7514 static statement_t *parse_default_statement(void)
7518 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7520 statement->base.source_position = token.source_position;
7523 if (current_switch != NULL) {
7524 const case_label_statement_t *def_label = find_default_label(current_switch);
7525 if (def_label != NULL) {
7526 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7527 &def_label->base.source_position);
7529 /* link all cases into the switch statement */
7530 if (current_switch->last_case == NULL) {
7531 current_switch->first_case =
7532 current_switch->last_case = &statement->case_label;
7534 current_switch->last_case->next = &statement->case_label;
7538 errorf(&statement->base.source_position,
7539 "'default' label not within a switch statement");
7541 statement->case_label.statement = parse_statement();
7545 return create_invalid_statement();
7549 * Return the declaration for a given label symbol or create a new one.
7551 static declaration_t *get_label(symbol_t *symbol)
7553 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7554 assert(current_function != NULL);
7555 /* if we found a label in the same function, then we already created the
7557 if (candidate != NULL
7558 && candidate->parent_scope == ¤t_function->scope) {
7562 /* otherwise we need to create a new one */
7563 declaration_t *const declaration = allocate_declaration_zero();
7564 declaration->namespc = NAMESPACE_LABEL;
7565 declaration->symbol = symbol;
7567 label_push(declaration);
7573 * Parse a label statement.
7575 static statement_t *parse_label_statement(void)
7577 assert(token.type == T_IDENTIFIER);
7578 symbol_t *symbol = token.v.symbol;
7581 declaration_t *label = get_label(symbol);
7583 /* if source position is already set then the label is defined twice,
7584 * otherwise it was just mentioned in a goto so far */
7585 if (label->source_position.input_name != NULL) {
7586 errorf(HERE, "duplicate label '%Y' (declared %P)",
7587 symbol, &label->source_position);
7589 label->source_position = token.source_position;
7592 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7594 statement->base.source_position = token.source_position;
7595 statement->label.label = label;
7599 if (token.type == '}') {
7600 /* TODO only warn? */
7602 warningf(HERE, "label at end of compound statement");
7603 statement->label.statement = create_empty_statement();
7605 errorf(HERE, "label at end of compound statement");
7606 statement->label.statement = create_invalid_statement();
7610 if (token.type == ';') {
7611 /* eat an empty statement here, to avoid the warning about an empty
7612 * after a label. label:; is commonly used to have a label before
7614 statement->label.statement = create_empty_statement();
7617 statement->label.statement = parse_statement();
7621 /* remember the labels's in a list for later checking */
7622 if (label_last == NULL) {
7623 label_first = &statement->label;
7625 label_last->next = &statement->label;
7627 label_last = &statement->label;
7633 * Parse an if statement.
7635 static statement_t *parse_if(void)
7639 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7640 statement->base.source_position = token.source_position;
7643 add_anchor_token(')');
7644 statement->ifs.condition = parse_expression();
7645 rem_anchor_token(')');
7648 add_anchor_token(T_else);
7649 statement->ifs.true_statement = parse_statement();
7650 rem_anchor_token(T_else);
7652 if (token.type == T_else) {
7654 statement->ifs.false_statement = parse_statement();
7659 return create_invalid_statement();
7663 * Parse a switch statement.
7665 static statement_t *parse_switch(void)
7669 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7670 statement->base.source_position = token.source_position;
7673 expression_t *const expr = parse_expression();
7674 type_t * type = skip_typeref(expr->base.type);
7675 if (is_type_integer(type)) {
7676 type = promote_integer(type);
7677 } else if (is_type_valid(type)) {
7678 errorf(&expr->base.source_position,
7679 "switch quantity is not an integer, but '%T'", type);
7680 type = type_error_type;
7682 statement->switchs.expression = create_implicit_cast(expr, type);
7685 switch_statement_t *rem = current_switch;
7686 current_switch = &statement->switchs;
7687 statement->switchs.body = parse_statement();
7688 current_switch = rem;
7690 if (warning.switch_default &&
7691 find_default_label(&statement->switchs) == NULL) {
7692 warningf(&statement->base.source_position, "switch has no default case");
7697 return create_invalid_statement();
7700 static statement_t *parse_loop_body(statement_t *const loop)
7702 statement_t *const rem = current_loop;
7703 current_loop = loop;
7705 statement_t *const body = parse_statement();
7712 * Parse a while statement.
7714 static statement_t *parse_while(void)
7718 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7719 statement->base.source_position = token.source_position;
7722 add_anchor_token(')');
7723 statement->whiles.condition = parse_expression();
7724 rem_anchor_token(')');
7727 statement->whiles.body = parse_loop_body(statement);
7731 return create_invalid_statement();
7735 * Parse a do statement.
7737 static statement_t *parse_do(void)
7741 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7743 statement->base.source_position = token.source_position;
7745 add_anchor_token(T_while);
7746 statement->do_while.body = parse_loop_body(statement);
7747 rem_anchor_token(T_while);
7751 add_anchor_token(')');
7752 statement->do_while.condition = parse_expression();
7753 rem_anchor_token(')');
7759 return create_invalid_statement();
7763 * Parse a for statement.
7765 static statement_t *parse_for(void)
7769 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7770 statement->base.source_position = token.source_position;
7772 int top = environment_top();
7773 scope_t *last_scope = scope;
7774 set_scope(&statement->fors.scope);
7777 add_anchor_token(')');
7779 if (token.type != ';') {
7780 if (is_declaration_specifier(&token, false)) {
7781 parse_declaration(record_declaration);
7783 add_anchor_token(';');
7784 expression_t *const init = parse_expression();
7785 statement->fors.initialisation = init;
7786 if (warning.unused_value && !expression_has_effect(init)) {
7787 warningf(&init->base.source_position,
7788 "initialisation of 'for'-statement has no effect");
7790 rem_anchor_token(';');
7797 if (token.type != ';') {
7798 add_anchor_token(';');
7799 statement->fors.condition = parse_expression();
7800 rem_anchor_token(';');
7803 if (token.type != ')') {
7804 expression_t *const step = parse_expression();
7805 statement->fors.step = step;
7806 if (warning.unused_value && !expression_has_effect(step)) {
7807 warningf(&step->base.source_position,
7808 "step of 'for'-statement has no effect");
7811 rem_anchor_token(')');
7813 statement->fors.body = parse_loop_body(statement);
7815 assert(scope == &statement->fors.scope);
7816 set_scope(last_scope);
7817 environment_pop_to(top);
7822 rem_anchor_token(')');
7823 assert(scope == &statement->fors.scope);
7824 set_scope(last_scope);
7825 environment_pop_to(top);
7827 return create_invalid_statement();
7831 * Parse a goto statement.
7833 static statement_t *parse_goto(void)
7837 if (token.type != T_IDENTIFIER) {
7838 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7842 symbol_t *symbol = token.v.symbol;
7845 declaration_t *label = get_label(symbol);
7847 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7848 statement->base.source_position = token.source_position;
7850 statement->gotos.label = label;
7852 /* remember the goto's in a list for later checking */
7853 if (goto_last == NULL) {
7854 goto_first = &statement->gotos;
7856 goto_last->next = &statement->gotos;
7858 goto_last = &statement->gotos;
7864 return create_invalid_statement();
7868 * Parse a continue statement.
7870 static statement_t *parse_continue(void)
7872 statement_t *statement;
7873 if (current_loop == NULL) {
7874 errorf(HERE, "continue statement not within loop");
7875 statement = create_invalid_statement();
7877 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7879 statement->base.source_position = token.source_position;
7887 return create_invalid_statement();
7891 * Parse a break statement.
7893 static statement_t *parse_break(void)
7895 statement_t *statement;
7896 if (current_switch == NULL && current_loop == NULL) {
7897 errorf(HERE, "break statement not within loop or switch");
7898 statement = create_invalid_statement();
7900 statement = allocate_statement_zero(STATEMENT_BREAK);
7902 statement->base.source_position = token.source_position;
7910 return create_invalid_statement();
7914 * Parse a __leave statement.
7916 static statement_t *parse_leave(void)
7918 statement_t *statement;
7919 if (current_try == NULL) {
7920 errorf(HERE, "__leave statement not within __try");
7921 statement = create_invalid_statement();
7923 statement = allocate_statement_zero(STATEMENT_LEAVE);
7925 statement->base.source_position = token.source_position;
7933 return create_invalid_statement();
7937 * Check if a given declaration represents a local variable.
7939 static bool is_local_var_declaration(const declaration_t *declaration) {
7940 switch ((storage_class_tag_t) declaration->storage_class) {
7941 case STORAGE_CLASS_AUTO:
7942 case STORAGE_CLASS_REGISTER: {
7943 const type_t *type = skip_typeref(declaration->type);
7944 if (is_type_function(type)) {
7956 * Check if a given declaration represents a variable.
7958 static bool is_var_declaration(const declaration_t *declaration) {
7959 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7962 const type_t *type = skip_typeref(declaration->type);
7963 return !is_type_function(type);
7967 * Check if a given expression represents a local variable.
7969 static bool is_local_variable(const expression_t *expression)
7971 if (expression->base.kind != EXPR_REFERENCE) {
7974 const declaration_t *declaration = expression->reference.declaration;
7975 return is_local_var_declaration(declaration);
7979 * Check if a given expression represents a local variable and
7980 * return its declaration then, else return NULL.
7982 declaration_t *expr_is_variable(const expression_t *expression)
7984 if (expression->base.kind != EXPR_REFERENCE) {
7987 declaration_t *declaration = expression->reference.declaration;
7988 if (is_var_declaration(declaration))
7994 * Parse a return statement.
7996 static statement_t *parse_return(void)
7998 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7999 statement->base.source_position = token.source_position;
8003 expression_t *return_value = NULL;
8004 if (token.type != ';') {
8005 return_value = parse_expression();
8009 const type_t *const func_type = current_function->type;
8010 assert(is_type_function(func_type));
8011 type_t *const return_type = skip_typeref(func_type->function.return_type);
8013 if (return_value != NULL) {
8014 type_t *return_value_type = skip_typeref(return_value->base.type);
8016 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8017 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8018 warningf(&statement->base.source_position,
8019 "'return' with a value, in function returning void");
8020 return_value = NULL;
8022 assign_error_t error = semantic_assign(return_type, return_value);
8023 report_assign_error(error, return_type, return_value, "'return'",
8024 &statement->base.source_position);
8025 return_value = create_implicit_cast(return_value, return_type);
8027 /* check for returning address of a local var */
8028 if (return_value != NULL &&
8029 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8030 const expression_t *expression = return_value->unary.value;
8031 if (is_local_variable(expression)) {
8032 warningf(&statement->base.source_position,
8033 "function returns address of local variable");
8037 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8038 warningf(&statement->base.source_position,
8039 "'return' without value, in function returning non-void");
8042 statement->returns.value = return_value;
8046 return create_invalid_statement();
8050 * Parse a declaration statement.
8052 static statement_t *parse_declaration_statement(void)
8054 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8056 statement->base.source_position = token.source_position;
8058 declaration_t *before = last_declaration;
8059 parse_declaration(record_declaration);
8061 if (before == NULL) {
8062 statement->declaration.declarations_begin = scope->declarations;
8064 statement->declaration.declarations_begin = before->next;
8066 statement->declaration.declarations_end = last_declaration;
8072 * Parse an expression statement, ie. expr ';'.
8074 static statement_t *parse_expression_statement(void)
8076 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8078 statement->base.source_position = token.source_position;
8079 expression_t *const expr = parse_expression();
8080 statement->expression.expression = expr;
8086 return create_invalid_statement();
8090 * Parse a microsoft __try { } __finally { } or
8091 * __try{ } __except() { }
8093 static statement_t *parse_ms_try_statment(void) {
8094 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8096 statement->base.source_position = token.source_position;
8099 ms_try_statement_t *rem = current_try;
8100 current_try = &statement->ms_try;
8101 statement->ms_try.try_statement = parse_compound_statement(false);
8104 if (token.type == T___except) {
8107 add_anchor_token(')');
8108 expression_t *const expr = parse_expression();
8109 type_t * type = skip_typeref(expr->base.type);
8110 if (is_type_integer(type)) {
8111 type = promote_integer(type);
8112 } else if (is_type_valid(type)) {
8113 errorf(&expr->base.source_position,
8114 "__expect expression is not an integer, but '%T'", type);
8115 type = type_error_type;
8117 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8118 rem_anchor_token(')');
8120 statement->ms_try.final_statement = parse_compound_statement(false);
8121 } else if (token.type == T__finally) {
8123 statement->ms_try.final_statement = parse_compound_statement(false);
8125 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8126 return create_invalid_statement();
8130 return create_invalid_statement();
8134 * Parse a statement.
8135 * There's also parse_statement() which additionally checks for
8136 * "statement has no effect" warnings
8138 static statement_t *intern_parse_statement(void)
8140 statement_t *statement = NULL;
8142 /* declaration or statement */
8143 add_anchor_token(';');
8144 switch(token.type) {
8146 statement = parse_asm_statement();
8150 statement = parse_case_statement();
8154 statement = parse_default_statement();
8158 statement = parse_compound_statement(false);
8162 statement = parse_if ();
8166 statement = parse_switch();
8170 statement = parse_while();
8174 statement = parse_do();
8178 statement = parse_for();
8182 statement = parse_goto();
8186 statement = parse_continue();
8190 statement = parse_break();
8194 statement = parse_leave();
8198 statement = parse_return();
8202 if (warning.empty_statement) {
8203 warningf(HERE, "statement is empty");
8205 statement = create_empty_statement();
8210 if (look_ahead(1)->type == ':') {
8211 statement = parse_label_statement();
8215 if (is_typedef_symbol(token.v.symbol)) {
8216 statement = parse_declaration_statement();
8220 statement = parse_expression_statement();
8223 case T___extension__:
8224 /* this can be a prefix to a declaration or an expression statement */
8225 /* we simply eat it now and parse the rest with tail recursion */
8228 } while(token.type == T___extension__);
8229 statement = parse_statement();
8233 statement = parse_declaration_statement();
8237 statement = parse_ms_try_statment();
8241 statement = parse_expression_statement();
8244 rem_anchor_token(';');
8246 assert(statement != NULL
8247 && statement->base.source_position.input_name != NULL);
8253 * parse a statement and emits "statement has no effect" warning if needed
8254 * (This is really a wrapper around intern_parse_statement with check for 1
8255 * single warning. It is needed, because for statement expressions we have
8256 * to avoid the warning on the last statement)
8258 static statement_t *parse_statement(void)
8260 statement_t *statement = intern_parse_statement();
8262 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8263 expression_t *expression = statement->expression.expression;
8264 if (!expression_has_effect(expression)) {
8265 warningf(&expression->base.source_position,
8266 "statement has no effect");
8274 * Parse a compound statement.
8276 static statement_t *parse_compound_statement(bool inside_expression_statement)
8278 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8280 statement->base.source_position = token.source_position;
8283 add_anchor_token('}');
8285 int top = environment_top();
8286 scope_t *last_scope = scope;
8287 set_scope(&statement->compound.scope);
8289 statement_t *last_statement = NULL;
8291 while(token.type != '}' && token.type != T_EOF) {
8292 statement_t *sub_statement = intern_parse_statement();
8293 if (is_invalid_statement(sub_statement)) {
8294 /* an error occurred. if we are at an anchor, return */
8300 if (last_statement != NULL) {
8301 last_statement->base.next = sub_statement;
8303 statement->compound.statements = sub_statement;
8306 while(sub_statement->base.next != NULL)
8307 sub_statement = sub_statement->base.next;
8309 last_statement = sub_statement;
8312 if (token.type == '}') {
8315 errorf(&statement->base.source_position,
8316 "end of file while looking for closing '}'");
8319 /* look over all statements again to produce no effect warnings */
8320 if (warning.unused_value) {
8321 statement_t *sub_statement = statement->compound.statements;
8322 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8323 if (sub_statement->kind != STATEMENT_EXPRESSION)
8325 /* don't emit a warning for the last expression in an expression
8326 * statement as it has always an effect */
8327 if (inside_expression_statement && sub_statement->base.next == NULL)
8330 expression_t *expression = sub_statement->expression.expression;
8331 if (!expression_has_effect(expression)) {
8332 warningf(&expression->base.source_position,
8333 "statement has no effect");
8339 rem_anchor_token('}');
8340 assert(scope == &statement->compound.scope);
8341 set_scope(last_scope);
8342 environment_pop_to(top);
8348 * Initialize builtin types.
8350 static void initialize_builtin_types(void)
8352 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8353 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8354 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8355 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8356 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8357 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8358 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8359 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8361 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8362 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8363 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8364 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8368 * Check for unused global static functions and variables
8370 static void check_unused_globals(void)
8372 if (!warning.unused_function && !warning.unused_variable)
8375 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8377 decl->modifiers & DM_USED ||
8378 decl->storage_class != STORAGE_CLASS_STATIC)
8381 type_t *const type = decl->type;
8383 if (is_type_function(skip_typeref(type))) {
8384 if (!warning.unused_function || decl->is_inline)
8387 s = (decl->init.statement != NULL ? "defined" : "declared");
8389 if (!warning.unused_variable)
8395 warningf(&decl->source_position, "'%#T' %s but not used",
8396 type, decl->symbol, s);
8400 static void parse_global_asm(void)
8405 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8406 statement->base.source_position = token.source_position;
8407 statement->asms.asm_text = parse_string_literals();
8408 statement->base.next = unit->global_asm;
8409 unit->global_asm = statement;
8418 * Parse a translation unit.
8420 static void parse_translation_unit(void)
8422 while(token.type != T_EOF) {
8423 switch (token.type) {
8425 /* TODO error in strict mode */
8426 warningf(HERE, "stray ';' outside of function");
8435 parse_external_declaration();
8444 * @return the translation unit or NULL if errors occurred.
8446 void start_parsing(void)
8448 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8449 label_stack = NEW_ARR_F(stack_entry_t, 0);
8450 diagnostic_count = 0;
8454 type_set_output(stderr);
8455 ast_set_output(stderr);
8457 assert(unit == NULL);
8458 unit = allocate_ast_zero(sizeof(unit[0]));
8460 assert(global_scope == NULL);
8461 global_scope = &unit->scope;
8463 assert(scope == NULL);
8464 set_scope(&unit->scope);
8466 initialize_builtin_types();
8469 translation_unit_t *finish_parsing(void)
8471 assert(scope == &unit->scope);
8473 last_declaration = NULL;
8475 assert(global_scope == &unit->scope);
8476 check_unused_globals();
8477 global_scope = NULL;
8479 DEL_ARR_F(environment_stack);
8480 DEL_ARR_F(label_stack);
8482 translation_unit_t *result = unit;
8489 lookahead_bufpos = 0;
8490 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8493 parse_translation_unit();
8497 * Initialize the parser.
8499 void init_parser(void)
8502 /* add predefined symbols for extended-decl-modifier */
8503 sym_align = symbol_table_insert("align");
8504 sym_allocate = symbol_table_insert("allocate");
8505 sym_dllimport = symbol_table_insert("dllimport");
8506 sym_dllexport = symbol_table_insert("dllexport");
8507 sym_naked = symbol_table_insert("naked");
8508 sym_noinline = symbol_table_insert("noinline");
8509 sym_noreturn = symbol_table_insert("noreturn");
8510 sym_nothrow = symbol_table_insert("nothrow");
8511 sym_novtable = symbol_table_insert("novtable");
8512 sym_property = symbol_table_insert("property");
8513 sym_get = symbol_table_insert("get");
8514 sym_put = symbol_table_insert("put");
8515 sym_selectany = symbol_table_insert("selectany");
8516 sym_thread = symbol_table_insert("thread");
8517 sym_uuid = symbol_table_insert("uuid");
8518 sym_deprecated = symbol_table_insert("deprecated");
8519 sym_restrict = symbol_table_insert("restrict");
8520 sym_noalias = symbol_table_insert("noalias");
8522 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8524 init_expression_parsers();
8525 obstack_init(&temp_obst);
8527 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8528 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8532 * Terminate the parser.
8534 void exit_parser(void)
8536 obstack_free(&temp_obst, NULL);