2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 //#define PRINT_TOKENS
43 #define MAX_LOOKAHEAD 2
46 declaration_t *old_declaration;
48 unsigned short namespc;
51 typedef struct gnu_attribute_t gnu_attribute_t;
52 struct gnu_attribute_t {
53 gnu_attribute_kind_t kind;
54 gnu_attribute_t *next;
63 typedef struct declaration_specifiers_t declaration_specifiers_t;
64 struct declaration_specifiers_t {
65 source_position_t source_position;
66 unsigned char declared_storage_class;
67 unsigned char alignment; /**< Alignment, 0 if not set. */
68 unsigned int is_inline : 1;
69 unsigned int deprecated : 1;
70 decl_modifiers_t modifiers; /**< declaration modifiers */
71 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
72 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
73 symbol_t *get_property_sym; /**< the name of the get property if set. */
74 symbol_t *put_property_sym; /**< the name of the put property if set. */
79 * An environment for parsing initializers (and compound literals).
81 typedef struct parse_initializer_env_t {
82 type_t *type; /**< the type of the initializer. In case of an
83 array type with unspecified size this gets
84 adjusted to the actual size. */
85 declaration_t *declaration; /**< the declaration that is initialized if any */
86 bool must_be_constant;
87 } parse_initializer_env_t;
89 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
92 static token_t lookahead_buffer[MAX_LOOKAHEAD];
93 static int lookahead_bufpos;
94 static stack_entry_t *environment_stack = NULL;
95 static stack_entry_t *label_stack = NULL;
96 static scope_t *global_scope = NULL;
97 static scope_t *scope = NULL;
98 static declaration_t *last_declaration = NULL;
99 static declaration_t *current_function = NULL;
100 static switch_statement_t *current_switch = NULL;
101 static statement_t *current_loop = NULL;
102 static ms_try_statement_t *current_try = NULL;
103 static goto_statement_t *goto_first = NULL;
104 static goto_statement_t *goto_last = NULL;
105 static label_statement_t *label_first = NULL;
106 static label_statement_t *label_last = NULL;
107 static translation_unit_t *unit = NULL;
108 static struct obstack temp_obst;
110 static source_position_t null_position = { NULL, 0 };
112 /* symbols for Microsoft extended-decl-modifier */
113 static const symbol_t *sym_align = NULL;
114 static const symbol_t *sym_allocate = NULL;
115 static const symbol_t *sym_dllimport = NULL;
116 static const symbol_t *sym_dllexport = NULL;
117 static const symbol_t *sym_naked = NULL;
118 static const symbol_t *sym_noinline = NULL;
119 static const symbol_t *sym_noreturn = NULL;
120 static const symbol_t *sym_nothrow = NULL;
121 static const symbol_t *sym_novtable = NULL;
122 static const symbol_t *sym_property = NULL;
123 static const symbol_t *sym_get = NULL;
124 static const symbol_t *sym_put = NULL;
125 static const symbol_t *sym_selectany = NULL;
126 static const symbol_t *sym_thread = NULL;
127 static const symbol_t *sym_uuid = NULL;
128 static const symbol_t *sym_deprecated = NULL;
129 static const symbol_t *sym_restrict = NULL;
130 static const symbol_t *sym_noalias = NULL;
132 /** The token anchor set */
133 static unsigned char token_anchor_set[T_LAST_TOKEN];
135 /** The current source position. */
136 #define HERE (&token.source_position)
138 static type_t *type_valist;
140 static statement_t *parse_compound_statement(bool inside_expression_statement);
141 static statement_t *parse_statement(void);
143 static expression_t *parse_sub_expression(unsigned precedence);
144 static expression_t *parse_expression(void);
145 static type_t *parse_typename(void);
147 static void parse_compound_type_entries(declaration_t *compound_declaration);
148 static declaration_t *parse_declarator(
149 const declaration_specifiers_t *specifiers, bool may_be_abstract);
150 static declaration_t *record_declaration(declaration_t *declaration);
152 static void semantic_comparison(binary_expression_t *expression);
154 #define STORAGE_CLASSES \
161 #define TYPE_QUALIFIERS \
166 case T__forceinline: \
167 case T___attribute__:
169 #ifdef PROVIDE_COMPLEX
170 #define COMPLEX_SPECIFIERS \
172 #define IMAGINARY_SPECIFIERS \
175 #define COMPLEX_SPECIFIERS
176 #define IMAGINARY_SPECIFIERS
179 #define TYPE_SPECIFIERS \
194 case T___builtin_va_list: \
199 #define DECLARATION_START \
204 #define TYPENAME_START \
209 * Allocate an AST node with given size and
210 * initialize all fields with zero.
212 static void *allocate_ast_zero(size_t size)
214 void *res = allocate_ast(size);
215 memset(res, 0, size);
219 static declaration_t *allocate_declaration_zero(void)
221 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
222 declaration->type = type_error_type;
223 declaration->alignment = 0;
228 * Returns the size of a statement node.
230 * @param kind the statement kind
232 static size_t get_statement_struct_size(statement_kind_t kind)
234 static const size_t sizes[] = {
235 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
236 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
237 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
238 [STATEMENT_RETURN] = sizeof(return_statement_t),
239 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
240 [STATEMENT_IF] = sizeof(if_statement_t),
241 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
242 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
243 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
244 [STATEMENT_BREAK] = sizeof(statement_base_t),
245 [STATEMENT_GOTO] = sizeof(goto_statement_t),
246 [STATEMENT_LABEL] = sizeof(label_statement_t),
247 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
248 [STATEMENT_WHILE] = sizeof(while_statement_t),
249 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
250 [STATEMENT_FOR] = sizeof(for_statement_t),
251 [STATEMENT_ASM] = sizeof(asm_statement_t),
252 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
253 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
255 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
256 assert(sizes[kind] != 0);
261 * Returns the size of an expression node.
263 * @param kind the expression kind
265 static size_t get_expression_struct_size(expression_kind_t kind)
267 static const size_t sizes[] = {
268 [EXPR_INVALID] = sizeof(expression_base_t),
269 [EXPR_REFERENCE] = sizeof(reference_expression_t),
270 [EXPR_CONST] = sizeof(const_expression_t),
271 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
272 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
273 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
274 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
275 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
276 [EXPR_CALL] = sizeof(call_expression_t),
277 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
278 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
279 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
280 [EXPR_SELECT] = sizeof(select_expression_t),
281 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
282 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
283 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
284 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
285 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
286 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
287 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
288 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
289 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
290 [EXPR_VA_START] = sizeof(va_start_expression_t),
291 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
292 [EXPR_STATEMENT] = sizeof(statement_expression_t),
294 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
295 return sizes[EXPR_UNARY_FIRST];
297 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
298 return sizes[EXPR_BINARY_FIRST];
300 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
301 assert(sizes[kind] != 0);
306 * Allocate a statement node of given kind and initialize all
309 static statement_t *allocate_statement_zero(statement_kind_t kind)
311 size_t size = get_statement_struct_size(kind);
312 statement_t *res = allocate_ast_zero(size);
314 res->base.kind = kind;
319 * Allocate an expression node of given kind and initialize all
322 static expression_t *allocate_expression_zero(expression_kind_t kind)
324 size_t size = get_expression_struct_size(kind);
325 expression_t *res = allocate_ast_zero(size);
327 res->base.kind = kind;
328 res->base.type = type_error_type;
333 * Creates a new invalid expression.
335 static expression_t *create_invalid_expression(void)
337 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
338 expression->base.source_position = token.source_position;
343 * Creates a new invalid statement.
345 static statement_t *create_invalid_statement(void)
347 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
348 statement->base.source_position = token.source_position;
353 * Allocate a new empty statement.
355 static statement_t *create_empty_statement(void)
357 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
358 statement->base.source_position = token.source_position;
363 * Returns the size of a type node.
365 * @param kind the type kind
367 static size_t get_type_struct_size(type_kind_t kind)
369 static const size_t sizes[] = {
370 [TYPE_ATOMIC] = sizeof(atomic_type_t),
371 [TYPE_COMPLEX] = sizeof(complex_type_t),
372 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
373 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
374 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
375 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
376 [TYPE_ENUM] = sizeof(enum_type_t),
377 [TYPE_FUNCTION] = sizeof(function_type_t),
378 [TYPE_POINTER] = sizeof(pointer_type_t),
379 [TYPE_ARRAY] = sizeof(array_type_t),
380 [TYPE_BUILTIN] = sizeof(builtin_type_t),
381 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
382 [TYPE_TYPEOF] = sizeof(typeof_type_t),
384 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
385 assert(kind <= TYPE_TYPEOF);
386 assert(sizes[kind] != 0);
391 * Allocate a type node of given kind and initialize all
394 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
396 size_t size = get_type_struct_size(kind);
397 type_t *res = obstack_alloc(type_obst, size);
398 memset(res, 0, size);
400 res->base.kind = kind;
401 res->base.source_position = *source_position;
406 * Returns the size of an initializer node.
408 * @param kind the initializer kind
410 static size_t get_initializer_size(initializer_kind_t kind)
412 static const size_t sizes[] = {
413 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
414 [INITIALIZER_STRING] = sizeof(initializer_string_t),
415 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
416 [INITIALIZER_LIST] = sizeof(initializer_list_t),
417 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
419 assert(kind < sizeof(sizes) / sizeof(*sizes));
420 assert(sizes[kind] != 0);
425 * Allocate an initializer node of given kind and initialize all
428 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
430 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
437 * Free a type from the type obstack.
439 static void free_type(void *type)
441 obstack_free(type_obst, type);
445 * Returns the index of the top element of the environment stack.
447 static size_t environment_top(void)
449 return ARR_LEN(environment_stack);
453 * Returns the index of the top element of the label stack.
455 static size_t label_top(void)
457 return ARR_LEN(label_stack);
461 * Return the next token.
463 static inline void next_token(void)
465 token = lookahead_buffer[lookahead_bufpos];
466 lookahead_buffer[lookahead_bufpos] = lexer_token;
469 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
472 print_token(stderr, &token);
473 fprintf(stderr, "\n");
478 * Return the next token with a given lookahead.
480 static inline const token_t *look_ahead(int num)
482 assert(num > 0 && num <= MAX_LOOKAHEAD);
483 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
484 return &lookahead_buffer[pos];
488 * Adds a token to the token anchor set (a multi-set).
490 static void add_anchor_token(int token_type) {
491 assert(0 <= token_type && token_type < T_LAST_TOKEN);
492 ++token_anchor_set[token_type];
495 static int save_and_reset_anchor_state(int token_type) {
496 assert(0 <= token_type && token_type < T_LAST_TOKEN);
497 int count = token_anchor_set[token_type];
498 token_anchor_set[token_type] = 0;
502 static void restore_anchor_state(int token_type, int count) {
503 assert(0 <= token_type && token_type < T_LAST_TOKEN);
504 token_anchor_set[token_type] = count;
508 * Remove a token from the token anchor set (a multi-set).
510 static void rem_anchor_token(int token_type) {
511 assert(0 <= token_type && token_type < T_LAST_TOKEN);
512 --token_anchor_set[token_type];
515 static bool at_anchor(void) {
518 return token_anchor_set[token.type];
522 * Eat tokens until a matching token is found.
524 static void eat_until_matching_token(int type) {
525 unsigned parenthesis_count = 0;
526 unsigned brace_count = 0;
527 unsigned bracket_count = 0;
528 int end_token = type;
537 while(token.type != end_token ||
538 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
542 case '(': ++parenthesis_count; break;
543 case '{': ++brace_count; break;
544 case '[': ++bracket_count; break;
546 if(parenthesis_count > 0)
554 if(bracket_count > 0)
565 * Eat input tokens until an anchor is found.
567 static void eat_until_anchor(void) {
568 if(token.type == T_EOF)
570 while(token_anchor_set[token.type] == 0) {
571 if(token.type == '(' || token.type == '{' || token.type == '[')
572 eat_until_matching_token(token.type);
573 if(token.type == T_EOF)
579 static void eat_block(void) {
580 eat_until_matching_token('{');
581 if(token.type == '}')
586 * eat all token until a ';' is reached or a stop token is found.
588 static void eat_statement(void) {
589 eat_until_matching_token(';');
590 if(token.type == ';')
594 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
597 * Report a parse error because an expected token was not found.
600 #if defined __GNUC__ && __GNUC__ >= 4
601 __attribute__((sentinel))
603 void parse_error_expected(const char *message, ...)
605 if(message != NULL) {
606 errorf(HERE, "%s", message);
609 va_start(ap, message);
610 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
615 * Report a type error.
617 static void type_error(const char *msg, const source_position_t *source_position,
620 errorf(source_position, "%s, but found type '%T'", msg, type);
624 * Report an incompatible type.
626 static void type_error_incompatible(const char *msg,
627 const source_position_t *source_position, type_t *type1, type_t *type2)
629 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
634 * Expect the the current token is the expected token.
635 * If not, generate an error, eat the current statement,
636 * and goto the end_error label.
638 #define expect(expected) \
640 if(UNLIKELY(token.type != (expected))) { \
641 parse_error_expected(NULL, (expected), NULL); \
642 add_anchor_token(expected); \
643 eat_until_anchor(); \
644 if (token.type == expected) \
646 rem_anchor_token(expected); \
652 static void set_scope(scope_t *new_scope)
655 scope->last_declaration = last_declaration;
659 last_declaration = new_scope->last_declaration;
663 * Search a symbol in a given namespace and returns its declaration or
664 * NULL if this symbol was not found.
666 static declaration_t *get_declaration(const symbol_t *const symbol,
667 const namespace_t namespc)
669 declaration_t *declaration = symbol->declaration;
670 for( ; declaration != NULL; declaration = declaration->symbol_next) {
671 if(declaration->namespc == namespc)
679 * pushs an environment_entry on the environment stack and links the
680 * corresponding symbol to the new entry
682 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
684 symbol_t *symbol = declaration->symbol;
685 namespace_t namespc = (namespace_t) declaration->namespc;
687 /* replace/add declaration into declaration list of the symbol */
688 declaration_t *iter = symbol->declaration;
690 symbol->declaration = declaration;
692 declaration_t *iter_last = NULL;
693 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
694 /* replace an entry? */
695 if(iter->namespc == namespc) {
696 if(iter_last == NULL) {
697 symbol->declaration = declaration;
699 iter_last->symbol_next = declaration;
701 declaration->symbol_next = iter->symbol_next;
706 assert(iter_last->symbol_next == NULL);
707 iter_last->symbol_next = declaration;
711 /* remember old declaration */
713 entry.symbol = symbol;
714 entry.old_declaration = iter;
715 entry.namespc = (unsigned short) namespc;
716 ARR_APP1(stack_entry_t, *stack_ptr, entry);
719 static void environment_push(declaration_t *declaration)
721 assert(declaration->source_position.input_name != NULL);
722 assert(declaration->parent_scope != NULL);
723 stack_push(&environment_stack, declaration);
726 static void label_push(declaration_t *declaration)
728 declaration->parent_scope = ¤t_function->scope;
729 stack_push(&label_stack, declaration);
733 * pops symbols from the environment stack until @p new_top is the top element
735 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
737 stack_entry_t *stack = *stack_ptr;
738 size_t top = ARR_LEN(stack);
741 assert(new_top <= top);
745 for(i = top; i > new_top; --i) {
746 stack_entry_t *entry = &stack[i - 1];
748 declaration_t *old_declaration = entry->old_declaration;
749 symbol_t *symbol = entry->symbol;
750 namespace_t namespc = (namespace_t)entry->namespc;
752 /* replace/remove declaration */
753 declaration_t *declaration = symbol->declaration;
754 assert(declaration != NULL);
755 if(declaration->namespc == namespc) {
756 if(old_declaration == NULL) {
757 symbol->declaration = declaration->symbol_next;
759 symbol->declaration = old_declaration;
762 declaration_t *iter_last = declaration;
763 declaration_t *iter = declaration->symbol_next;
764 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
765 /* replace an entry? */
766 if(iter->namespc == namespc) {
767 assert(iter_last != NULL);
768 iter_last->symbol_next = old_declaration;
769 if(old_declaration != NULL) {
770 old_declaration->symbol_next = iter->symbol_next;
775 assert(iter != NULL);
779 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
782 static void environment_pop_to(size_t new_top)
784 stack_pop_to(&environment_stack, new_top);
787 static void label_pop_to(size_t new_top)
789 stack_pop_to(&label_stack, new_top);
793 static int get_rank(const type_t *type)
795 assert(!is_typeref(type));
796 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
797 * and esp. footnote 108). However we can't fold constants (yet), so we
798 * can't decide whether unsigned int is possible, while int always works.
799 * (unsigned int would be preferable when possible... for stuff like
800 * struct { enum { ... } bla : 4; } ) */
801 if(type->kind == TYPE_ENUM)
802 return ATOMIC_TYPE_INT;
804 assert(type->kind == TYPE_ATOMIC);
805 return type->atomic.akind;
808 static type_t *promote_integer(type_t *type)
810 if(type->kind == TYPE_BITFIELD)
811 type = type->bitfield.base_type;
813 if(get_rank(type) < ATOMIC_TYPE_INT)
820 * Create a cast expression.
822 * @param expression the expression to cast
823 * @param dest_type the destination type
825 static expression_t *create_cast_expression(expression_t *expression,
828 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
830 cast->unary.value = expression;
831 cast->base.type = dest_type;
837 * Check if a given expression represents the 0 pointer constant.
839 static bool is_null_pointer_constant(const expression_t *expression)
841 /* skip void* cast */
842 if(expression->kind == EXPR_UNARY_CAST
843 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
844 expression = expression->unary.value;
847 /* TODO: not correct yet, should be any constant integer expression
848 * which evaluates to 0 */
849 if (expression->kind != EXPR_CONST)
852 type_t *const type = skip_typeref(expression->base.type);
853 if (!is_type_integer(type))
856 return expression->conste.v.int_value == 0;
860 * Create an implicit cast expression.
862 * @param expression the expression to cast
863 * @param dest_type the destination type
865 static expression_t *create_implicit_cast(expression_t *expression,
868 type_t *const source_type = expression->base.type;
870 if (source_type == dest_type)
873 return create_cast_expression(expression, dest_type);
876 typedef enum assign_error_t {
878 ASSIGN_ERROR_INCOMPATIBLE,
879 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
880 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
881 ASSIGN_WARNING_POINTER_FROM_INT,
882 ASSIGN_WARNING_INT_FROM_POINTER
885 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
886 const expression_t *const right,
888 const source_position_t *source_position)
890 type_t *const orig_type_right = right->base.type;
891 type_t *const type_left = skip_typeref(orig_type_left);
892 type_t *const type_right = skip_typeref(orig_type_right);
897 case ASSIGN_ERROR_INCOMPATIBLE:
898 errorf(source_position,
899 "destination type '%T' in %s is incompatible with type '%T'",
900 orig_type_left, context, orig_type_right);
903 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
904 type_t *points_to_left
905 = skip_typeref(type_left->pointer.points_to);
906 type_t *points_to_right
907 = skip_typeref(type_right->pointer.points_to);
909 /* the left type has all qualifiers from the right type */
910 unsigned missing_qualifiers
911 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
912 errorf(source_position,
913 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type",
914 orig_type_left, context, orig_type_right, missing_qualifiers);
918 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
919 warningf(source_position,
920 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
921 orig_type_left, context, right, orig_type_right);
924 case ASSIGN_WARNING_POINTER_FROM_INT:
925 warningf(source_position,
926 "%s makes integer '%T' from pointer '%T' without a cast",
927 context, orig_type_left, orig_type_right);
930 case ASSIGN_WARNING_INT_FROM_POINTER:
931 warningf(source_position,
932 "%s makes integer '%T' from pointer '%T' without a cast",
933 context, orig_type_left, orig_type_right);
937 panic("invalid error value");
941 /** Implements the rules from § 6.5.16.1 */
942 static assign_error_t semantic_assign(type_t *orig_type_left,
943 const expression_t *const right)
945 type_t *const orig_type_right = right->base.type;
946 type_t *const type_left = skip_typeref(orig_type_left);
947 type_t *const type_right = skip_typeref(orig_type_right);
949 if(is_type_pointer(type_left)) {
950 if(is_null_pointer_constant(right)) {
951 return ASSIGN_SUCCESS;
952 } else if(is_type_pointer(type_right)) {
953 type_t *points_to_left
954 = skip_typeref(type_left->pointer.points_to);
955 type_t *points_to_right
956 = skip_typeref(type_right->pointer.points_to);
958 /* the left type has all qualifiers from the right type */
959 unsigned missing_qualifiers
960 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
961 if(missing_qualifiers != 0) {
962 return ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
965 points_to_left = get_unqualified_type(points_to_left);
966 points_to_right = get_unqualified_type(points_to_right);
968 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
969 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
970 return ASSIGN_SUCCESS;
973 if (!types_compatible(points_to_left, points_to_right)) {
974 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
977 return ASSIGN_SUCCESS;
978 } else if(is_type_integer(type_right)) {
979 return ASSIGN_WARNING_POINTER_FROM_INT;
981 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
982 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
983 && is_type_pointer(type_right))) {
984 return ASSIGN_SUCCESS;
985 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
986 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
987 type_t *const unqual_type_left = get_unqualified_type(type_left);
988 type_t *const unqual_type_right = get_unqualified_type(type_right);
989 if (types_compatible(unqual_type_left, unqual_type_right)) {
990 return ASSIGN_SUCCESS;
992 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
993 return ASSIGN_WARNING_INT_FROM_POINTER;
996 if (!is_type_valid(type_left) || !is_type_valid(type_right))
997 return ASSIGN_SUCCESS;
999 return ASSIGN_ERROR_INCOMPATIBLE;
1002 static expression_t *parse_constant_expression(void)
1004 /* start parsing at precedence 7 (conditional expression) */
1005 expression_t *result = parse_sub_expression(7);
1007 if(!is_constant_expression(result)) {
1008 errorf(&result->base.source_position,
1009 "expression '%E' is not constant\n", result);
1015 static expression_t *parse_assignment_expression(void)
1017 /* start parsing at precedence 2 (assignment expression) */
1018 return parse_sub_expression(2);
1021 static type_t *make_global_typedef(const char *name, type_t *type)
1023 symbol_t *const symbol = symbol_table_insert(name);
1025 declaration_t *const declaration = allocate_declaration_zero();
1026 declaration->namespc = NAMESPACE_NORMAL;
1027 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1028 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1029 declaration->type = type;
1030 declaration->symbol = symbol;
1031 declaration->source_position = builtin_source_position;
1033 record_declaration(declaration);
1035 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1036 typedef_type->typedeft.declaration = declaration;
1038 return typedef_type;
1041 static string_t parse_string_literals(void)
1043 assert(token.type == T_STRING_LITERAL);
1044 string_t result = token.v.string;
1048 while (token.type == T_STRING_LITERAL) {
1049 result = concat_strings(&result, &token.v.string);
1056 static const char *gnu_attribute_names[GNU_AK_LAST] = {
1057 [GNU_AK_CONST] = "const",
1058 [GNU_AK_VOLATILE] = "volatile",
1059 [GNU_AK_CDECL] = "cdecl",
1060 [GNU_AK_STDCALL] = "stdcall",
1061 [GNU_AK_FASTCALL] = "fastcall",
1062 [GNU_AK_DEPRECATED] = "deprecated",
1063 [GNU_AK_NOINLINE] = "noinline",
1064 [GNU_AK_NORETURN] = "noreturn",
1065 [GNU_AK_NAKED] = "naked",
1066 [GNU_AK_PURE] = "pure",
1067 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1068 [GNU_AK_MALLOC] = "malloc",
1069 [GNU_AK_WEAK] = "weak",
1070 [GNU_AK_CONSTRUCTOR] = "constructor",
1071 [GNU_AK_DESTRUCTOR] = "destructor",
1072 [GNU_AK_NOTHROW] = "nothrow",
1073 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1074 [GNU_AK_COMMON] = "common",
1075 [GNU_AK_NOCOMMON] = "nocommon",
1076 [GNU_AK_PACKED] = "packed",
1077 [GNU_AK_SHARED] = "shared",
1078 [GNU_AK_NOTSHARED] = "notshared",
1079 [GNU_AK_USED] = "used",
1080 [GNU_AK_UNUSED] = "unused",
1081 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1082 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1083 [GNU_AK_LONGCALL] = "longcall",
1084 [GNU_AK_SHORTCALL] = "shortcall",
1085 [GNU_AK_LONG_CALL] = "long_call",
1086 [GNU_AK_SHORT_CALL] = "short_call",
1087 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1088 [GNU_AK_INTERRUPT] = "interrupt",
1089 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1090 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1091 [GNU_AK_NESTING] = "nesting",
1092 [GNU_AK_NEAR] = "near",
1093 [GNU_AK_FAR] = "far",
1094 [GNU_AK_SIGNAL] = "signal",
1095 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1096 [GNU_AK_TINY_DATA] = "tiny_data",
1097 [GNU_AK_SAVEALL] = "saveall",
1098 [GNU_AK_FLATTEN] = "flatten",
1099 [GNU_AK_SSEREGPARM] = "sseregparm",
1100 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1101 [GNU_AK_RETURN_TWICE] = "return_twice",
1102 [GNU_AK_MAY_ALIAS] = "may_alias",
1103 [GNU_AK_MS_STRUCT] = "ms_struct",
1104 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1105 [GNU_AK_DLLIMPORT] = "dllimport",
1106 [GNU_AK_DLLEXPORT] = "dllexport",
1107 [GNU_AK_ALIGNED] = "aligned",
1108 [GNU_AK_ALIAS] = "alias",
1109 [GNU_AK_SECTION] = "section",
1110 [GNU_AK_FORMAT] = "format",
1111 [GNU_AK_FORMAT_ARG] = "format_arg",
1112 [GNU_AK_WEAKREF] = "weakref",
1113 [GNU_AK_NONNULL] = "nonnull",
1114 [GNU_AK_TLS_MODEL] = "tls_model",
1115 [GNU_AK_VISIBILITY] = "visibility",
1116 [GNU_AK_REGPARM] = "regparm",
1117 [GNU_AK_MODE] = "mode",
1118 [GNU_AK_MODEL] = "model",
1119 [GNU_AK_TRAP_EXIT] = "trap_exit",
1120 [GNU_AK_SP_SWITCH] = "sp_switch",
1121 [GNU_AK_SENTINEL] = "sentinel"
1125 * compare two string, ignoring double underscores on the second.
1127 static int strcmp_underscore(const char *s1, const char *s2) {
1128 if(s2[0] == '_' && s2[1] == '_') {
1129 size_t len2 = strlen(s2);
1130 size_t len1 = strlen(s1);
1131 if(len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1132 return strncmp(s1, s2+2, len2-4);
1136 return strcmp(s1, s2);
1140 * Allocate a new gnu temporal attribute.
1142 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1143 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1144 attribute->kind = kind;
1145 attribute->next = NULL;
1146 attribute->invalid = false;
1147 attribute->have_arguments = false;
1153 * parse one constant expression argument.
1155 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1156 expression_t *expression;
1157 add_anchor_token(')');
1158 expression = parse_constant_expression();
1159 rem_anchor_token(')');
1164 attribute->invalid = true;
1168 * parse a list of constant expressions arguments.
1170 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1171 expression_t *expression;
1172 add_anchor_token(')');
1173 add_anchor_token(',');
1175 expression = parse_constant_expression();
1176 if(token.type != ',')
1180 rem_anchor_token(',');
1181 rem_anchor_token(')');
1186 attribute->invalid = true;
1190 * parse one string literal argument.
1192 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1195 add_anchor_token('(');
1196 if(token.type != T_STRING_LITERAL) {
1197 parse_error_expected("while parsing attribute directive",
1198 T_STRING_LITERAL, NULL);
1201 *string = parse_string_literals();
1202 rem_anchor_token('(');
1206 attribute->invalid = true;
1210 * parse one tls model.
1212 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1213 static const char *tls_models[] = {
1219 string_t string = { NULL, 0 };
1220 parse_gnu_attribute_string_arg(attribute, &string);
1221 if(string.begin != NULL) {
1222 for(size_t i = 0; i < 4; ++i) {
1223 if(strcmp(tls_models[i], string.begin) == 0) {
1224 attribute->u.value = i;
1228 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1230 attribute->invalid = true;
1234 * parse one tls model.
1236 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1237 static const char *visibilities[] = {
1243 string_t string = { NULL, 0 };
1244 parse_gnu_attribute_string_arg(attribute, &string);
1245 if(string.begin != NULL) {
1246 for(size_t i = 0; i < 4; ++i) {
1247 if(strcmp(visibilities[i], string.begin) == 0) {
1248 attribute->u.value = i;
1252 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1254 attribute->invalid = true;
1258 * parse one (code) model.
1260 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1261 static const char *visibilities[] = {
1266 string_t string = { NULL, 0 };
1267 parse_gnu_attribute_string_arg(attribute, &string);
1268 if(string.begin != NULL) {
1269 for(int i = 0; i < 3; ++i) {
1270 if(strcmp(visibilities[i], string.begin) == 0) {
1271 attribute->u.value = i;
1275 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1277 attribute->invalid = true;
1280 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1282 /* TODO: find out what is allowed here... */
1284 /* at least: byte, word, pointer, list of machine modes
1285 * __XXX___ is interpreted as XXX */
1286 add_anchor_token(')');
1287 expect(T_IDENTIFIER);
1288 rem_anchor_token(')');
1292 attribute->invalid = true;
1296 * parse one interrupt argument.
1298 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1299 static const char *interrupts[] = {
1306 string_t string = { NULL, 0 };
1307 parse_gnu_attribute_string_arg(attribute, &string);
1308 if(string.begin != NULL) {
1309 for(size_t i = 0; i < 5; ++i) {
1310 if(strcmp(interrupts[i], string.begin) == 0) {
1311 attribute->u.value = i;
1315 errorf(HERE, "'%s' is not an interrupt", string.begin);
1317 attribute->invalid = true;
1321 * parse ( identifier, const expression, const expression )
1323 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1324 static const char *format_names[] = {
1332 if(token.type != T_IDENTIFIER) {
1333 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1336 const char *name = token.v.symbol->string;
1337 for(i = 0; i < 4; ++i) {
1338 if(strcmp_underscore(format_names[i], name) == 0)
1342 if(warning.attribute)
1343 warningf(HERE, "'%s' is an unrecognized format function type", name);
1348 add_anchor_token(')');
1349 add_anchor_token(',');
1350 parse_constant_expression();
1351 rem_anchor_token(',');
1352 rem_anchor_token('(');
1355 add_anchor_token(')');
1356 parse_constant_expression();
1357 rem_anchor_token('(');
1361 attribute->u.value = true;
1364 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1366 if(!attribute->have_arguments)
1369 /* should have no arguments */
1370 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1371 eat_until_matching_token('(');
1372 /* we have already consumed '(', so we stop before ')', eat it */
1374 attribute->invalid = true;
1378 * Parse one GNU attribute.
1380 * Note that attribute names can be specified WITH or WITHOUT
1381 * double underscores, ie const or __const__.
1383 * The following attributes are parsed without arguments
1408 * no_instrument_function
1409 * warn_unused_result
1426 * externally_visible
1434 * The following attributes are parsed with arguments
1435 * aligned( const expression )
1436 * alias( string literal )
1437 * section( string literal )
1438 * format( identifier, const expression, const expression )
1439 * format_arg( const expression )
1440 * tls_model( string literal )
1441 * visibility( string literal )
1442 * regparm( const expression )
1443 * model( string leteral )
1444 * trap_exit( const expression )
1445 * sp_switch( string literal )
1447 * The following attributes might have arguments
1448 * weak_ref( string literal )
1449 * non_null( const expression // ',' )
1450 * interrupt( string literal )
1451 * sentinel( constant expression )
1453 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1455 gnu_attribute_t *head = *attributes;
1456 gnu_attribute_t *last = *attributes;
1457 decl_modifiers_t modifiers = 0;
1458 gnu_attribute_t *attribute;
1460 eat(T___attribute__);
1464 if(token.type != ')') {
1465 /* find the end of the list */
1467 while(last->next != NULL)
1471 /* non-empty attribute list */
1474 if (token.type == T_const) {
1476 } else if(token.type == T_volatile) {
1478 } else if(token.type == T_cdecl) {
1479 /* __attribute__((cdecl)), WITH ms mode */
1481 } else if (token.type == T_IDENTIFIER) {
1482 const symbol_t *sym = token.v.symbol;
1485 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1492 for(i = 0; i < GNU_AK_LAST; ++i) {
1493 if(strcmp_underscore(gnu_attribute_names[i], name) == 0)
1496 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1499 if(kind == GNU_AK_LAST) {
1500 if(warning.attribute)
1501 warningf(HERE, "'%s' attribute directive ignored", name);
1503 /* skip possible arguments */
1504 if(token.type == '(') {
1505 eat_until_matching_token(')');
1508 /* check for arguments */
1509 attribute = allocate_gnu_attribute(kind);
1510 if(token.type == '(') {
1512 if(token.type == ')') {
1513 /* empty args are allowed */
1516 attribute->have_arguments = true;
1521 case GNU_AK_VOLATILE:
1523 case GNU_AK_STDCALL:
1524 case GNU_AK_FASTCALL:
1525 case GNU_AK_DEPRECATED:
1530 case GNU_AK_NOCOMMON:
1532 case GNU_AK_NOTSHARED:
1535 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1536 case GNU_AK_WARN_UNUSED_RESULT:
1537 case GNU_AK_LONGCALL:
1538 case GNU_AK_SHORTCALL:
1539 case GNU_AK_LONG_CALL:
1540 case GNU_AK_SHORT_CALL:
1541 case GNU_AK_FUNCTION_VECTOR:
1542 case GNU_AK_INTERRUPT_HANDLER:
1543 case GNU_AK_NMI_HANDLER:
1544 case GNU_AK_NESTING:
1548 case GNU_AK_EIGTHBIT_DATA:
1549 case GNU_AK_TINY_DATA:
1550 case GNU_AK_SAVEALL:
1551 case GNU_AK_FLATTEN:
1552 case GNU_AK_SSEREGPARM:
1553 case GNU_AK_EXTERNALLY_VISIBLE:
1554 case GNU_AK_RETURN_TWICE:
1555 case GNU_AK_MAY_ALIAS:
1556 case GNU_AK_MS_STRUCT:
1557 case GNU_AK_GCC_STRUCT:
1558 check_no_argument(attribute, name);
1562 check_no_argument(attribute, name);
1563 modifiers |= DM_PURE;
1566 case GNU_AK_ALWAYS_INLINE:
1567 check_no_argument(attribute, name);
1568 modifiers |= DM_FORCEINLINE;
1571 case GNU_AK_DLLIMPORT:
1572 check_no_argument(attribute, name);
1573 modifiers |= DM_DLLIMPORT;
1576 case GNU_AK_DLLEXPORT:
1577 check_no_argument(attribute, name);
1578 modifiers |= DM_DLLEXPORT;
1582 check_no_argument(attribute, name);
1583 modifiers |= DM_PACKED;
1586 case GNU_AK_NOINLINE:
1587 check_no_argument(attribute, name);
1588 modifiers |= DM_NOINLINE;
1591 case GNU_AK_NORETURN:
1592 check_no_argument(attribute, name);
1593 modifiers |= DM_NORETURN;
1596 case GNU_AK_NOTHROW:
1597 check_no_argument(attribute, name);
1598 modifiers |= DM_NOTHROW;
1601 case GNU_AK_TRANSPARENT_UNION:
1602 check_no_argument(attribute, name);
1603 modifiers |= DM_TRANSPARENT_UNION;
1606 case GNU_AK_CONSTRUCTOR:
1607 check_no_argument(attribute, name);
1608 modifiers |= DM_CONSTRUCTOR;
1611 case GNU_AK_DESTRUCTOR:
1612 check_no_argument(attribute, name);
1613 modifiers |= DM_DESTRUCTOR;
1616 case GNU_AK_ALIGNED:
1617 case GNU_AK_FORMAT_ARG:
1618 case GNU_AK_REGPARM:
1619 case GNU_AK_TRAP_EXIT:
1620 if(!attribute->have_arguments) {
1621 /* should have arguments */
1622 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1623 attribute->invalid = true;
1625 parse_gnu_attribute_const_arg(attribute);
1628 case GNU_AK_SECTION:
1629 case GNU_AK_SP_SWITCH:
1630 if(!attribute->have_arguments) {
1631 /* should have arguments */
1632 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1633 attribute->invalid = true;
1635 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1638 if(!attribute->have_arguments) {
1639 /* should have arguments */
1640 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1641 attribute->invalid = true;
1643 parse_gnu_attribute_format_args(attribute);
1645 case GNU_AK_WEAKREF:
1646 /* may have one string argument */
1647 if(attribute->have_arguments)
1648 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1650 case GNU_AK_NONNULL:
1651 if(attribute->have_arguments)
1652 parse_gnu_attribute_const_arg_list(attribute);
1654 case GNU_AK_TLS_MODEL:
1655 if(!attribute->have_arguments) {
1656 /* should have arguments */
1657 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1659 parse_gnu_attribute_tls_model_arg(attribute);
1661 case GNU_AK_VISIBILITY:
1662 if(!attribute->have_arguments) {
1663 /* should have arguments */
1664 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1666 parse_gnu_attribute_visibility_arg(attribute);
1669 if(!attribute->have_arguments) {
1670 /* should have arguments */
1671 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1673 parse_gnu_attribute_model_arg(attribute);
1677 if(!attribute->have_arguments) {
1678 /* should have arguments */
1679 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1681 parse_gnu_attribute_mode_arg(attribute);
1684 case GNU_AK_INTERRUPT:
1685 /* may have one string argument */
1686 if(attribute->have_arguments)
1687 parse_gnu_attribute_interrupt_arg(attribute);
1689 case GNU_AK_SENTINEL:
1690 /* may have one string argument */
1691 if(attribute->have_arguments)
1692 parse_gnu_attribute_const_arg(attribute);
1695 /* already handled */
1699 if(attribute != NULL) {
1701 last->next = attribute;
1704 head = last = attribute;
1708 if(token.type != ',')
1722 * Parse GNU attributes.
1724 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1726 decl_modifiers_t modifiers = 0;
1729 switch(token.type) {
1730 case T___attribute__: {
1731 modifiers |= parse_gnu_attribute(attributes);
1737 if(token.type != T_STRING_LITERAL) {
1738 parse_error_expected("while parsing assembler attribute",
1739 T_STRING_LITERAL, NULL);
1740 eat_until_matching_token('(');
1743 parse_string_literals();
1748 goto attributes_finished;
1752 attributes_finished:
1757 static designator_t *parse_designation(void)
1759 designator_t *result = NULL;
1760 designator_t *last = NULL;
1763 designator_t *designator;
1764 switch(token.type) {
1766 designator = allocate_ast_zero(sizeof(designator[0]));
1767 designator->source_position = token.source_position;
1769 add_anchor_token(']');
1770 designator->array_index = parse_constant_expression();
1771 rem_anchor_token(']');
1775 designator = allocate_ast_zero(sizeof(designator[0]));
1776 designator->source_position = token.source_position;
1778 if(token.type != T_IDENTIFIER) {
1779 parse_error_expected("while parsing designator",
1780 T_IDENTIFIER, NULL);
1783 designator->symbol = token.v.symbol;
1791 assert(designator != NULL);
1793 last->next = designator;
1795 result = designator;
1803 static initializer_t *initializer_from_string(array_type_t *type,
1804 const string_t *const string)
1806 /* TODO: check len vs. size of array type */
1809 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1810 initializer->string.string = *string;
1815 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1816 wide_string_t *const string)
1818 /* TODO: check len vs. size of array type */
1821 initializer_t *const initializer =
1822 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1823 initializer->wide_string.string = *string;
1829 * Build an initializer from a given expression.
1831 static initializer_t *initializer_from_expression(type_t *orig_type,
1832 expression_t *expression)
1834 /* TODO check that expression is a constant expression */
1836 /* § 6.7.8.14/15 char array may be initialized by string literals */
1837 type_t *type = skip_typeref(orig_type);
1838 type_t *expr_type_orig = expression->base.type;
1839 type_t *expr_type = skip_typeref(expr_type_orig);
1840 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1841 array_type_t *const array_type = &type->array;
1842 type_t *const element_type = skip_typeref(array_type->element_type);
1844 if (element_type->kind == TYPE_ATOMIC) {
1845 atomic_type_kind_t akind = element_type->atomic.akind;
1846 switch (expression->kind) {
1847 case EXPR_STRING_LITERAL:
1848 if (akind == ATOMIC_TYPE_CHAR
1849 || akind == ATOMIC_TYPE_SCHAR
1850 || akind == ATOMIC_TYPE_UCHAR) {
1851 return initializer_from_string(array_type,
1852 &expression->string.value);
1855 case EXPR_WIDE_STRING_LITERAL: {
1856 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1857 if (get_unqualified_type(element_type) == bare_wchar_type) {
1858 return initializer_from_wide_string(array_type,
1859 &expression->wide_string.value);
1869 assign_error_t error = semantic_assign(type, expression);
1870 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1872 report_assign_error(error, type, expression, "initializer",
1873 &expression->base.source_position);
1875 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1876 result->value.value = create_implicit_cast(expression, type);
1882 * Checks if a given expression can be used as an constant initializer.
1884 static bool is_initializer_constant(const expression_t *expression)
1886 return is_constant_expression(expression)
1887 || is_address_constant(expression);
1891 * Parses an scalar initializer.
1893 * § 6.7.8.11; eat {} without warning
1895 static initializer_t *parse_scalar_initializer(type_t *type,
1896 bool must_be_constant)
1898 /* there might be extra {} hierarchies */
1900 while(token.type == '{') {
1903 warningf(HERE, "extra curly braces around scalar initializer");
1908 expression_t *expression = parse_assignment_expression();
1909 if(must_be_constant && !is_initializer_constant(expression)) {
1910 errorf(&expression->base.source_position,
1911 "Initialisation expression '%E' is not constant\n",
1915 initializer_t *initializer = initializer_from_expression(type, expression);
1917 if(initializer == NULL) {
1918 errorf(&expression->base.source_position,
1919 "expression '%E' (type '%T') doesn't match expected type '%T'",
1920 expression, expression->base.type, type);
1925 bool additional_warning_displayed = false;
1927 if(token.type == ',') {
1930 if(token.type != '}') {
1931 if(!additional_warning_displayed) {
1932 warningf(HERE, "additional elements in scalar initializer");
1933 additional_warning_displayed = true;
1944 * An entry in the type path.
1946 typedef struct type_path_entry_t type_path_entry_t;
1947 struct type_path_entry_t {
1948 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1950 size_t index; /**< For array types: the current index. */
1951 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1956 * A type path expression a position inside compound or array types.
1958 typedef struct type_path_t type_path_t;
1959 struct type_path_t {
1960 type_path_entry_t *path; /**< An flexible array containing the current path. */
1961 type_t *top_type; /**< type of the element the path points */
1962 size_t max_index; /**< largest index in outermost array */
1966 * Prints a type path for debugging.
1968 static __attribute__((unused)) void debug_print_type_path(
1969 const type_path_t *path)
1971 size_t len = ARR_LEN(path->path);
1973 for(size_t i = 0; i < len; ++i) {
1974 const type_path_entry_t *entry = & path->path[i];
1976 type_t *type = skip_typeref(entry->type);
1977 if(is_type_compound(type)) {
1978 /* in gcc mode structs can have no members */
1979 if(entry->v.compound_entry == NULL) {
1983 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1984 } else if(is_type_array(type)) {
1985 fprintf(stderr, "[%zd]", entry->v.index);
1987 fprintf(stderr, "-INVALID-");
1990 if(path->top_type != NULL) {
1991 fprintf(stderr, " (");
1992 print_type(path->top_type);
1993 fprintf(stderr, ")");
1998 * Return the top type path entry, ie. in a path
1999 * (type).a.b returns the b.
2001 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2003 size_t len = ARR_LEN(path->path);
2005 return &path->path[len-1];
2009 * Enlarge the type path by an (empty) element.
2011 static type_path_entry_t *append_to_type_path(type_path_t *path)
2013 size_t len = ARR_LEN(path->path);
2014 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2016 type_path_entry_t *result = & path->path[len];
2017 memset(result, 0, sizeof(result[0]));
2022 * Descending into a sub-type. Enter the scope of the current
2025 static void descend_into_subtype(type_path_t *path)
2027 type_t *orig_top_type = path->top_type;
2028 type_t *top_type = skip_typeref(orig_top_type);
2030 assert(is_type_compound(top_type) || is_type_array(top_type));
2032 type_path_entry_t *top = append_to_type_path(path);
2033 top->type = top_type;
2035 if(is_type_compound(top_type)) {
2036 declaration_t *declaration = top_type->compound.declaration;
2037 declaration_t *entry = declaration->scope.declarations;
2038 top->v.compound_entry = entry;
2041 path->top_type = entry->type;
2043 path->top_type = NULL;
2046 assert(is_type_array(top_type));
2049 path->top_type = top_type->array.element_type;
2054 * Pop an entry from the given type path, ie. returning from
2055 * (type).a.b to (type).a
2057 static void ascend_from_subtype(type_path_t *path)
2059 type_path_entry_t *top = get_type_path_top(path);
2061 path->top_type = top->type;
2063 size_t len = ARR_LEN(path->path);
2064 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2068 * Pop entries from the given type path until the given
2069 * path level is reached.
2071 static void ascend_to(type_path_t *path, size_t top_path_level)
2073 size_t len = ARR_LEN(path->path);
2075 while(len > top_path_level) {
2076 ascend_from_subtype(path);
2077 len = ARR_LEN(path->path);
2081 static bool walk_designator(type_path_t *path, const designator_t *designator,
2082 bool used_in_offsetof)
2084 for( ; designator != NULL; designator = designator->next) {
2085 type_path_entry_t *top = get_type_path_top(path);
2086 type_t *orig_type = top->type;
2088 type_t *type = skip_typeref(orig_type);
2090 if(designator->symbol != NULL) {
2091 symbol_t *symbol = designator->symbol;
2092 if(!is_type_compound(type)) {
2093 if(is_type_valid(type)) {
2094 errorf(&designator->source_position,
2095 "'.%Y' designator used for non-compound type '%T'",
2101 declaration_t *declaration = type->compound.declaration;
2102 declaration_t *iter = declaration->scope.declarations;
2103 for( ; iter != NULL; iter = iter->next) {
2104 if(iter->symbol == symbol) {
2109 errorf(&designator->source_position,
2110 "'%T' has no member named '%Y'", orig_type, symbol);
2113 if(used_in_offsetof) {
2114 type_t *real_type = skip_typeref(iter->type);
2115 if(real_type->kind == TYPE_BITFIELD) {
2116 errorf(&designator->source_position,
2117 "offsetof designator '%Y' may not specify bitfield",
2123 top->type = orig_type;
2124 top->v.compound_entry = iter;
2125 orig_type = iter->type;
2127 expression_t *array_index = designator->array_index;
2128 assert(designator->array_index != NULL);
2130 if(!is_type_array(type)) {
2131 if(is_type_valid(type)) {
2132 errorf(&designator->source_position,
2133 "[%E] designator used for non-array type '%T'",
2134 array_index, orig_type);
2138 if(!is_type_valid(array_index->base.type)) {
2142 long index = fold_constant(array_index);
2143 if(!used_in_offsetof) {
2145 errorf(&designator->source_position,
2146 "array index [%E] must be positive", array_index);
2149 if(type->array.size_constant == true) {
2150 long array_size = type->array.size;
2151 if(index >= array_size) {
2152 errorf(&designator->source_position,
2153 "designator [%E] (%d) exceeds array size %d",
2154 array_index, index, array_size);
2160 top->type = orig_type;
2161 top->v.index = (size_t) index;
2162 orig_type = type->array.element_type;
2164 path->top_type = orig_type;
2166 if(designator->next != NULL) {
2167 descend_into_subtype(path);
2176 static void advance_current_object(type_path_t *path, size_t top_path_level)
2178 type_path_entry_t *top = get_type_path_top(path);
2180 type_t *type = skip_typeref(top->type);
2181 if(is_type_union(type)) {
2182 /* in unions only the first element is initialized */
2183 top->v.compound_entry = NULL;
2184 } else if(is_type_struct(type)) {
2185 declaration_t *entry = top->v.compound_entry;
2187 entry = entry->next;
2188 top->v.compound_entry = entry;
2190 path->top_type = entry->type;
2194 assert(is_type_array(type));
2198 if(!type->array.size_constant || top->v.index < type->array.size) {
2203 /* we're past the last member of the current sub-aggregate, try if we
2204 * can ascend in the type hierarchy and continue with another subobject */
2205 size_t len = ARR_LEN(path->path);
2207 if(len > top_path_level) {
2208 ascend_from_subtype(path);
2209 advance_current_object(path, top_path_level);
2211 path->top_type = NULL;
2216 * skip until token is found.
2218 static void skip_until(int type) {
2219 while(token.type != type) {
2220 if(token.type == T_EOF)
2227 * skip any {...} blocks until a closing bracket is reached.
2229 static void skip_initializers(void)
2231 if(token.type == '{')
2234 while(token.type != '}') {
2235 if(token.type == T_EOF)
2237 if(token.type == '{') {
2245 static initializer_t *create_empty_initializer(void)
2247 static initializer_t empty_initializer
2248 = { .list = { { INITIALIZER_LIST }, 0 } };
2249 return &empty_initializer;
2253 * Parse a part of an initialiser for a struct or union,
2255 static initializer_t *parse_sub_initializer(type_path_t *path,
2256 type_t *outer_type, size_t top_path_level,
2257 parse_initializer_env_t *env)
2259 if(token.type == '}') {
2260 /* empty initializer */
2261 return create_empty_initializer();
2264 type_t *orig_type = path->top_type;
2265 type_t *type = NULL;
2267 if (orig_type == NULL) {
2268 /* We are initializing an empty compound. */
2270 type = skip_typeref(orig_type);
2272 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2273 * initializers in this case. */
2274 if(!is_type_valid(type)) {
2275 skip_initializers();
2276 return create_empty_initializer();
2280 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2283 designator_t *designator = NULL;
2284 if(token.type == '.' || token.type == '[') {
2285 designator = parse_designation();
2287 /* reset path to toplevel, evaluate designator from there */
2288 ascend_to(path, top_path_level);
2289 if(!walk_designator(path, designator, false)) {
2290 /* can't continue after designation error */
2294 initializer_t *designator_initializer
2295 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2296 designator_initializer->designator.designator = designator;
2297 ARR_APP1(initializer_t*, initializers, designator_initializer);
2299 orig_type = path->top_type;
2300 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2305 if(token.type == '{') {
2306 if(type != NULL && is_type_scalar(type)) {
2307 sub = parse_scalar_initializer(type, env->must_be_constant);
2311 if (env->declaration != NULL)
2312 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2313 env->declaration->symbol);
2315 errorf(HERE, "extra brace group at end of initializer");
2317 descend_into_subtype(path);
2319 add_anchor_token('}');
2320 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2322 rem_anchor_token('}');
2325 ascend_from_subtype(path);
2329 goto error_parse_next;
2333 /* must be an expression */
2334 expression_t *expression = parse_assignment_expression();
2336 if(env->must_be_constant && !is_initializer_constant(expression)) {
2337 errorf(&expression->base.source_position,
2338 "Initialisation expression '%E' is not constant\n",
2343 /* we are already outside, ... */
2347 /* handle { "string" } special case */
2348 if((expression->kind == EXPR_STRING_LITERAL
2349 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2350 && outer_type != NULL) {
2351 sub = initializer_from_expression(outer_type, expression);
2353 if(token.type == ',') {
2356 if(token.type != '}') {
2357 warningf(HERE, "excessive elements in initializer for type '%T'",
2360 /* TODO: eat , ... */
2365 /* descend into subtypes until expression matches type */
2367 orig_type = path->top_type;
2368 type = skip_typeref(orig_type);
2370 sub = initializer_from_expression(orig_type, expression);
2374 if(!is_type_valid(type)) {
2377 if(is_type_scalar(type)) {
2378 errorf(&expression->base.source_position,
2379 "expression '%E' doesn't match expected type '%T'",
2380 expression, orig_type);
2384 descend_into_subtype(path);
2388 /* update largest index of top array */
2389 const type_path_entry_t *first = &path->path[0];
2390 type_t *first_type = first->type;
2391 first_type = skip_typeref(first_type);
2392 if(is_type_array(first_type)) {
2393 size_t index = first->v.index;
2394 if(index > path->max_index)
2395 path->max_index = index;
2399 /* append to initializers list */
2400 ARR_APP1(initializer_t*, initializers, sub);
2403 if(env->declaration != NULL)
2404 warningf(HERE, "excess elements in struct initializer for '%Y'",
2405 env->declaration->symbol);
2407 warningf(HERE, "excess elements in struct initializer");
2411 if(token.type == '}') {
2415 if(token.type == '}') {
2420 /* advance to the next declaration if we are not at the end */
2421 advance_current_object(path, top_path_level);
2422 orig_type = path->top_type;
2423 if(orig_type != NULL)
2424 type = skip_typeref(orig_type);
2430 size_t len = ARR_LEN(initializers);
2431 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2432 initializer_t *result = allocate_ast_zero(size);
2433 result->kind = INITIALIZER_LIST;
2434 result->list.len = len;
2435 memcpy(&result->list.initializers, initializers,
2436 len * sizeof(initializers[0]));
2438 DEL_ARR_F(initializers);
2439 ascend_to(path, top_path_level+1);
2444 skip_initializers();
2445 DEL_ARR_F(initializers);
2446 ascend_to(path, top_path_level+1);
2451 * Parses an initializer. Parsers either a compound literal
2452 * (env->declaration == NULL) or an initializer of a declaration.
2454 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2456 type_t *type = skip_typeref(env->type);
2457 initializer_t *result = NULL;
2460 if(is_type_scalar(type)) {
2461 result = parse_scalar_initializer(type, env->must_be_constant);
2462 } else if(token.type == '{') {
2466 memset(&path, 0, sizeof(path));
2467 path.top_type = env->type;
2468 path.path = NEW_ARR_F(type_path_entry_t, 0);
2470 descend_into_subtype(&path);
2472 add_anchor_token('}');
2473 result = parse_sub_initializer(&path, env->type, 1, env);
2474 rem_anchor_token('}');
2476 max_index = path.max_index;
2477 DEL_ARR_F(path.path);
2481 /* parse_scalar_initializer() also works in this case: we simply
2482 * have an expression without {} around it */
2483 result = parse_scalar_initializer(type, env->must_be_constant);
2486 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2487 * the array type size */
2488 if(is_type_array(type) && type->array.size_expression == NULL
2489 && result != NULL) {
2491 switch (result->kind) {
2492 case INITIALIZER_LIST:
2493 size = max_index + 1;
2496 case INITIALIZER_STRING:
2497 size = result->string.string.size;
2500 case INITIALIZER_WIDE_STRING:
2501 size = result->wide_string.string.size;
2504 case INITIALIZER_DESIGNATOR:
2505 case INITIALIZER_VALUE:
2506 /* can happen for parse errors */
2511 internal_errorf(HERE, "invalid initializer type");
2514 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2515 cnst->base.type = type_size_t;
2516 cnst->conste.v.int_value = size;
2518 type_t *new_type = duplicate_type(type);
2520 new_type->array.size_expression = cnst;
2521 new_type->array.size_constant = true;
2522 new_type->array.size = size;
2523 env->type = new_type;
2531 static declaration_t *append_declaration(declaration_t *declaration);
2533 static declaration_t *parse_compound_type_specifier(bool is_struct)
2535 gnu_attribute_t *attributes = NULL;
2536 decl_modifiers_t modifiers = 0;
2543 symbol_t *symbol = NULL;
2544 declaration_t *declaration = NULL;
2546 if (token.type == T___attribute__) {
2547 modifiers |= parse_attributes(&attributes);
2550 if(token.type == T_IDENTIFIER) {
2551 symbol = token.v.symbol;
2555 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2557 declaration = get_declaration(symbol, NAMESPACE_UNION);
2559 } else if(token.type != '{') {
2561 parse_error_expected("while parsing struct type specifier",
2562 T_IDENTIFIER, '{', NULL);
2564 parse_error_expected("while parsing union type specifier",
2565 T_IDENTIFIER, '{', NULL);
2571 if(declaration == NULL) {
2572 declaration = allocate_declaration_zero();
2573 declaration->namespc =
2574 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2575 declaration->source_position = token.source_position;
2576 declaration->symbol = symbol;
2577 declaration->parent_scope = scope;
2578 if (symbol != NULL) {
2579 environment_push(declaration);
2581 append_declaration(declaration);
2584 if(token.type == '{') {
2585 if (declaration->init.complete) {
2586 assert(symbol != NULL);
2587 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2588 is_struct ? "struct" : "union", symbol,
2589 &declaration->source_position);
2590 declaration->scope.declarations = NULL;
2592 declaration->init.complete = true;
2594 parse_compound_type_entries(declaration);
2595 modifiers |= parse_attributes(&attributes);
2598 declaration->modifiers |= modifiers;
2602 static void parse_enum_entries(type_t *const enum_type)
2606 if(token.type == '}') {
2608 errorf(HERE, "empty enum not allowed");
2612 add_anchor_token('}');
2614 if(token.type != T_IDENTIFIER) {
2615 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2617 rem_anchor_token('}');
2621 declaration_t *const entry = allocate_declaration_zero();
2622 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2623 entry->type = enum_type;
2624 entry->symbol = token.v.symbol;
2625 entry->source_position = token.source_position;
2628 if(token.type == '=') {
2630 expression_t *value = parse_constant_expression();
2632 value = create_implicit_cast(value, enum_type);
2633 entry->init.enum_value = value;
2638 record_declaration(entry);
2640 if(token.type != ',')
2643 } while(token.type != '}');
2644 rem_anchor_token('}');
2652 static type_t *parse_enum_specifier(void)
2654 gnu_attribute_t *attributes = NULL;
2655 declaration_t *declaration;
2659 if(token.type == T_IDENTIFIER) {
2660 symbol = token.v.symbol;
2663 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2664 } else if(token.type != '{') {
2665 parse_error_expected("while parsing enum type specifier",
2666 T_IDENTIFIER, '{', NULL);
2673 if(declaration == NULL) {
2674 declaration = allocate_declaration_zero();
2675 declaration->namespc = NAMESPACE_ENUM;
2676 declaration->source_position = token.source_position;
2677 declaration->symbol = symbol;
2678 declaration->parent_scope = scope;
2681 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2682 type->enumt.declaration = declaration;
2684 if(token.type == '{') {
2685 if(declaration->init.complete) {
2686 errorf(HERE, "multiple definitions of enum %Y", symbol);
2688 if (symbol != NULL) {
2689 environment_push(declaration);
2691 append_declaration(declaration);
2692 declaration->init.complete = true;
2694 parse_enum_entries(type);
2695 parse_attributes(&attributes);
2702 * if a symbol is a typedef to another type, return true
2704 static bool is_typedef_symbol(symbol_t *symbol)
2706 const declaration_t *const declaration =
2707 get_declaration(symbol, NAMESPACE_NORMAL);
2709 declaration != NULL &&
2710 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2713 static type_t *parse_typeof(void)
2720 add_anchor_token(')');
2722 expression_t *expression = NULL;
2725 switch(token.type) {
2726 case T___extension__:
2727 /* this can be a prefix to a typename or an expression */
2728 /* we simply eat it now. */
2731 } while(token.type == T___extension__);
2735 if(is_typedef_symbol(token.v.symbol)) {
2736 type = parse_typename();
2738 expression = parse_expression();
2739 type = expression->base.type;
2744 type = parse_typename();
2748 expression = parse_expression();
2749 type = expression->base.type;
2753 rem_anchor_token(')');
2756 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2757 typeof_type->typeoft.expression = expression;
2758 typeof_type->typeoft.typeof_type = type;
2766 SPECIFIER_SIGNED = 1 << 0,
2767 SPECIFIER_UNSIGNED = 1 << 1,
2768 SPECIFIER_LONG = 1 << 2,
2769 SPECIFIER_INT = 1 << 3,
2770 SPECIFIER_DOUBLE = 1 << 4,
2771 SPECIFIER_CHAR = 1 << 5,
2772 SPECIFIER_SHORT = 1 << 6,
2773 SPECIFIER_LONG_LONG = 1 << 7,
2774 SPECIFIER_FLOAT = 1 << 8,
2775 SPECIFIER_BOOL = 1 << 9,
2776 SPECIFIER_VOID = 1 << 10,
2777 SPECIFIER_INT8 = 1 << 11,
2778 SPECIFIER_INT16 = 1 << 12,
2779 SPECIFIER_INT32 = 1 << 13,
2780 SPECIFIER_INT64 = 1 << 14,
2781 SPECIFIER_INT128 = 1 << 15,
2782 SPECIFIER_COMPLEX = 1 << 16,
2783 SPECIFIER_IMAGINARY = 1 << 17,
2786 static type_t *create_builtin_type(symbol_t *const symbol,
2787 type_t *const real_type)
2789 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2790 type->builtin.symbol = symbol;
2791 type->builtin.real_type = real_type;
2793 type_t *result = typehash_insert(type);
2794 if(type != result) {
2801 static type_t *get_typedef_type(symbol_t *symbol)
2803 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2804 if(declaration == NULL ||
2805 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2808 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2809 type->typedeft.declaration = declaration;
2815 * check for the allowed MS alignment values.
2817 static bool check_elignment_value(long long intvalue) {
2818 if(intvalue < 1 || intvalue > 8192) {
2819 errorf(HERE, "illegal alignment value");
2822 unsigned v = (unsigned)intvalue;
2823 for(unsigned i = 1; i <= 8192; i += i) {
2827 errorf(HERE, "alignment must be power of two");
2831 #define DET_MOD(name, tag) do { \
2832 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2833 *modifiers |= tag; \
2836 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2838 decl_modifiers_t *modifiers = &specifiers->modifiers;
2841 if(token.type == T_restrict) {
2843 DET_MOD(restrict, DM_RESTRICT);
2845 } else if(token.type != T_IDENTIFIER)
2847 symbol_t *symbol = token.v.symbol;
2848 if(symbol == sym_align) {
2851 if(token.type != T_INTEGER)
2853 if(check_elignment_value(token.v.intvalue)) {
2854 if(specifiers->alignment != 0)
2855 warningf(HERE, "align used more than once");
2856 specifiers->alignment = (unsigned char)token.v.intvalue;
2860 } else if(symbol == sym_allocate) {
2863 if(token.type != T_IDENTIFIER)
2865 (void)token.v.symbol;
2867 } else if(symbol == sym_dllimport) {
2869 DET_MOD(dllimport, DM_DLLIMPORT);
2870 } else if(symbol == sym_dllexport) {
2872 DET_MOD(dllexport, DM_DLLEXPORT);
2873 } else if(symbol == sym_thread) {
2875 DET_MOD(thread, DM_THREAD);
2876 } else if(symbol == sym_naked) {
2878 DET_MOD(naked, DM_NAKED);
2879 } else if(symbol == sym_noinline) {
2881 DET_MOD(noinline, DM_NOINLINE);
2882 } else if(symbol == sym_noreturn) {
2884 DET_MOD(noreturn, DM_NORETURN);
2885 } else if(symbol == sym_nothrow) {
2887 DET_MOD(nothrow, DM_NOTHROW);
2888 } else if(symbol == sym_novtable) {
2890 DET_MOD(novtable, DM_NOVTABLE);
2891 } else if(symbol == sym_property) {
2895 bool is_get = false;
2896 if(token.type != T_IDENTIFIER)
2898 if(token.v.symbol == sym_get) {
2900 } else if(token.v.symbol == sym_put) {
2902 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2907 if(token.type != T_IDENTIFIER)
2910 if(specifiers->get_property_sym != NULL) {
2911 errorf(HERE, "get property name already specified");
2913 specifiers->get_property_sym = token.v.symbol;
2916 if(specifiers->put_property_sym != NULL) {
2917 errorf(HERE, "put property name already specified");
2919 specifiers->put_property_sym = token.v.symbol;
2923 if(token.type == ',') {
2930 } else if(symbol == sym_selectany) {
2932 DET_MOD(selectany, DM_SELECTANY);
2933 } else if(symbol == sym_uuid) {
2936 if(token.type != T_STRING_LITERAL)
2940 } else if(symbol == sym_deprecated) {
2942 if(specifiers->deprecated != 0)
2943 warningf(HERE, "deprecated used more than once");
2944 specifiers->deprecated = 1;
2945 if(token.type == '(') {
2947 if(token.type == T_STRING_LITERAL) {
2948 specifiers->deprecated_string = token.v.string.begin;
2951 errorf(HERE, "string literal expected");
2955 } else if(symbol == sym_noalias) {
2957 DET_MOD(noalias, DM_NOALIAS);
2959 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2961 if(token.type == '(')
2965 if (token.type == ',')
2972 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2974 type_t *type = NULL;
2975 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2976 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
2977 unsigned type_specifiers = 0;
2980 specifiers->source_position = token.source_position;
2983 switch(token.type) {
2986 #define MATCH_STORAGE_CLASS(token, class) \
2988 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2989 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2991 specifiers->declared_storage_class = class; \
2995 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2996 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2997 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2998 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2999 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3004 add_anchor_token(')');
3005 parse_microsoft_extended_decl_modifier(specifiers);
3006 rem_anchor_token(')');
3011 switch (specifiers->declared_storage_class) {
3012 case STORAGE_CLASS_NONE:
3013 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3016 case STORAGE_CLASS_EXTERN:
3017 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3020 case STORAGE_CLASS_STATIC:
3021 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3025 errorf(HERE, "multiple storage classes in declaration specifiers");
3031 /* type qualifiers */
3032 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3034 qualifiers |= qualifier; \
3038 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3039 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3040 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3041 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3042 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3043 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3044 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3045 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3047 case T___extension__:
3052 /* type specifiers */
3053 #define MATCH_SPECIFIER(token, specifier, name) \
3056 if(type_specifiers & specifier) { \
3057 errorf(HERE, "multiple " name " type specifiers given"); \
3059 type_specifiers |= specifier; \
3063 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3064 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3065 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3066 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3067 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3068 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3069 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3070 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3071 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3072 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3073 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3074 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3075 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3076 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3077 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3078 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3080 case T__forceinline:
3081 /* only in microsoft mode */
3082 specifiers->modifiers |= DM_FORCEINLINE;
3086 specifiers->is_inline = true;
3091 if(type_specifiers & SPECIFIER_LONG_LONG) {
3092 errorf(HERE, "multiple type specifiers given");
3093 } else if(type_specifiers & SPECIFIER_LONG) {
3094 type_specifiers |= SPECIFIER_LONG_LONG;
3096 type_specifiers |= SPECIFIER_LONG;
3101 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3103 type->compound.declaration = parse_compound_type_specifier(true);
3107 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3108 type->compound.declaration = parse_compound_type_specifier(false);
3109 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3110 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3114 type = parse_enum_specifier();
3117 type = parse_typeof();
3119 case T___builtin_va_list:
3120 type = duplicate_type(type_valist);
3124 case T___attribute__:
3125 specifiers->modifiers
3126 |= parse_attributes(&specifiers->gnu_attributes);
3127 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3128 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3131 case T_IDENTIFIER: {
3132 /* only parse identifier if we haven't found a type yet */
3133 if(type != NULL || type_specifiers != 0)
3134 goto finish_specifiers;
3136 type_t *typedef_type = get_typedef_type(token.v.symbol);
3138 if(typedef_type == NULL)
3139 goto finish_specifiers;
3142 type = typedef_type;
3146 /* function specifier */
3148 goto finish_specifiers;
3155 atomic_type_kind_t atomic_type;
3157 /* match valid basic types */
3158 switch(type_specifiers) {
3159 case SPECIFIER_VOID:
3160 atomic_type = ATOMIC_TYPE_VOID;
3162 case SPECIFIER_CHAR:
3163 atomic_type = ATOMIC_TYPE_CHAR;
3165 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3166 atomic_type = ATOMIC_TYPE_SCHAR;
3168 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3169 atomic_type = ATOMIC_TYPE_UCHAR;
3171 case SPECIFIER_SHORT:
3172 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3173 case SPECIFIER_SHORT | SPECIFIER_INT:
3174 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3175 atomic_type = ATOMIC_TYPE_SHORT;
3177 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3178 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3179 atomic_type = ATOMIC_TYPE_USHORT;
3182 case SPECIFIER_SIGNED:
3183 case SPECIFIER_SIGNED | SPECIFIER_INT:
3184 atomic_type = ATOMIC_TYPE_INT;
3186 case SPECIFIER_UNSIGNED:
3187 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3188 atomic_type = ATOMIC_TYPE_UINT;
3190 case SPECIFIER_LONG:
3191 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3192 case SPECIFIER_LONG | SPECIFIER_INT:
3193 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3194 atomic_type = ATOMIC_TYPE_LONG;
3196 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3197 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3198 atomic_type = ATOMIC_TYPE_ULONG;
3200 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3201 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3202 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3203 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3205 atomic_type = ATOMIC_TYPE_LONGLONG;
3207 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3208 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3210 atomic_type = ATOMIC_TYPE_ULONGLONG;
3213 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3214 atomic_type = unsigned_int8_type_kind;
3217 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3218 atomic_type = unsigned_int16_type_kind;
3221 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3222 atomic_type = unsigned_int32_type_kind;
3225 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3226 atomic_type = unsigned_int64_type_kind;
3229 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3230 atomic_type = unsigned_int128_type_kind;
3233 case SPECIFIER_INT8:
3234 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3235 atomic_type = int8_type_kind;
3238 case SPECIFIER_INT16:
3239 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3240 atomic_type = int16_type_kind;
3243 case SPECIFIER_INT32:
3244 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3245 atomic_type = int32_type_kind;
3248 case SPECIFIER_INT64:
3249 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3250 atomic_type = int64_type_kind;
3253 case SPECIFIER_INT128:
3254 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3255 atomic_type = int128_type_kind;
3258 case SPECIFIER_FLOAT:
3259 atomic_type = ATOMIC_TYPE_FLOAT;
3261 case SPECIFIER_DOUBLE:
3262 atomic_type = ATOMIC_TYPE_DOUBLE;
3264 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3265 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3267 case SPECIFIER_BOOL:
3268 atomic_type = ATOMIC_TYPE_BOOL;
3270 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3271 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3272 atomic_type = ATOMIC_TYPE_FLOAT;
3274 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3275 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3276 atomic_type = ATOMIC_TYPE_DOUBLE;
3278 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3279 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3280 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3283 /* invalid specifier combination, give an error message */
3284 if(type_specifiers == 0) {
3285 if (! strict_mode) {
3286 if (warning.implicit_int) {
3287 warningf(HERE, "no type specifiers in declaration, using 'int'");
3289 atomic_type = ATOMIC_TYPE_INT;
3292 errorf(HERE, "no type specifiers given in declaration");
3294 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3295 (type_specifiers & SPECIFIER_UNSIGNED)) {
3296 errorf(HERE, "signed and unsigned specifiers gives");
3297 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3298 errorf(HERE, "only integer types can be signed or unsigned");
3300 errorf(HERE, "multiple datatypes in declaration");
3302 atomic_type = ATOMIC_TYPE_INVALID;
3305 if(type_specifiers & SPECIFIER_COMPLEX &&
3306 atomic_type != ATOMIC_TYPE_INVALID) {
3307 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3308 type->complex.akind = atomic_type;
3309 } else if(type_specifiers & SPECIFIER_IMAGINARY &&
3310 atomic_type != ATOMIC_TYPE_INVALID) {
3311 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3312 type->imaginary.akind = atomic_type;
3314 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3315 type->atomic.akind = atomic_type;
3319 if(type_specifiers != 0) {
3320 errorf(HERE, "multiple datatypes in declaration");
3324 /* FIXME: check type qualifiers here */
3326 type->base.qualifiers = qualifiers;
3327 type->base.modifiers = modifiers;
3329 type_t *result = typehash_insert(type);
3330 if(newtype && result != type) {
3334 specifiers->type = result;
3339 static type_qualifiers_t parse_type_qualifiers(void)
3341 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3344 switch(token.type) {
3345 /* type qualifiers */
3346 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3347 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3348 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3349 /* microsoft extended type modifiers */
3350 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3351 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3352 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3353 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3354 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3362 static declaration_t *parse_identifier_list(void)
3364 declaration_t *declarations = NULL;
3365 declaration_t *last_declaration = NULL;
3367 declaration_t *const declaration = allocate_declaration_zero();
3368 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3369 declaration->source_position = token.source_position;
3370 declaration->symbol = token.v.symbol;
3373 if(last_declaration != NULL) {
3374 last_declaration->next = declaration;
3376 declarations = declaration;
3378 last_declaration = declaration;
3380 if (token.type != ',') {
3384 } while(token.type == T_IDENTIFIER);
3386 return declarations;
3389 static void semantic_parameter(declaration_t *declaration)
3391 /* TODO: improve error messages */
3393 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3394 errorf(HERE, "typedef not allowed in parameter list");
3395 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3396 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3397 errorf(HERE, "parameter may only have none or register storage class");
3400 type_t *const orig_type = declaration->type;
3401 type_t * type = skip_typeref(orig_type);
3403 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3404 * into a pointer. § 6.7.5.3 (7) */
3405 if (is_type_array(type)) {
3406 type_t *const element_type = type->array.element_type;
3408 type = make_pointer_type(element_type, type->base.qualifiers);
3410 declaration->type = type;
3413 if(is_type_incomplete(type)) {
3414 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3415 orig_type, declaration->symbol);
3419 static declaration_t *parse_parameter(void)
3421 declaration_specifiers_t specifiers;
3422 memset(&specifiers, 0, sizeof(specifiers));
3424 parse_declaration_specifiers(&specifiers);
3426 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3431 static declaration_t *parse_parameters(function_type_t *type)
3433 declaration_t *declarations = NULL;
3436 add_anchor_token(')');
3437 int saved_comma_state = save_and_reset_anchor_state(',');
3439 if(token.type == T_IDENTIFIER) {
3440 symbol_t *symbol = token.v.symbol;
3441 if(!is_typedef_symbol(symbol)) {
3442 type->kr_style_parameters = true;
3443 declarations = parse_identifier_list();
3444 goto parameters_finished;
3448 if(token.type == ')') {
3449 type->unspecified_parameters = 1;
3450 goto parameters_finished;
3453 declaration_t *declaration;
3454 declaration_t *last_declaration = NULL;
3455 function_parameter_t *parameter;
3456 function_parameter_t *last_parameter = NULL;
3459 switch(token.type) {
3463 goto parameters_finished;
3466 case T___extension__:
3468 declaration = parse_parameter();
3470 /* func(void) is not a parameter */
3471 if (last_parameter == NULL
3472 && token.type == ')'
3473 && declaration->symbol == NULL
3474 && skip_typeref(declaration->type) == type_void) {
3475 goto parameters_finished;
3477 semantic_parameter(declaration);
3479 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3480 memset(parameter, 0, sizeof(parameter[0]));
3481 parameter->type = declaration->type;
3483 if(last_parameter != NULL) {
3484 last_declaration->next = declaration;
3485 last_parameter->next = parameter;
3487 type->parameters = parameter;
3488 declarations = declaration;
3490 last_parameter = parameter;
3491 last_declaration = declaration;
3495 goto parameters_finished;
3497 if (token.type != ',') {
3498 goto parameters_finished;
3504 parameters_finished:
3505 rem_anchor_token(')');
3508 restore_anchor_state(',', saved_comma_state);
3509 return declarations;
3512 restore_anchor_state(',', saved_comma_state);
3521 } construct_type_kind_t;
3523 typedef struct construct_type_t construct_type_t;
3524 struct construct_type_t {
3525 construct_type_kind_t kind;
3526 construct_type_t *next;
3529 typedef struct parsed_pointer_t parsed_pointer_t;
3530 struct parsed_pointer_t {
3531 construct_type_t construct_type;
3532 type_qualifiers_t type_qualifiers;
3535 typedef struct construct_function_type_t construct_function_type_t;
3536 struct construct_function_type_t {
3537 construct_type_t construct_type;
3538 type_t *function_type;
3541 typedef struct parsed_array_t parsed_array_t;
3542 struct parsed_array_t {
3543 construct_type_t construct_type;
3544 type_qualifiers_t type_qualifiers;
3550 typedef struct construct_base_type_t construct_base_type_t;
3551 struct construct_base_type_t {
3552 construct_type_t construct_type;
3556 static construct_type_t *parse_pointer_declarator(void)
3560 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3561 memset(pointer, 0, sizeof(pointer[0]));
3562 pointer->construct_type.kind = CONSTRUCT_POINTER;
3563 pointer->type_qualifiers = parse_type_qualifiers();
3565 return (construct_type_t*) pointer;
3568 static construct_type_t *parse_array_declarator(void)
3571 add_anchor_token(']');
3573 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3574 memset(array, 0, sizeof(array[0]));
3575 array->construct_type.kind = CONSTRUCT_ARRAY;
3577 if(token.type == T_static) {
3578 array->is_static = true;
3582 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3583 if(type_qualifiers != 0) {
3584 if(token.type == T_static) {
3585 array->is_static = true;
3589 array->type_qualifiers = type_qualifiers;
3591 if(token.type == '*' && look_ahead(1)->type == ']') {
3592 array->is_variable = true;
3594 } else if(token.type != ']') {
3595 array->size = parse_assignment_expression();
3598 rem_anchor_token(']');
3601 return (construct_type_t*) array;
3606 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3609 if(declaration != NULL) {
3610 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3612 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3615 declaration_t *parameters = parse_parameters(&type->function);
3616 if(declaration != NULL) {
3617 declaration->scope.declarations = parameters;
3620 construct_function_type_t *construct_function_type =
3621 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3622 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3623 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3624 construct_function_type->function_type = type;
3626 return (construct_type_t*) construct_function_type;
3629 static void fix_declaration_type(declaration_t *declaration)
3631 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3632 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3634 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3635 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3637 if (declaration->type->base.modifiers == type_modifiers)
3640 type_t *copy = duplicate_type(declaration->type);
3641 copy->base.modifiers = type_modifiers;
3643 type_t *result = typehash_insert(copy);
3644 if (result != copy) {
3645 obstack_free(type_obst, copy);
3648 declaration->type = result;
3651 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3652 bool may_be_abstract)
3654 /* construct a single linked list of construct_type_t's which describe
3655 * how to construct the final declarator type */
3656 construct_type_t *first = NULL;
3657 construct_type_t *last = NULL;
3658 gnu_attribute_t *attributes = NULL;
3661 while(token.type == '*') {
3662 construct_type_t *type = parse_pointer_declarator();
3673 /* TODO: find out if this is correct */
3674 decl_modifiers_t modifiers = parse_attributes(&attributes);
3676 construct_type_t *inner_types = NULL;
3678 switch(token.type) {
3680 if(declaration == NULL) {
3681 errorf(HERE, "no identifier expected in typename");
3683 declaration->symbol = token.v.symbol;
3684 declaration->source_position = token.source_position;
3690 add_anchor_token(')');
3691 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3692 rem_anchor_token(')');
3698 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3699 /* avoid a loop in the outermost scope, because eat_statement doesn't
3701 if(token.type == '}' && current_function == NULL) {
3709 construct_type_t *p = last;
3712 construct_type_t *type;
3713 switch(token.type) {
3715 type = parse_function_declarator(declaration);
3718 type = parse_array_declarator();
3721 goto declarator_finished;
3724 /* insert in the middle of the list (behind p) */
3726 type->next = p->next;
3737 declarator_finished:
3738 modifiers = parse_attributes(&attributes);
3739 if (declaration != NULL) {
3740 declaration->modifiers |= modifiers;
3743 /* append inner_types at the end of the list, we don't to set last anymore
3744 * as it's not needed anymore */
3746 assert(first == NULL);
3747 first = inner_types;
3749 last->next = inner_types;
3757 static type_t *construct_declarator_type(construct_type_t *construct_list,
3760 construct_type_t *iter = construct_list;
3761 for( ; iter != NULL; iter = iter->next) {
3762 switch(iter->kind) {
3763 case CONSTRUCT_INVALID:
3764 internal_errorf(HERE, "invalid type construction found");
3765 case CONSTRUCT_FUNCTION: {
3766 construct_function_type_t *construct_function_type
3767 = (construct_function_type_t*) iter;
3769 type_t *function_type = construct_function_type->function_type;
3771 function_type->function.return_type = type;
3773 type_t *skipped_return_type = skip_typeref(type);
3774 if (is_type_function(skipped_return_type)) {
3775 errorf(HERE, "function returning function is not allowed");
3776 type = type_error_type;
3777 } else if (is_type_array(skipped_return_type)) {
3778 errorf(HERE, "function returning array is not allowed");
3779 type = type_error_type;
3781 type = function_type;
3786 case CONSTRUCT_POINTER: {
3787 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3788 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3789 pointer_type->pointer.points_to = type;
3790 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3792 type = pointer_type;
3796 case CONSTRUCT_ARRAY: {
3797 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3798 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3800 expression_t *size_expression = parsed_array->size;
3801 if(size_expression != NULL) {
3803 = create_implicit_cast(size_expression, type_size_t);
3806 array_type->base.qualifiers = parsed_array->type_qualifiers;
3807 array_type->array.element_type = type;
3808 array_type->array.is_static = parsed_array->is_static;
3809 array_type->array.is_variable = parsed_array->is_variable;
3810 array_type->array.size_expression = size_expression;
3812 if(size_expression != NULL) {
3813 if(is_constant_expression(size_expression)) {
3814 array_type->array.size_constant = true;
3815 array_type->array.size
3816 = fold_constant(size_expression);
3818 array_type->array.is_vla = true;
3822 type_t *skipped_type = skip_typeref(type);
3823 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3824 errorf(HERE, "array of void is not allowed");
3825 type = type_error_type;
3833 type_t *hashed_type = typehash_insert(type);
3834 if(hashed_type != type) {
3835 /* the function type was constructed earlier freeing it here will
3836 * destroy other types... */
3837 if(iter->kind != CONSTRUCT_FUNCTION) {
3847 static declaration_t *parse_declarator(
3848 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3850 declaration_t *const declaration = allocate_declaration_zero();
3851 declaration->declared_storage_class = specifiers->declared_storage_class;
3852 declaration->modifiers = specifiers->modifiers;
3853 declaration->deprecated = specifiers->deprecated;
3854 declaration->deprecated_string = specifiers->deprecated_string;
3855 declaration->get_property_sym = specifiers->get_property_sym;
3856 declaration->put_property_sym = specifiers->put_property_sym;
3857 declaration->is_inline = specifiers->is_inline;
3859 declaration->storage_class = specifiers->declared_storage_class;
3860 if(declaration->storage_class == STORAGE_CLASS_NONE
3861 && scope != global_scope) {
3862 declaration->storage_class = STORAGE_CLASS_AUTO;
3865 if(specifiers->alignment != 0) {
3866 /* TODO: add checks here */
3867 declaration->alignment = specifiers->alignment;
3870 construct_type_t *construct_type
3871 = parse_inner_declarator(declaration, may_be_abstract);
3872 type_t *const type = specifiers->type;
3873 declaration->type = construct_declarator_type(construct_type, type);
3875 fix_declaration_type(declaration);
3877 if(construct_type != NULL) {
3878 obstack_free(&temp_obst, construct_type);
3884 static type_t *parse_abstract_declarator(type_t *base_type)
3886 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3888 type_t *result = construct_declarator_type(construct_type, base_type);
3889 if(construct_type != NULL) {
3890 obstack_free(&temp_obst, construct_type);
3896 static declaration_t *append_declaration(declaration_t* const declaration)
3898 if (last_declaration != NULL) {
3899 last_declaration->next = declaration;
3901 scope->declarations = declaration;
3903 last_declaration = declaration;
3908 * Check if the declaration of main is suspicious. main should be a
3909 * function with external linkage, returning int, taking either zero
3910 * arguments, two, or three arguments of appropriate types, ie.
3912 * int main([ int argc, char **argv [, char **env ] ]).
3914 * @param decl the declaration to check
3915 * @param type the function type of the declaration
3917 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3919 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3920 warningf(&decl->source_position,
3921 "'main' is normally a non-static function");
3923 if (skip_typeref(func_type->return_type) != type_int) {
3924 warningf(&decl->source_position,
3925 "return type of 'main' should be 'int', but is '%T'",
3926 func_type->return_type);
3928 const function_parameter_t *parm = func_type->parameters;
3930 type_t *const first_type = parm->type;
3931 if (!types_compatible(skip_typeref(first_type), type_int)) {
3932 warningf(&decl->source_position,
3933 "first argument of 'main' should be 'int', but is '%T'", first_type);
3937 type_t *const second_type = parm->type;
3938 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3939 warningf(&decl->source_position,
3940 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3944 type_t *const third_type = parm->type;
3945 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3946 warningf(&decl->source_position,
3947 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3951 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3955 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3961 * Check if a symbol is the equal to "main".
3963 static bool is_sym_main(const symbol_t *const sym)
3965 return strcmp(sym->string, "main") == 0;
3968 static declaration_t *internal_record_declaration(
3969 declaration_t *const declaration,
3970 const bool is_function_definition)
3972 const symbol_t *const symbol = declaration->symbol;
3973 const namespace_t namespc = (namespace_t)declaration->namespc;
3975 assert(declaration->symbol != NULL);
3976 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3978 type_t *const orig_type = declaration->type;
3979 type_t *const type = skip_typeref(orig_type);
3980 if (is_type_function(type) &&
3981 type->function.unspecified_parameters &&
3982 warning.strict_prototypes &&
3983 previous_declaration == NULL) {
3984 warningf(&declaration->source_position,
3985 "function declaration '%#T' is not a prototype",
3986 orig_type, declaration->symbol);
3989 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3990 check_type_of_main(declaration, &type->function);
3993 assert(declaration != previous_declaration);
3994 if (previous_declaration != NULL
3995 && previous_declaration->parent_scope == scope) {
3996 /* can happen for K&R style declarations */
3997 if (previous_declaration->type == NULL) {
3998 previous_declaration->type = declaration->type;
4001 const type_t *prev_type = skip_typeref(previous_declaration->type);
4002 if (!types_compatible(type, prev_type)) {
4003 errorf(&declaration->source_position,
4004 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4005 orig_type, symbol, previous_declaration->type, symbol,
4006 &previous_declaration->source_position);
4008 unsigned old_storage_class = previous_declaration->storage_class;
4009 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4010 errorf(&declaration->source_position,
4011 "redeclaration of enum entry '%Y' (declared %P)",
4012 symbol, &previous_declaration->source_position);
4013 return previous_declaration;
4016 unsigned new_storage_class = declaration->storage_class;
4018 if (is_type_incomplete(prev_type)) {
4019 previous_declaration->type = type;
4023 /* pretend no storage class means extern for function
4024 * declarations (except if the previous declaration is neither
4025 * none nor extern) */
4026 if (is_type_function(type)) {
4027 if (prev_type->function.unspecified_parameters) {
4028 previous_declaration->type = type;
4032 switch (old_storage_class) {
4033 case STORAGE_CLASS_NONE:
4034 old_storage_class = STORAGE_CLASS_EXTERN;
4037 case STORAGE_CLASS_EXTERN:
4038 if (is_function_definition) {
4039 if (warning.missing_prototypes &&
4040 prev_type->function.unspecified_parameters &&
4041 !is_sym_main(symbol)) {
4042 warningf(&declaration->source_position,
4043 "no previous prototype for '%#T'",
4046 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4047 new_storage_class = STORAGE_CLASS_EXTERN;
4056 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4057 new_storage_class == STORAGE_CLASS_EXTERN) {
4058 warn_redundant_declaration:
4059 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4060 warningf(&declaration->source_position,
4061 "redundant declaration for '%Y' (declared %P)",
4062 symbol, &previous_declaration->source_position);
4064 } else if (current_function == NULL) {
4065 if (old_storage_class != STORAGE_CLASS_STATIC &&
4066 new_storage_class == STORAGE_CLASS_STATIC) {
4067 errorf(&declaration->source_position,
4068 "static declaration of '%Y' follows non-static declaration (declared %P)",
4069 symbol, &previous_declaration->source_position);
4070 } else if (old_storage_class != STORAGE_CLASS_EXTERN
4071 && !is_function_definition) {
4072 goto warn_redundant_declaration;
4073 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4074 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4075 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4077 } else if (old_storage_class == new_storage_class) {
4078 errorf(&declaration->source_position,
4079 "redeclaration of '%Y' (declared %P)",
4080 symbol, &previous_declaration->source_position);
4082 errorf(&declaration->source_position,
4083 "redeclaration of '%Y' with different linkage (declared %P)",
4084 symbol, &previous_declaration->source_position);
4088 if (declaration->is_inline)
4089 previous_declaration->is_inline = true;
4090 return previous_declaration;
4091 } else if (is_function_definition) {
4092 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4093 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4094 warningf(&declaration->source_position,
4095 "no previous prototype for '%#T'", orig_type, symbol);
4096 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4097 warningf(&declaration->source_position,
4098 "no previous declaration for '%#T'", orig_type,
4102 } else if (warning.missing_declarations &&
4103 scope == global_scope &&
4104 !is_type_function(type) && (
4105 declaration->storage_class == STORAGE_CLASS_NONE ||
4106 declaration->storage_class == STORAGE_CLASS_THREAD
4108 warningf(&declaration->source_position,
4109 "no previous declaration for '%#T'", orig_type, symbol);
4112 assert(declaration->parent_scope == NULL);
4113 assert(scope != NULL);
4115 declaration->parent_scope = scope;
4117 environment_push(declaration);
4118 return append_declaration(declaration);
4121 static declaration_t *record_declaration(declaration_t *declaration)
4123 return internal_record_declaration(declaration, false);
4126 static declaration_t *record_function_definition(declaration_t *declaration)
4128 return internal_record_declaration(declaration, true);
4131 static void parser_error_multiple_definition(declaration_t *declaration,
4132 const source_position_t *source_position)
4134 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4135 declaration->symbol, &declaration->source_position);
4138 static bool is_declaration_specifier(const token_t *token,
4139 bool only_specifiers_qualifiers)
4141 switch(token->type) {
4146 return is_typedef_symbol(token->v.symbol);
4148 case T___extension__:
4150 return !only_specifiers_qualifiers;
4157 static void parse_init_declarator_rest(declaration_t *declaration)
4161 type_t *orig_type = declaration->type;
4162 type_t *type = skip_typeref(orig_type);
4164 if(declaration->init.initializer != NULL) {
4165 parser_error_multiple_definition(declaration, HERE);
4168 bool must_be_constant = false;
4169 if(declaration->storage_class == STORAGE_CLASS_STATIC
4170 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4171 || declaration->parent_scope == global_scope) {
4172 must_be_constant = true;
4175 parse_initializer_env_t env;
4176 env.type = orig_type;
4177 env.must_be_constant = must_be_constant;
4178 env.declaration = declaration;
4180 initializer_t *initializer = parse_initializer(&env);
4182 if(env.type != orig_type) {
4183 orig_type = env.type;
4184 type = skip_typeref(orig_type);
4185 declaration->type = env.type;
4188 if(is_type_function(type)) {
4189 errorf(&declaration->source_position,
4190 "initializers not allowed for function types at declator '%Y' (type '%T')",
4191 declaration->symbol, orig_type);
4193 declaration->init.initializer = initializer;
4197 /* parse rest of a declaration without any declarator */
4198 static void parse_anonymous_declaration_rest(
4199 const declaration_specifiers_t *specifiers,
4200 parsed_declaration_func finished_declaration)
4204 declaration_t *const declaration = allocate_declaration_zero();
4205 declaration->type = specifiers->type;
4206 declaration->declared_storage_class = specifiers->declared_storage_class;
4207 declaration->source_position = specifiers->source_position;
4208 declaration->modifiers = specifiers->modifiers;
4210 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4211 warningf(&declaration->source_position,
4212 "useless storage class in empty declaration");
4214 declaration->storage_class = STORAGE_CLASS_NONE;
4216 type_t *type = declaration->type;
4217 switch (type->kind) {
4218 case TYPE_COMPOUND_STRUCT:
4219 case TYPE_COMPOUND_UNION: {
4220 if (type->compound.declaration->symbol == NULL) {
4221 warningf(&declaration->source_position,
4222 "unnamed struct/union that defines no instances");
4231 warningf(&declaration->source_position, "empty declaration");
4235 finished_declaration(declaration);
4238 static void parse_declaration_rest(declaration_t *ndeclaration,
4239 const declaration_specifiers_t *specifiers,
4240 parsed_declaration_func finished_declaration)
4242 add_anchor_token(';');
4243 add_anchor_token('=');
4244 add_anchor_token(',');
4246 declaration_t *declaration = finished_declaration(ndeclaration);
4248 type_t *orig_type = declaration->type;
4249 type_t *type = skip_typeref(orig_type);
4251 if (type->kind != TYPE_FUNCTION &&
4252 declaration->is_inline &&
4253 is_type_valid(type)) {
4254 warningf(&declaration->source_position,
4255 "variable '%Y' declared 'inline'\n", declaration->symbol);
4258 if(token.type == '=') {
4259 parse_init_declarator_rest(declaration);
4262 if(token.type != ',')
4266 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4271 rem_anchor_token(';');
4272 rem_anchor_token('=');
4273 rem_anchor_token(',');
4276 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4278 symbol_t *symbol = declaration->symbol;
4279 if(symbol == NULL) {
4280 errorf(HERE, "anonymous declaration not valid as function parameter");
4283 namespace_t namespc = (namespace_t) declaration->namespc;
4284 if(namespc != NAMESPACE_NORMAL) {
4285 return record_declaration(declaration);
4288 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4289 if(previous_declaration == NULL ||
4290 previous_declaration->parent_scope != scope) {
4291 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4296 if(previous_declaration->type == NULL) {
4297 previous_declaration->type = declaration->type;
4298 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4299 previous_declaration->storage_class = declaration->storage_class;
4300 previous_declaration->parent_scope = scope;
4301 return previous_declaration;
4303 return record_declaration(declaration);
4307 static void parse_declaration(parsed_declaration_func finished_declaration)
4309 declaration_specifiers_t specifiers;
4310 memset(&specifiers, 0, sizeof(specifiers));
4311 parse_declaration_specifiers(&specifiers);
4313 if(token.type == ';') {
4314 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4316 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4317 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4321 static type_t *get_default_promoted_type(type_t *orig_type)
4323 type_t *result = orig_type;
4325 type_t *type = skip_typeref(orig_type);
4326 if(is_type_integer(type)) {
4327 result = promote_integer(type);
4328 } else if(type == type_float) {
4329 result = type_double;
4335 static void parse_kr_declaration_list(declaration_t *declaration)
4337 type_t *type = skip_typeref(declaration->type);
4338 if (!is_type_function(type))
4341 if (!type->function.kr_style_parameters)
4344 /* push function parameters */
4345 int top = environment_top();
4346 scope_t *last_scope = scope;
4347 set_scope(&declaration->scope);
4349 declaration_t *parameter = declaration->scope.declarations;
4350 for ( ; parameter != NULL; parameter = parameter->next) {
4351 assert(parameter->parent_scope == NULL);
4352 parameter->parent_scope = scope;
4353 environment_push(parameter);
4356 /* parse declaration list */
4357 while (is_declaration_specifier(&token, false)) {
4358 parse_declaration(finished_kr_declaration);
4361 /* pop function parameters */
4362 assert(scope == &declaration->scope);
4363 set_scope(last_scope);
4364 environment_pop_to(top);
4366 /* update function type */
4367 type_t *new_type = duplicate_type(type);
4369 function_parameter_t *parameters = NULL;
4370 function_parameter_t *last_parameter = NULL;
4372 declaration_t *parameter_declaration = declaration->scope.declarations;
4373 for( ; parameter_declaration != NULL;
4374 parameter_declaration = parameter_declaration->next) {
4375 type_t *parameter_type = parameter_declaration->type;
4376 if(parameter_type == NULL) {
4378 errorf(HERE, "no type specified for function parameter '%Y'",
4379 parameter_declaration->symbol);
4381 if (warning.implicit_int) {
4382 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4383 parameter_declaration->symbol);
4385 parameter_type = type_int;
4386 parameter_declaration->type = parameter_type;
4390 semantic_parameter(parameter_declaration);
4391 parameter_type = parameter_declaration->type;
4394 * we need the default promoted types for the function type
4396 parameter_type = get_default_promoted_type(parameter_type);
4398 function_parameter_t *function_parameter
4399 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4400 memset(function_parameter, 0, sizeof(function_parameter[0]));
4402 function_parameter->type = parameter_type;
4403 if(last_parameter != NULL) {
4404 last_parameter->next = function_parameter;
4406 parameters = function_parameter;
4408 last_parameter = function_parameter;
4411 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4413 new_type->function.parameters = parameters;
4414 new_type->function.unspecified_parameters = true;
4416 type = typehash_insert(new_type);
4417 if(type != new_type) {
4418 obstack_free(type_obst, new_type);
4421 declaration->type = type;
4424 static bool first_err = true;
4427 * When called with first_err set, prints the name of the current function,
4430 static void print_in_function(void) {
4433 diagnosticf("%s: In function '%Y':\n",
4434 current_function->source_position.input_name,
4435 current_function->symbol);
4440 * Check if all labels are defined in the current function.
4441 * Check if all labels are used in the current function.
4443 static void check_labels(void)
4445 for (const goto_statement_t *goto_statement = goto_first;
4446 goto_statement != NULL;
4447 goto_statement = goto_statement->next) {
4448 declaration_t *label = goto_statement->label;
4451 if (label->source_position.input_name == NULL) {
4452 print_in_function();
4453 errorf(&goto_statement->base.source_position,
4454 "label '%Y' used but not defined", label->symbol);
4457 goto_first = goto_last = NULL;
4459 if (warning.unused_label) {
4460 for (const label_statement_t *label_statement = label_first;
4461 label_statement != NULL;
4462 label_statement = label_statement->next) {
4463 const declaration_t *label = label_statement->label;
4465 if (! label->used) {
4466 print_in_function();
4467 warningf(&label_statement->base.source_position,
4468 "label '%Y' defined but not used", label->symbol);
4472 label_first = label_last = NULL;
4476 * Check declarations of current_function for unused entities.
4478 static void check_declarations(void)
4480 if (warning.unused_parameter) {
4481 const scope_t *scope = ¤t_function->scope;
4483 const declaration_t *parameter = scope->declarations;
4484 for (; parameter != NULL; parameter = parameter->next) {
4485 if (! parameter->used) {
4486 print_in_function();
4487 warningf(¶meter->source_position,
4488 "unused parameter '%Y'", parameter->symbol);
4492 if (warning.unused_variable) {
4496 static void parse_external_declaration(void)
4498 /* function-definitions and declarations both start with declaration
4500 declaration_specifiers_t specifiers;
4501 memset(&specifiers, 0, sizeof(specifiers));
4503 add_anchor_token(';');
4504 parse_declaration_specifiers(&specifiers);
4505 rem_anchor_token(';');
4507 /* must be a declaration */
4508 if(token.type == ';') {
4509 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4513 add_anchor_token(',');
4514 add_anchor_token('=');
4515 rem_anchor_token(';');
4517 /* declarator is common to both function-definitions and declarations */
4518 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4520 rem_anchor_token(',');
4521 rem_anchor_token('=');
4522 rem_anchor_token(';');
4524 /* must be a declaration */
4525 if(token.type == ',' || token.type == '=' || token.type == ';') {
4526 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4530 /* must be a function definition */
4531 parse_kr_declaration_list(ndeclaration);
4533 if(token.type != '{') {
4534 parse_error_expected("while parsing function definition", '{', NULL);
4535 eat_until_matching_token(';');
4539 type_t *type = ndeclaration->type;
4541 /* note that we don't skip typerefs: the standard doesn't allow them here
4542 * (so we can't use is_type_function here) */
4543 if(type->kind != TYPE_FUNCTION) {
4544 if (is_type_valid(type)) {
4545 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4546 type, ndeclaration->symbol);
4552 /* § 6.7.5.3 (14) a function definition with () means no
4553 * parameters (and not unspecified parameters) */
4554 if(type->function.unspecified_parameters
4555 && type->function.parameters == NULL
4556 && !type->function.kr_style_parameters) {
4557 type_t *duplicate = duplicate_type(type);
4558 duplicate->function.unspecified_parameters = false;
4560 type = typehash_insert(duplicate);
4561 if(type != duplicate) {
4562 obstack_free(type_obst, duplicate);
4564 ndeclaration->type = type;
4567 declaration_t *const declaration = record_function_definition(ndeclaration);
4568 if(ndeclaration != declaration) {
4569 declaration->scope = ndeclaration->scope;
4571 type = skip_typeref(declaration->type);
4573 /* push function parameters and switch scope */
4574 int top = environment_top();
4575 scope_t *last_scope = scope;
4576 set_scope(&declaration->scope);
4578 declaration_t *parameter = declaration->scope.declarations;
4579 for( ; parameter != NULL; parameter = parameter->next) {
4580 if(parameter->parent_scope == &ndeclaration->scope) {
4581 parameter->parent_scope = scope;
4583 assert(parameter->parent_scope == NULL
4584 || parameter->parent_scope == scope);
4585 parameter->parent_scope = scope;
4586 if (parameter->symbol == NULL) {
4587 errorf(&ndeclaration->source_position, "parameter name omitted");
4590 environment_push(parameter);
4593 if(declaration->init.statement != NULL) {
4594 parser_error_multiple_definition(declaration, HERE);
4596 goto end_of_parse_external_declaration;
4598 /* parse function body */
4599 int label_stack_top = label_top();
4600 declaration_t *old_current_function = current_function;
4601 current_function = declaration;
4603 declaration->init.statement = parse_compound_statement(false);
4606 check_declarations();
4608 assert(current_function == declaration);
4609 current_function = old_current_function;
4610 label_pop_to(label_stack_top);
4613 end_of_parse_external_declaration:
4614 assert(scope == &declaration->scope);
4615 set_scope(last_scope);
4616 environment_pop_to(top);
4619 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4620 source_position_t *source_position)
4622 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4624 type->bitfield.base_type = base_type;
4625 type->bitfield.size = size;
4630 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4633 declaration_t *iter = compound_declaration->scope.declarations;
4634 for( ; iter != NULL; iter = iter->next) {
4635 if(iter->namespc != NAMESPACE_NORMAL)
4638 if(iter->symbol == NULL) {
4639 type_t *type = skip_typeref(iter->type);
4640 if(is_type_compound(type)) {
4641 declaration_t *result
4642 = find_compound_entry(type->compound.declaration, symbol);
4649 if(iter->symbol == symbol) {
4657 static void parse_compound_declarators(declaration_t *struct_declaration,
4658 const declaration_specifiers_t *specifiers)
4660 declaration_t *last_declaration = struct_declaration->scope.declarations;
4661 if(last_declaration != NULL) {
4662 while(last_declaration->next != NULL) {
4663 last_declaration = last_declaration->next;
4668 declaration_t *declaration;
4670 if(token.type == ':') {
4671 source_position_t source_position = *HERE;
4674 type_t *base_type = specifiers->type;
4675 expression_t *size = parse_constant_expression();
4677 if(!is_type_integer(skip_typeref(base_type))) {
4678 errorf(HERE, "bitfield base type '%T' is not an integer type",
4682 type_t *type = make_bitfield_type(base_type, size, &source_position);
4684 declaration = allocate_declaration_zero();
4685 declaration->namespc = NAMESPACE_NORMAL;
4686 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4687 declaration->storage_class = STORAGE_CLASS_NONE;
4688 declaration->source_position = source_position;
4689 declaration->modifiers = specifiers->modifiers;
4690 declaration->type = type;
4692 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4694 type_t *orig_type = declaration->type;
4695 type_t *type = skip_typeref(orig_type);
4697 if(token.type == ':') {
4698 source_position_t source_position = *HERE;
4700 expression_t *size = parse_constant_expression();
4702 if(!is_type_integer(type)) {
4703 errorf(HERE, "bitfield base type '%T' is not an "
4704 "integer type", orig_type);
4707 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4708 declaration->type = bitfield_type;
4710 /* TODO we ignore arrays for now... what is missing is a check
4711 * that they're at the end of the struct */
4712 if(is_type_incomplete(type) && !is_type_array(type)) {
4714 "compound member '%Y' has incomplete type '%T'",
4715 declaration->symbol, orig_type);
4716 } else if(is_type_function(type)) {
4717 errorf(HERE, "compound member '%Y' must not have function "
4718 "type '%T'", declaration->symbol, orig_type);
4723 /* make sure we don't define a symbol multiple times */
4724 symbol_t *symbol = declaration->symbol;
4725 if(symbol != NULL) {
4726 declaration_t *prev_decl
4727 = find_compound_entry(struct_declaration, symbol);
4729 if(prev_decl != NULL) {
4730 assert(prev_decl->symbol == symbol);
4731 errorf(&declaration->source_position,
4732 "multiple declarations of symbol '%Y' (declared %P)",
4733 symbol, &prev_decl->source_position);
4737 /* append declaration */
4738 if(last_declaration != NULL) {
4739 last_declaration->next = declaration;
4741 struct_declaration->scope.declarations = declaration;
4743 last_declaration = declaration;
4745 if(token.type != ',')
4755 static void parse_compound_type_entries(declaration_t *compound_declaration)
4758 add_anchor_token('}');
4760 while(token.type != '}' && token.type != T_EOF) {
4761 declaration_specifiers_t specifiers;
4762 memset(&specifiers, 0, sizeof(specifiers));
4763 parse_declaration_specifiers(&specifiers);
4765 parse_compound_declarators(compound_declaration, &specifiers);
4767 rem_anchor_token('}');
4769 if(token.type == T_EOF) {
4770 errorf(HERE, "EOF while parsing struct");
4775 static type_t *parse_typename(void)
4777 declaration_specifiers_t specifiers;
4778 memset(&specifiers, 0, sizeof(specifiers));
4779 parse_declaration_specifiers(&specifiers);
4780 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4781 /* TODO: improve error message, user does probably not know what a
4782 * storage class is...
4784 errorf(HERE, "typename may not have a storage class");
4787 type_t *result = parse_abstract_declarator(specifiers.type);
4795 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4796 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4797 expression_t *left);
4799 typedef struct expression_parser_function_t expression_parser_function_t;
4800 struct expression_parser_function_t {
4801 unsigned precedence;
4802 parse_expression_function parser;
4803 unsigned infix_precedence;
4804 parse_expression_infix_function infix_parser;
4807 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4810 * Prints an error message if an expression was expected but not read
4812 static expression_t *expected_expression_error(void)
4814 /* skip the error message if the error token was read */
4815 if (token.type != T_ERROR) {
4816 errorf(HERE, "expected expression, got token '%K'", &token);
4820 return create_invalid_expression();
4824 * Parse a string constant.
4826 static expression_t *parse_string_const(void)
4829 if (token.type == T_STRING_LITERAL) {
4830 string_t res = token.v.string;
4832 while (token.type == T_STRING_LITERAL) {
4833 res = concat_strings(&res, &token.v.string);
4836 if (token.type != T_WIDE_STRING_LITERAL) {
4837 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4838 /* note: that we use type_char_ptr here, which is already the
4839 * automatic converted type. revert_automatic_type_conversion
4840 * will construct the array type */
4841 cnst->base.type = type_char_ptr;
4842 cnst->string.value = res;
4846 wres = concat_string_wide_string(&res, &token.v.wide_string);
4848 wres = token.v.wide_string;
4853 switch (token.type) {
4854 case T_WIDE_STRING_LITERAL:
4855 wres = concat_wide_strings(&wres, &token.v.wide_string);
4858 case T_STRING_LITERAL:
4859 wres = concat_wide_string_string(&wres, &token.v.string);
4863 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4864 cnst->base.type = type_wchar_t_ptr;
4865 cnst->wide_string.value = wres;
4874 * Parse an integer constant.
4876 static expression_t *parse_int_const(void)
4878 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4879 cnst->base.source_position = *HERE;
4880 cnst->base.type = token.datatype;
4881 cnst->conste.v.int_value = token.v.intvalue;
4889 * Parse a character constant.
4891 static expression_t *parse_character_constant(void)
4893 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4895 cnst->base.source_position = *HERE;
4896 cnst->base.type = token.datatype;
4897 cnst->conste.v.character = token.v.string;
4899 if (cnst->conste.v.character.size != 1) {
4900 if (warning.multichar && (c_mode & _GNUC)) {
4902 warningf(HERE, "multi-character character constant");
4904 errorf(HERE, "more than 1 characters in character constant");
4913 * Parse a wide character constant.
4915 static expression_t *parse_wide_character_constant(void)
4917 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4919 cnst->base.source_position = *HERE;
4920 cnst->base.type = token.datatype;
4921 cnst->conste.v.wide_character = token.v.wide_string;
4923 if (cnst->conste.v.wide_character.size != 1) {
4924 if (warning.multichar && (c_mode & _GNUC)) {
4926 warningf(HERE, "multi-character character constant");
4928 errorf(HERE, "more than 1 characters in character constant");
4937 * Parse a float constant.
4939 static expression_t *parse_float_const(void)
4941 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4942 cnst->base.type = token.datatype;
4943 cnst->conste.v.float_value = token.v.floatvalue;
4950 static declaration_t *create_implicit_function(symbol_t *symbol,
4951 const source_position_t *source_position)
4953 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4954 ntype->function.return_type = type_int;
4955 ntype->function.unspecified_parameters = true;
4957 type_t *type = typehash_insert(ntype);
4962 declaration_t *const declaration = allocate_declaration_zero();
4963 declaration->storage_class = STORAGE_CLASS_EXTERN;
4964 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4965 declaration->type = type;
4966 declaration->symbol = symbol;
4967 declaration->source_position = *source_position;
4969 bool strict_prototypes_old = warning.strict_prototypes;
4970 warning.strict_prototypes = false;
4971 record_declaration(declaration);
4972 warning.strict_prototypes = strict_prototypes_old;
4978 * Creates a return_type (func)(argument_type) function type if not
4981 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
4982 type_t *argument_type2)
4984 function_parameter_t *parameter2
4985 = obstack_alloc(type_obst, sizeof(parameter2[0]));
4986 memset(parameter2, 0, sizeof(parameter2[0]));
4987 parameter2->type = argument_type2;
4989 function_parameter_t *parameter1
4990 = obstack_alloc(type_obst, sizeof(parameter1[0]));
4991 memset(parameter1, 0, sizeof(parameter1[0]));
4992 parameter1->type = argument_type1;
4993 parameter1->next = parameter2;
4995 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4996 type->function.return_type = return_type;
4997 type->function.parameters = parameter1;
4999 type_t *result = typehash_insert(type);
5000 if(result != type) {
5008 * Creates a return_type (func)(argument_type) function type if not
5011 * @param return_type the return type
5012 * @param argument_type the argument type
5014 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5016 function_parameter_t *parameter
5017 = obstack_alloc(type_obst, sizeof(parameter[0]));
5018 memset(parameter, 0, sizeof(parameter[0]));
5019 parameter->type = argument_type;
5021 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5022 type->function.return_type = return_type;
5023 type->function.parameters = parameter;
5025 type_t *result = typehash_insert(type);
5026 if(result != type) {
5033 static type_t *make_function_0_type(type_t *return_type)
5035 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5036 type->function.return_type = return_type;
5037 type->function.parameters = NULL;
5039 type_t *result = typehash_insert(type);
5040 if(result != type) {
5048 * Creates a function type for some function like builtins.
5050 * @param symbol the symbol describing the builtin
5052 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5054 switch(symbol->ID) {
5055 case T___builtin_alloca:
5056 return make_function_1_type(type_void_ptr, type_size_t);
5057 case T___builtin_huge_val:
5058 return make_function_0_type(type_double);
5059 case T___builtin_nan:
5060 return make_function_1_type(type_double, type_char_ptr);
5061 case T___builtin_nanf:
5062 return make_function_1_type(type_float, type_char_ptr);
5063 case T___builtin_nand:
5064 return make_function_1_type(type_long_double, type_char_ptr);
5065 case T___builtin_va_end:
5066 return make_function_1_type(type_void, type_valist);
5067 case T___builtin_expect:
5068 return make_function_2_type(type_long, type_long, type_long);
5070 internal_errorf(HERE, "not implemented builtin symbol found");
5075 * Performs automatic type cast as described in § 6.3.2.1.
5077 * @param orig_type the original type
5079 static type_t *automatic_type_conversion(type_t *orig_type)
5081 type_t *type = skip_typeref(orig_type);
5082 if(is_type_array(type)) {
5083 array_type_t *array_type = &type->array;
5084 type_t *element_type = array_type->element_type;
5085 unsigned qualifiers = array_type->base.qualifiers;
5087 return make_pointer_type(element_type, qualifiers);
5090 if(is_type_function(type)) {
5091 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5098 * reverts the automatic casts of array to pointer types and function
5099 * to function-pointer types as defined § 6.3.2.1
5101 type_t *revert_automatic_type_conversion(const expression_t *expression)
5103 switch (expression->kind) {
5104 case EXPR_REFERENCE: return expression->reference.declaration->type;
5105 case EXPR_SELECT: return expression->select.compound_entry->type;
5107 case EXPR_UNARY_DEREFERENCE: {
5108 const expression_t *const value = expression->unary.value;
5109 type_t *const type = skip_typeref(value->base.type);
5110 assert(is_type_pointer(type));
5111 return type->pointer.points_to;
5114 case EXPR_BUILTIN_SYMBOL:
5115 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5117 case EXPR_ARRAY_ACCESS: {
5118 const expression_t *array_ref = expression->array_access.array_ref;
5119 type_t *type_left = skip_typeref(array_ref->base.type);
5120 if (!is_type_valid(type_left))
5122 assert(is_type_pointer(type_left));
5123 return type_left->pointer.points_to;
5126 case EXPR_STRING_LITERAL: {
5127 size_t size = expression->string.value.size;
5128 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5131 case EXPR_WIDE_STRING_LITERAL: {
5132 size_t size = expression->wide_string.value.size;
5133 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5136 case EXPR_COMPOUND_LITERAL:
5137 return expression->compound_literal.type;
5142 return expression->base.type;
5145 static expression_t *parse_reference(void)
5147 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5149 reference_expression_t *ref = &expression->reference;
5150 symbol_t *const symbol = token.v.symbol;
5152 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5154 source_position_t source_position = token.source_position;
5157 if(declaration == NULL) {
5158 if (! strict_mode && token.type == '(') {
5159 /* an implicitly defined function */
5160 if (warning.implicit_function_declaration) {
5161 warningf(HERE, "implicit declaration of function '%Y'",
5165 declaration = create_implicit_function(symbol,
5168 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5169 return create_invalid_expression();
5173 type_t *type = declaration->type;
5175 /* we always do the auto-type conversions; the & and sizeof parser contains
5176 * code to revert this! */
5177 type = automatic_type_conversion(type);
5179 ref->declaration = declaration;
5180 ref->base.type = type;
5182 /* this declaration is used */
5183 declaration->used = true;
5185 /* check for deprecated functions */
5186 if(declaration->deprecated != 0) {
5187 const char *prefix = "";
5188 if (is_type_function(declaration->type))
5189 prefix = "function ";
5191 if (declaration->deprecated_string != NULL) {
5192 warningf(&source_position,
5193 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5194 declaration->deprecated_string);
5196 warningf(&source_position,
5197 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5204 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5208 /* TODO check if explicit cast is allowed and issue warnings/errors */
5211 static expression_t *parse_compound_literal(type_t *type)
5213 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5215 parse_initializer_env_t env;
5217 env.declaration = NULL;
5218 env.must_be_constant = false;
5219 initializer_t *initializer = parse_initializer(&env);
5222 expression->compound_literal.initializer = initializer;
5223 expression->compound_literal.type = type;
5224 expression->base.type = automatic_type_conversion(type);
5230 * Parse a cast expression.
5232 static expression_t *parse_cast(void)
5234 source_position_t source_position = token.source_position;
5236 type_t *type = parse_typename();
5238 /* matching add_anchor_token() is at call site */
5239 rem_anchor_token(')');
5242 if(token.type == '{') {
5243 return parse_compound_literal(type);
5246 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5247 cast->base.source_position = source_position;
5249 expression_t *value = parse_sub_expression(20);
5251 check_cast_allowed(value, type);
5253 cast->base.type = type;
5254 cast->unary.value = value;
5258 return create_invalid_expression();
5262 * Parse a statement expression.
5264 static expression_t *parse_statement_expression(void)
5266 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5268 statement_t *statement = parse_compound_statement(true);
5269 expression->statement.statement = statement;
5270 expression->base.source_position = statement->base.source_position;
5272 /* find last statement and use its type */
5273 type_t *type = type_void;
5274 const statement_t *stmt = statement->compound.statements;
5276 while (stmt->base.next != NULL)
5277 stmt = stmt->base.next;
5279 if (stmt->kind == STATEMENT_EXPRESSION) {
5280 type = stmt->expression.expression->base.type;
5283 warningf(&expression->base.source_position, "empty statement expression ({})");
5285 expression->base.type = type;
5291 return create_invalid_expression();
5295 * Parse a braced expression.
5297 static expression_t *parse_brace_expression(void)
5300 add_anchor_token(')');
5302 switch(token.type) {
5304 /* gcc extension: a statement expression */
5305 return parse_statement_expression();
5309 return parse_cast();
5311 if(is_typedef_symbol(token.v.symbol)) {
5312 return parse_cast();
5316 expression_t *result = parse_expression();
5317 rem_anchor_token(')');
5322 return create_invalid_expression();
5325 static expression_t *parse_function_keyword(void)
5330 if (current_function == NULL) {
5331 errorf(HERE, "'__func__' used outside of a function");
5334 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5335 expression->base.type = type_char_ptr;
5336 expression->funcname.kind = FUNCNAME_FUNCTION;
5341 static expression_t *parse_pretty_function_keyword(void)
5343 eat(T___PRETTY_FUNCTION__);
5345 if (current_function == NULL) {
5346 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5349 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5350 expression->base.type = type_char_ptr;
5351 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5356 static expression_t *parse_funcsig_keyword(void)
5360 if (current_function == NULL) {
5361 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5364 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5365 expression->base.type = type_char_ptr;
5366 expression->funcname.kind = FUNCNAME_FUNCSIG;
5371 static expression_t *parse_funcdname_keyword(void)
5373 eat(T___FUNCDNAME__);
5375 if (current_function == NULL) {
5376 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5379 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5380 expression->base.type = type_char_ptr;
5381 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5386 static designator_t *parse_designator(void)
5388 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5389 result->source_position = *HERE;
5391 if(token.type != T_IDENTIFIER) {
5392 parse_error_expected("while parsing member designator",
5393 T_IDENTIFIER, NULL);
5396 result->symbol = token.v.symbol;
5399 designator_t *last_designator = result;
5401 if(token.type == '.') {
5403 if(token.type != T_IDENTIFIER) {
5404 parse_error_expected("while parsing member designator",
5405 T_IDENTIFIER, NULL);
5408 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5409 designator->source_position = *HERE;
5410 designator->symbol = token.v.symbol;
5413 last_designator->next = designator;
5414 last_designator = designator;
5417 if(token.type == '[') {
5419 add_anchor_token(']');
5420 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5421 designator->source_position = *HERE;
5422 designator->array_index = parse_expression();
5423 rem_anchor_token(']');
5425 if(designator->array_index == NULL) {
5429 last_designator->next = designator;
5430 last_designator = designator;
5442 * Parse the __builtin_offsetof() expression.
5444 static expression_t *parse_offsetof(void)
5446 eat(T___builtin_offsetof);
5448 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5449 expression->base.type = type_size_t;
5452 add_anchor_token(',');
5453 type_t *type = parse_typename();
5454 rem_anchor_token(',');
5456 add_anchor_token(')');
5457 designator_t *designator = parse_designator();
5458 rem_anchor_token(')');
5461 expression->offsetofe.type = type;
5462 expression->offsetofe.designator = designator;
5465 memset(&path, 0, sizeof(path));
5466 path.top_type = type;
5467 path.path = NEW_ARR_F(type_path_entry_t, 0);
5469 descend_into_subtype(&path);
5471 if(!walk_designator(&path, designator, true)) {
5472 return create_invalid_expression();
5475 DEL_ARR_F(path.path);
5479 return create_invalid_expression();
5483 * Parses a _builtin_va_start() expression.
5485 static expression_t *parse_va_start(void)
5487 eat(T___builtin_va_start);
5489 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5492 add_anchor_token(',');
5493 expression->va_starte.ap = parse_assignment_expression();
5494 rem_anchor_token(',');
5496 expression_t *const expr = parse_assignment_expression();
5497 if (expr->kind == EXPR_REFERENCE) {
5498 declaration_t *const decl = expr->reference.declaration;
5500 return create_invalid_expression();
5501 if (decl->parent_scope == ¤t_function->scope &&
5502 decl->next == NULL) {
5503 expression->va_starte.parameter = decl;
5508 errorf(&expr->base.source_position,
5509 "second argument of 'va_start' must be last parameter of the current function");
5511 return create_invalid_expression();
5515 * Parses a _builtin_va_arg() expression.
5517 static expression_t *parse_va_arg(void)
5519 eat(T___builtin_va_arg);
5521 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5524 expression->va_arge.ap = parse_assignment_expression();
5526 expression->base.type = parse_typename();
5531 return create_invalid_expression();
5534 static expression_t *parse_builtin_symbol(void)
5536 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5538 symbol_t *symbol = token.v.symbol;
5540 expression->builtin_symbol.symbol = symbol;
5543 type_t *type = get_builtin_symbol_type(symbol);
5544 type = automatic_type_conversion(type);
5546 expression->base.type = type;
5551 * Parses a __builtin_constant() expression.
5553 static expression_t *parse_builtin_constant(void)
5555 eat(T___builtin_constant_p);
5557 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5560 add_anchor_token(')');
5561 expression->builtin_constant.value = parse_assignment_expression();
5562 rem_anchor_token(')');
5564 expression->base.type = type_int;
5568 return create_invalid_expression();
5572 * Parses a __builtin_prefetch() expression.
5574 static expression_t *parse_builtin_prefetch(void)
5576 eat(T___builtin_prefetch);
5578 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5581 add_anchor_token(')');
5582 expression->builtin_prefetch.adr = parse_assignment_expression();
5583 if (token.type == ',') {
5585 expression->builtin_prefetch.rw = parse_assignment_expression();
5587 if (token.type == ',') {
5589 expression->builtin_prefetch.locality = parse_assignment_expression();
5591 rem_anchor_token(')');
5593 expression->base.type = type_void;
5597 return create_invalid_expression();
5601 * Parses a __builtin_is_*() compare expression.
5603 static expression_t *parse_compare_builtin(void)
5605 expression_t *expression;
5607 switch(token.type) {
5608 case T___builtin_isgreater:
5609 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5611 case T___builtin_isgreaterequal:
5612 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5614 case T___builtin_isless:
5615 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5617 case T___builtin_islessequal:
5618 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5620 case T___builtin_islessgreater:
5621 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5623 case T___builtin_isunordered:
5624 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5627 internal_errorf(HERE, "invalid compare builtin found");
5630 expression->base.source_position = *HERE;
5634 expression->binary.left = parse_assignment_expression();
5636 expression->binary.right = parse_assignment_expression();
5639 type_t *const orig_type_left = expression->binary.left->base.type;
5640 type_t *const orig_type_right = expression->binary.right->base.type;
5642 type_t *const type_left = skip_typeref(orig_type_left);
5643 type_t *const type_right = skip_typeref(orig_type_right);
5644 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5645 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5646 type_error_incompatible("invalid operands in comparison",
5647 &expression->base.source_position, orig_type_left, orig_type_right);
5650 semantic_comparison(&expression->binary);
5655 return create_invalid_expression();
5660 * Parses a __builtin_expect() expression.
5662 static expression_t *parse_builtin_expect(void)
5664 eat(T___builtin_expect);
5666 expression_t *expression
5667 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5670 expression->binary.left = parse_assignment_expression();
5672 expression->binary.right = parse_constant_expression();
5675 expression->base.type = expression->binary.left->base.type;
5679 return create_invalid_expression();
5684 * Parses a MS assume() expression.
5686 static expression_t *parse_assume(void) {
5689 expression_t *expression
5690 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5693 add_anchor_token(')');
5694 expression->unary.value = parse_assignment_expression();
5695 rem_anchor_token(')');
5698 expression->base.type = type_void;
5701 return create_invalid_expression();
5705 * Parse a microsoft __noop expression.
5707 static expression_t *parse_noop_expression(void) {
5708 source_position_t source_position = *HERE;
5711 if (token.type == '(') {
5712 /* parse arguments */
5714 add_anchor_token(')');
5715 add_anchor_token(',');
5717 if(token.type != ')') {
5719 (void)parse_assignment_expression();
5720 if(token.type != ',')
5726 rem_anchor_token(',');
5727 rem_anchor_token(')');
5730 /* the result is a (int)0 */
5731 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5732 cnst->base.source_position = source_position;
5733 cnst->base.type = type_int;
5734 cnst->conste.v.int_value = 0;
5735 cnst->conste.is_ms_noop = true;
5740 return create_invalid_expression();
5744 * Parses a primary expression.
5746 static expression_t *parse_primary_expression(void)
5748 switch (token.type) {
5749 case T_INTEGER: return parse_int_const();
5750 case T_CHARACTER_CONSTANT: return parse_character_constant();
5751 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5752 case T_FLOATINGPOINT: return parse_float_const();
5753 case T_STRING_LITERAL:
5754 case T_WIDE_STRING_LITERAL: return parse_string_const();
5755 case T_IDENTIFIER: return parse_reference();
5756 case T___FUNCTION__:
5757 case T___func__: return parse_function_keyword();
5758 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5759 case T___FUNCSIG__: return parse_funcsig_keyword();
5760 case T___FUNCDNAME__: return parse_funcdname_keyword();
5761 case T___builtin_offsetof: return parse_offsetof();
5762 case T___builtin_va_start: return parse_va_start();
5763 case T___builtin_va_arg: return parse_va_arg();
5764 case T___builtin_expect:
5765 case T___builtin_alloca:
5766 case T___builtin_nan:
5767 case T___builtin_nand:
5768 case T___builtin_nanf:
5769 case T___builtin_huge_val:
5770 case T___builtin_va_end: return parse_builtin_symbol();
5771 case T___builtin_isgreater:
5772 case T___builtin_isgreaterequal:
5773 case T___builtin_isless:
5774 case T___builtin_islessequal:
5775 case T___builtin_islessgreater:
5776 case T___builtin_isunordered: return parse_compare_builtin();
5777 case T___builtin_constant_p: return parse_builtin_constant();
5778 case T___builtin_prefetch: return parse_builtin_prefetch();
5779 case T__assume: return parse_assume();
5781 case '(': return parse_brace_expression();
5782 case T___noop: return parse_noop_expression();
5785 errorf(HERE, "unexpected token %K, expected an expression", &token);
5786 return create_invalid_expression();
5790 * Check if the expression has the character type and issue a warning then.
5792 static void check_for_char_index_type(const expression_t *expression) {
5793 type_t *const type = expression->base.type;
5794 const type_t *const base_type = skip_typeref(type);
5796 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5797 warning.char_subscripts) {
5798 warningf(&expression->base.source_position,
5799 "array subscript has type '%T'", type);
5803 static expression_t *parse_array_expression(unsigned precedence,
5809 add_anchor_token(']');
5811 expression_t *inside = parse_expression();
5813 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5815 array_access_expression_t *array_access = &expression->array_access;
5817 type_t *const orig_type_left = left->base.type;
5818 type_t *const orig_type_inside = inside->base.type;
5820 type_t *const type_left = skip_typeref(orig_type_left);
5821 type_t *const type_inside = skip_typeref(orig_type_inside);
5823 type_t *return_type;
5824 if (is_type_pointer(type_left)) {
5825 return_type = type_left->pointer.points_to;
5826 array_access->array_ref = left;
5827 array_access->index = inside;
5828 check_for_char_index_type(inside);
5829 } else if (is_type_pointer(type_inside)) {
5830 return_type = type_inside->pointer.points_to;
5831 array_access->array_ref = inside;
5832 array_access->index = left;
5833 array_access->flipped = true;
5834 check_for_char_index_type(left);
5836 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5838 "array access on object with non-pointer types '%T', '%T'",
5839 orig_type_left, orig_type_inside);
5841 return_type = type_error_type;
5842 array_access->array_ref = create_invalid_expression();
5845 rem_anchor_token(']');
5846 if(token.type != ']') {
5847 parse_error_expected("Problem while parsing array access", ']', NULL);
5852 return_type = automatic_type_conversion(return_type);
5853 expression->base.type = return_type;
5858 static expression_t *parse_typeprop(expression_kind_t const kind,
5859 source_position_t const pos,
5860 unsigned const precedence)
5862 expression_t *tp_expression = allocate_expression_zero(kind);
5863 tp_expression->base.type = type_size_t;
5864 tp_expression->base.source_position = pos;
5866 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5868 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5870 add_anchor_token(')');
5871 type_t* const orig_type = parse_typename();
5872 tp_expression->typeprop.type = orig_type;
5874 type_t const* const type = skip_typeref(orig_type);
5875 char const* const wrong_type =
5876 is_type_incomplete(type) ? "incomplete" :
5877 type->kind == TYPE_FUNCTION ? "function designator" :
5878 type->kind == TYPE_BITFIELD ? "bitfield" :
5880 if (wrong_type != NULL) {
5881 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5882 what, wrong_type, type);
5885 rem_anchor_token(')');
5888 expression_t *expression = parse_sub_expression(precedence);
5890 type_t* const orig_type = revert_automatic_type_conversion(expression);
5891 expression->base.type = orig_type;
5893 type_t const* const type = skip_typeref(orig_type);
5894 char const* const wrong_type =
5895 is_type_incomplete(type) ? "incomplete" :
5896 type->kind == TYPE_FUNCTION ? "function designator" :
5897 type->kind == TYPE_BITFIELD ? "bitfield" :
5899 if (wrong_type != NULL) {
5900 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5903 tp_expression->typeprop.type = expression->base.type;
5904 tp_expression->typeprop.tp_expression = expression;
5907 return tp_expression;
5909 return create_invalid_expression();
5912 static expression_t *parse_sizeof(unsigned precedence)
5914 source_position_t pos = *HERE;
5916 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5919 static expression_t *parse_alignof(unsigned precedence)
5921 source_position_t pos = *HERE;
5923 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5926 static expression_t *parse_select_expression(unsigned precedence,
5927 expression_t *compound)
5930 assert(token.type == '.' || token.type == T_MINUSGREATER);
5932 bool is_pointer = (token.type == T_MINUSGREATER);
5935 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5936 select->select.compound = compound;
5938 if (token.type != T_IDENTIFIER) {
5939 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5942 symbol_t *symbol = token.v.symbol;
5943 select->select.symbol = symbol;
5946 type_t *const orig_type = compound->base.type;
5947 type_t *const type = skip_typeref(orig_type);
5949 type_t *type_left = type;
5951 if (!is_type_pointer(type)) {
5952 if (is_type_valid(type)) {
5953 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5955 return create_invalid_expression();
5957 type_left = type->pointer.points_to;
5959 type_left = skip_typeref(type_left);
5961 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5962 type_left->kind != TYPE_COMPOUND_UNION) {
5963 if (is_type_valid(type_left)) {
5964 errorf(HERE, "request for member '%Y' in something not a struct or "
5965 "union, but '%T'", symbol, type_left);
5967 return create_invalid_expression();
5970 declaration_t *const declaration = type_left->compound.declaration;
5972 if (!declaration->init.complete) {
5973 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5975 return create_invalid_expression();
5978 declaration_t *iter = find_compound_entry(declaration, symbol);
5980 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5981 return create_invalid_expression();
5984 /* we always do the auto-type conversions; the & and sizeof parser contains
5985 * code to revert this! */
5986 type_t *expression_type = automatic_type_conversion(iter->type);
5988 select->select.compound_entry = iter;
5989 select->base.type = expression_type;
5991 type_t *skipped = skip_typeref(iter->type);
5992 if (skipped->kind == TYPE_BITFIELD) {
5993 select->base.type = skipped->bitfield.base_type;
5999 static void check_call_argument(const function_parameter_t *parameter,
6000 call_argument_t *argument)
6002 type_t *expected_type = parameter->type;
6003 type_t *expected_type_skip = skip_typeref(expected_type);
6004 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6005 expression_t *arg_expr = argument->expression;
6007 /* handle transparent union gnu extension */
6008 if (is_type_union(expected_type_skip)
6009 && (expected_type_skip->base.modifiers
6010 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6011 declaration_t *union_decl = expected_type_skip->compound.declaration;
6013 declaration_t *declaration = union_decl->scope.declarations;
6014 type_t *best_type = NULL;
6015 for ( ; declaration != NULL; declaration = declaration->next) {
6016 type_t *decl_type = declaration->type;
6017 error = semantic_assign(decl_type, arg_expr);
6018 if (error == ASSIGN_ERROR_INCOMPATIBLE
6019 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6022 if (error == ASSIGN_SUCCESS) {
6023 best_type = decl_type;
6024 } else if (best_type == NULL) {
6025 best_type = decl_type;
6029 if (best_type != NULL) {
6030 expected_type = best_type;
6034 error = semantic_assign(expected_type, arg_expr);
6035 argument->expression = create_implicit_cast(argument->expression,
6038 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6039 report_assign_error(error, expected_type, arg_expr, "function call",
6040 &arg_expr->base.source_position);
6044 * Parse a call expression, ie. expression '( ... )'.
6046 * @param expression the function address
6048 static expression_t *parse_call_expression(unsigned precedence,
6049 expression_t *expression)
6052 expression_t *result = allocate_expression_zero(EXPR_CALL);
6053 result->base.source_position = expression->base.source_position;
6055 call_expression_t *call = &result->call;
6056 call->function = expression;
6058 type_t *const orig_type = expression->base.type;
6059 type_t *const type = skip_typeref(orig_type);
6061 function_type_t *function_type = NULL;
6062 if (is_type_pointer(type)) {
6063 type_t *const to_type = skip_typeref(type->pointer.points_to);
6065 if (is_type_function(to_type)) {
6066 function_type = &to_type->function;
6067 call->base.type = function_type->return_type;
6071 if (function_type == NULL && is_type_valid(type)) {
6072 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6075 /* parse arguments */
6077 add_anchor_token(')');
6078 add_anchor_token(',');
6080 if(token.type != ')') {
6081 call_argument_t *last_argument = NULL;
6084 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6086 argument->expression = parse_assignment_expression();
6087 if(last_argument == NULL) {
6088 call->arguments = argument;
6090 last_argument->next = argument;
6092 last_argument = argument;
6094 if(token.type != ',')
6099 rem_anchor_token(',');
6100 rem_anchor_token(')');
6103 if(function_type == NULL)
6106 function_parameter_t *parameter = function_type->parameters;
6107 call_argument_t *argument = call->arguments;
6108 if (!function_type->unspecified_parameters) {
6109 for( ; parameter != NULL && argument != NULL;
6110 parameter = parameter->next, argument = argument->next) {
6111 check_call_argument(parameter, argument);
6114 if (parameter != NULL) {
6115 errorf(HERE, "too few arguments to function '%E'", expression);
6116 } else if (argument != NULL && !function_type->variadic) {
6117 errorf(HERE, "too many arguments to function '%E'", expression);
6121 /* do default promotion */
6122 for( ; argument != NULL; argument = argument->next) {
6123 type_t *type = argument->expression->base.type;
6125 type = get_default_promoted_type(type);
6127 argument->expression
6128 = create_implicit_cast(argument->expression, type);
6131 check_format(&result->call);
6135 return create_invalid_expression();
6138 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6140 static bool same_compound_type(const type_t *type1, const type_t *type2)
6143 is_type_compound(type1) &&
6144 type1->kind == type2->kind &&
6145 type1->compound.declaration == type2->compound.declaration;
6149 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6151 * @param expression the conditional expression
6153 static expression_t *parse_conditional_expression(unsigned precedence,
6154 expression_t *expression)
6157 add_anchor_token(':');
6159 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6161 conditional_expression_t *conditional = &result->conditional;
6162 conditional->condition = expression;
6165 type_t *const condition_type_orig = expression->base.type;
6166 type_t *const condition_type = skip_typeref(condition_type_orig);
6167 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6168 type_error("expected a scalar type in conditional condition",
6169 &expression->base.source_position, condition_type_orig);
6172 expression_t *true_expression = parse_expression();
6173 rem_anchor_token(':');
6175 expression_t *false_expression = parse_sub_expression(precedence);
6177 type_t *const orig_true_type = true_expression->base.type;
6178 type_t *const orig_false_type = false_expression->base.type;
6179 type_t *const true_type = skip_typeref(orig_true_type);
6180 type_t *const false_type = skip_typeref(orig_false_type);
6183 type_t *result_type;
6184 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6185 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6186 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6187 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6188 warningf(&expression->base.source_position,
6189 "ISO C forbids conditional expression with only one void side");
6191 result_type = type_void;
6192 } else if (is_type_arithmetic(true_type)
6193 && is_type_arithmetic(false_type)) {
6194 result_type = semantic_arithmetic(true_type, false_type);
6196 true_expression = create_implicit_cast(true_expression, result_type);
6197 false_expression = create_implicit_cast(false_expression, result_type);
6199 conditional->true_expression = true_expression;
6200 conditional->false_expression = false_expression;
6201 conditional->base.type = result_type;
6202 } else if (same_compound_type(true_type, false_type)) {
6203 /* just take 1 of the 2 types */
6204 result_type = true_type;
6205 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6206 type_t *pointer_type;
6208 expression_t *other_expression;
6209 if (is_type_pointer(true_type)) {
6210 pointer_type = true_type;
6211 other_type = false_type;
6212 other_expression = false_expression;
6214 pointer_type = false_type;
6215 other_type = true_type;
6216 other_expression = true_expression;
6219 /* TODO Treat (void*)0 as null pointer constant */
6220 if (is_type_pointer(other_type)) {
6221 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6222 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6225 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6226 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6228 } else if (types_compatible(get_unqualified_type(to1),
6229 get_unqualified_type(to2))) {
6232 warningf(&expression->base.source_position,
6233 "pointer types '%T' and '%T' in conditional expression are incompatible",
6234 true_type, false_type);
6238 type_t *const copy = duplicate_type(to);
6239 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6241 type_t *const type = typehash_insert(copy);
6245 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6246 } else if(is_null_pointer_constant(other_expression)) {
6247 result_type = pointer_type;
6248 } else if(is_type_integer(other_type)) {
6249 warningf(&expression->base.source_position,
6250 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6251 result_type = pointer_type;
6253 type_error_incompatible("while parsing conditional",
6254 &expression->base.source_position, true_type, false_type);
6255 result_type = type_error_type;
6258 /* TODO: one pointer to void*, other some pointer */
6260 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6261 type_error_incompatible("while parsing conditional",
6262 &expression->base.source_position, true_type,
6265 result_type = type_error_type;
6268 conditional->true_expression
6269 = create_implicit_cast(true_expression, result_type);
6270 conditional->false_expression
6271 = create_implicit_cast(false_expression, result_type);
6272 conditional->base.type = result_type;
6275 return create_invalid_expression();
6279 * Parse an extension expression.
6281 static expression_t *parse_extension(unsigned precedence)
6283 eat(T___extension__);
6285 /* TODO enable extensions */
6286 expression_t *expression = parse_sub_expression(precedence);
6287 /* TODO disable extensions */
6292 * Parse a __builtin_classify_type() expression.
6294 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6296 eat(T___builtin_classify_type);
6298 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6299 result->base.type = type_int;
6302 add_anchor_token(')');
6303 expression_t *expression = parse_sub_expression(precedence);
6304 rem_anchor_token(')');
6306 result->classify_type.type_expression = expression;
6310 return create_invalid_expression();
6313 static void check_pointer_arithmetic(const source_position_t *source_position,
6314 type_t *pointer_type,
6315 type_t *orig_pointer_type)
6317 type_t *points_to = pointer_type->pointer.points_to;
6318 points_to = skip_typeref(points_to);
6320 if (is_type_incomplete(points_to) &&
6322 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6323 errorf(source_position,
6324 "arithmetic with pointer to incomplete type '%T' not allowed",
6326 } else if (is_type_function(points_to)) {
6327 errorf(source_position,
6328 "arithmetic with pointer to function type '%T' not allowed",
6333 static void semantic_incdec(unary_expression_t *expression)
6335 type_t *const orig_type = expression->value->base.type;
6336 type_t *const type = skip_typeref(orig_type);
6337 if (is_type_pointer(type)) {
6338 check_pointer_arithmetic(&expression->base.source_position,
6340 } else if (!is_type_real(type) && is_type_valid(type)) {
6341 /* TODO: improve error message */
6342 errorf(HERE, "operation needs an arithmetic or pointer type");
6344 expression->base.type = orig_type;
6347 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6349 type_t *const orig_type = expression->value->base.type;
6350 type_t *const type = skip_typeref(orig_type);
6351 if(!is_type_arithmetic(type)) {
6352 if (is_type_valid(type)) {
6353 /* TODO: improve error message */
6354 errorf(HERE, "operation needs an arithmetic type");
6359 expression->base.type = orig_type;
6362 static void semantic_unexpr_scalar(unary_expression_t *expression)
6364 type_t *const orig_type = expression->value->base.type;
6365 type_t *const type = skip_typeref(orig_type);
6366 if (!is_type_scalar(type)) {
6367 if (is_type_valid(type)) {
6368 errorf(HERE, "operand of ! must be of scalar type");
6373 expression->base.type = orig_type;
6376 static void semantic_unexpr_integer(unary_expression_t *expression)
6378 type_t *const orig_type = expression->value->base.type;
6379 type_t *const type = skip_typeref(orig_type);
6380 if (!is_type_integer(type)) {
6381 if (is_type_valid(type)) {
6382 errorf(HERE, "operand of ~ must be of integer type");
6387 expression->base.type = orig_type;
6390 static void semantic_dereference(unary_expression_t *expression)
6392 type_t *const orig_type = expression->value->base.type;
6393 type_t *const type = skip_typeref(orig_type);
6394 if(!is_type_pointer(type)) {
6395 if (is_type_valid(type)) {
6396 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6401 type_t *result_type = type->pointer.points_to;
6402 result_type = automatic_type_conversion(result_type);
6403 expression->base.type = result_type;
6406 static void set_address_taken(expression_t *expression, bool may_be_register)
6408 if(expression->kind != EXPR_REFERENCE)
6411 declaration_t *const declaration = expression->reference.declaration;
6412 /* happens for parse errors */
6413 if(declaration == NULL)
6416 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6417 errorf(&expression->base.source_position,
6418 "address of register variable '%Y' requested",
6419 declaration->symbol);
6421 declaration->address_taken = 1;
6426 * Check the semantic of the address taken expression.
6428 static void semantic_take_addr(unary_expression_t *expression)
6430 expression_t *value = expression->value;
6431 value->base.type = revert_automatic_type_conversion(value);
6433 type_t *orig_type = value->base.type;
6434 if(!is_type_valid(orig_type))
6437 set_address_taken(value, false);
6439 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6442 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6443 static expression_t *parse_##unexpression_type(unsigned precedence) \
6447 expression_t *unary_expression \
6448 = allocate_expression_zero(unexpression_type); \
6449 unary_expression->base.source_position = *HERE; \
6450 unary_expression->unary.value = parse_sub_expression(precedence); \
6452 sfunc(&unary_expression->unary); \
6454 return unary_expression; \
6457 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6458 semantic_unexpr_arithmetic)
6459 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6460 semantic_unexpr_arithmetic)
6461 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6462 semantic_unexpr_scalar)
6463 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6464 semantic_dereference)
6465 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6467 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6468 semantic_unexpr_integer)
6469 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6471 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6474 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6476 static expression_t *parse_##unexpression_type(unsigned precedence, \
6477 expression_t *left) \
6479 (void) precedence; \
6482 expression_t *unary_expression \
6483 = allocate_expression_zero(unexpression_type); \
6484 unary_expression->unary.value = left; \
6486 sfunc(&unary_expression->unary); \
6488 return unary_expression; \
6491 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6492 EXPR_UNARY_POSTFIX_INCREMENT,
6494 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6495 EXPR_UNARY_POSTFIX_DECREMENT,
6498 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6500 /* TODO: handle complex + imaginary types */
6502 /* § 6.3.1.8 Usual arithmetic conversions */
6503 if(type_left == type_long_double || type_right == type_long_double) {
6504 return type_long_double;
6505 } else if(type_left == type_double || type_right == type_double) {
6507 } else if(type_left == type_float || type_right == type_float) {
6511 type_right = promote_integer(type_right);
6512 type_left = promote_integer(type_left);
6514 if(type_left == type_right)
6517 bool signed_left = is_type_signed(type_left);
6518 bool signed_right = is_type_signed(type_right);
6519 int rank_left = get_rank(type_left);
6520 int rank_right = get_rank(type_right);
6521 if(rank_left < rank_right) {
6522 if(signed_left == signed_right || !signed_right) {
6528 if(signed_left == signed_right || !signed_left) {
6537 * Check the semantic restrictions for a binary expression.
6539 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6541 expression_t *const left = expression->left;
6542 expression_t *const right = expression->right;
6543 type_t *const orig_type_left = left->base.type;
6544 type_t *const orig_type_right = right->base.type;
6545 type_t *const type_left = skip_typeref(orig_type_left);
6546 type_t *const type_right = skip_typeref(orig_type_right);
6548 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6549 /* TODO: improve error message */
6550 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6551 errorf(HERE, "operation needs arithmetic types");
6556 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6557 expression->left = create_implicit_cast(left, arithmetic_type);
6558 expression->right = create_implicit_cast(right, arithmetic_type);
6559 expression->base.type = arithmetic_type;
6562 static void semantic_shift_op(binary_expression_t *expression)
6564 expression_t *const left = expression->left;
6565 expression_t *const right = expression->right;
6566 type_t *const orig_type_left = left->base.type;
6567 type_t *const orig_type_right = right->base.type;
6568 type_t * type_left = skip_typeref(orig_type_left);
6569 type_t * type_right = skip_typeref(orig_type_right);
6571 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6572 /* TODO: improve error message */
6573 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6574 errorf(HERE, "operation needs integer types");
6579 type_left = promote_integer(type_left);
6580 type_right = promote_integer(type_right);
6582 expression->left = create_implicit_cast(left, type_left);
6583 expression->right = create_implicit_cast(right, type_right);
6584 expression->base.type = type_left;
6587 static void semantic_add(binary_expression_t *expression)
6589 expression_t *const left = expression->left;
6590 expression_t *const right = expression->right;
6591 type_t *const orig_type_left = left->base.type;
6592 type_t *const orig_type_right = right->base.type;
6593 type_t *const type_left = skip_typeref(orig_type_left);
6594 type_t *const type_right = skip_typeref(orig_type_right);
6597 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6598 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6599 expression->left = create_implicit_cast(left, arithmetic_type);
6600 expression->right = create_implicit_cast(right, arithmetic_type);
6601 expression->base.type = arithmetic_type;
6603 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6604 check_pointer_arithmetic(&expression->base.source_position,
6605 type_left, orig_type_left);
6606 expression->base.type = type_left;
6607 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6608 check_pointer_arithmetic(&expression->base.source_position,
6609 type_right, orig_type_right);
6610 expression->base.type = type_right;
6611 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6612 errorf(&expression->base.source_position,
6613 "invalid operands to binary + ('%T', '%T')",
6614 orig_type_left, orig_type_right);
6618 static void semantic_sub(binary_expression_t *expression)
6620 expression_t *const left = expression->left;
6621 expression_t *const right = expression->right;
6622 type_t *const orig_type_left = left->base.type;
6623 type_t *const orig_type_right = right->base.type;
6624 type_t *const type_left = skip_typeref(orig_type_left);
6625 type_t *const type_right = skip_typeref(orig_type_right);
6628 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6629 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6630 expression->left = create_implicit_cast(left, arithmetic_type);
6631 expression->right = create_implicit_cast(right, arithmetic_type);
6632 expression->base.type = arithmetic_type;
6634 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6635 check_pointer_arithmetic(&expression->base.source_position,
6636 type_left, orig_type_left);
6637 expression->base.type = type_left;
6638 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6639 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6640 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6641 if (!types_compatible(unqual_left, unqual_right)) {
6642 errorf(&expression->base.source_position,
6643 "subtracting pointers to incompatible types '%T' and '%T'",
6644 orig_type_left, orig_type_right);
6645 } else if (!is_type_object(unqual_left)) {
6646 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6647 warningf(&expression->base.source_position,
6648 "subtracting pointers to void");
6650 errorf(&expression->base.source_position,
6651 "subtracting pointers to non-object types '%T'",
6655 expression->base.type = type_ptrdiff_t;
6656 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6657 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6658 orig_type_left, orig_type_right);
6663 * Check the semantics of comparison expressions.
6665 * @param expression The expression to check.
6667 static void semantic_comparison(binary_expression_t *expression)
6669 expression_t *left = expression->left;
6670 expression_t *right = expression->right;
6671 type_t *orig_type_left = left->base.type;
6672 type_t *orig_type_right = right->base.type;
6674 type_t *type_left = skip_typeref(orig_type_left);
6675 type_t *type_right = skip_typeref(orig_type_right);
6677 /* TODO non-arithmetic types */
6678 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6679 /* test for signed vs unsigned compares */
6680 if (warning.sign_compare &&
6681 (expression->base.kind != EXPR_BINARY_EQUAL &&
6682 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6683 (is_type_signed(type_left) != is_type_signed(type_right))) {
6685 /* check if 1 of the operands is a constant, in this case we just
6686 * check wether we can safely represent the resulting constant in
6687 * the type of the other operand. */
6688 expression_t *const_expr = NULL;
6689 expression_t *other_expr = NULL;
6691 if(is_constant_expression(left)) {
6694 } else if(is_constant_expression(right)) {
6699 if(const_expr != NULL) {
6700 type_t *other_type = skip_typeref(other_expr->base.type);
6701 long val = fold_constant(const_expr);
6702 /* TODO: check if val can be represented by other_type */
6706 warningf(&expression->base.source_position,
6707 "comparison between signed and unsigned");
6709 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6710 expression->left = create_implicit_cast(left, arithmetic_type);
6711 expression->right = create_implicit_cast(right, arithmetic_type);
6712 expression->base.type = arithmetic_type;
6713 if (warning.float_equal &&
6714 (expression->base.kind == EXPR_BINARY_EQUAL ||
6715 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6716 is_type_float(arithmetic_type)) {
6717 warningf(&expression->base.source_position,
6718 "comparing floating point with == or != is unsafe");
6720 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6721 /* TODO check compatibility */
6722 } else if (is_type_pointer(type_left)) {
6723 expression->right = create_implicit_cast(right, type_left);
6724 } else if (is_type_pointer(type_right)) {
6725 expression->left = create_implicit_cast(left, type_right);
6726 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6727 type_error_incompatible("invalid operands in comparison",
6728 &expression->base.source_position,
6729 type_left, type_right);
6731 expression->base.type = type_int;
6735 * Checks if a compound type has constant fields.
6737 static bool has_const_fields(const compound_type_t *type)
6739 const scope_t *scope = &type->declaration->scope;
6740 const declaration_t *declaration = scope->declarations;
6742 for (; declaration != NULL; declaration = declaration->next) {
6743 if (declaration->namespc != NAMESPACE_NORMAL)
6746 const type_t *decl_type = skip_typeref(declaration->type);
6747 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6754 static bool is_lvalue(const expression_t *expression)
6756 switch (expression->kind) {
6757 case EXPR_REFERENCE:
6758 case EXPR_ARRAY_ACCESS:
6760 case EXPR_UNARY_DEREFERENCE:
6768 static bool is_valid_assignment_lhs(expression_t const* const left)
6770 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6771 type_t *const type_left = skip_typeref(orig_type_left);
6773 if (!is_lvalue(left)) {
6774 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6779 if (is_type_array(type_left)) {
6780 errorf(HERE, "cannot assign to arrays ('%E')", left);
6783 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6784 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6788 if (is_type_incomplete(type_left)) {
6789 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6790 left, orig_type_left);
6793 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6794 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6795 left, orig_type_left);
6802 static void semantic_arithmetic_assign(binary_expression_t *expression)
6804 expression_t *left = expression->left;
6805 expression_t *right = expression->right;
6806 type_t *orig_type_left = left->base.type;
6807 type_t *orig_type_right = right->base.type;
6809 if (!is_valid_assignment_lhs(left))
6812 type_t *type_left = skip_typeref(orig_type_left);
6813 type_t *type_right = skip_typeref(orig_type_right);
6815 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6816 /* TODO: improve error message */
6817 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6818 errorf(HERE, "operation needs arithmetic types");
6823 /* combined instructions are tricky. We can't create an implicit cast on
6824 * the left side, because we need the uncasted form for the store.
6825 * The ast2firm pass has to know that left_type must be right_type
6826 * for the arithmetic operation and create a cast by itself */
6827 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6828 expression->right = create_implicit_cast(right, arithmetic_type);
6829 expression->base.type = type_left;
6832 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6834 expression_t *const left = expression->left;
6835 expression_t *const right = expression->right;
6836 type_t *const orig_type_left = left->base.type;
6837 type_t *const orig_type_right = right->base.type;
6838 type_t *const type_left = skip_typeref(orig_type_left);
6839 type_t *const type_right = skip_typeref(orig_type_right);
6841 if (!is_valid_assignment_lhs(left))
6844 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6845 /* combined instructions are tricky. We can't create an implicit cast on
6846 * the left side, because we need the uncasted form for the store.
6847 * The ast2firm pass has to know that left_type must be right_type
6848 * for the arithmetic operation and create a cast by itself */
6849 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6850 expression->right = create_implicit_cast(right, arithmetic_type);
6851 expression->base.type = type_left;
6852 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6853 check_pointer_arithmetic(&expression->base.source_position,
6854 type_left, orig_type_left);
6855 expression->base.type = type_left;
6856 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6857 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6862 * Check the semantic restrictions of a logical expression.
6864 static void semantic_logical_op(binary_expression_t *expression)
6866 expression_t *const left = expression->left;
6867 expression_t *const right = expression->right;
6868 type_t *const orig_type_left = left->base.type;
6869 type_t *const orig_type_right = right->base.type;
6870 type_t *const type_left = skip_typeref(orig_type_left);
6871 type_t *const type_right = skip_typeref(orig_type_right);
6873 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6874 /* TODO: improve error message */
6875 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6876 errorf(HERE, "operation needs scalar types");
6881 expression->base.type = type_int;
6885 * Check the semantic restrictions of a binary assign expression.
6887 static void semantic_binexpr_assign(binary_expression_t *expression)
6889 expression_t *left = expression->left;
6890 type_t *orig_type_left = left->base.type;
6892 type_t *type_left = revert_automatic_type_conversion(left);
6893 type_left = skip_typeref(orig_type_left);
6895 if (!is_valid_assignment_lhs(left))
6898 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6899 report_assign_error(error, orig_type_left, expression->right,
6900 "assignment", &left->base.source_position);
6901 expression->right = create_implicit_cast(expression->right, orig_type_left);
6902 expression->base.type = orig_type_left;
6906 * Determine if the outermost operation (or parts thereof) of the given
6907 * expression has no effect in order to generate a warning about this fact.
6908 * Therefore in some cases this only examines some of the operands of the
6909 * expression (see comments in the function and examples below).
6911 * f() + 23; // warning, because + has no effect
6912 * x || f(); // no warning, because x controls execution of f()
6913 * x ? y : f(); // warning, because y has no effect
6914 * (void)x; // no warning to be able to suppress the warning
6915 * This function can NOT be used for an "expression has definitely no effect"-
6917 static bool expression_has_effect(const expression_t *const expr)
6919 switch (expr->kind) {
6920 case EXPR_UNKNOWN: break;
6921 case EXPR_INVALID: return true; /* do NOT warn */
6922 case EXPR_REFERENCE: return false;
6923 /* suppress the warning for microsoft __noop operations */
6924 case EXPR_CONST: return expr->conste.is_ms_noop;
6925 case EXPR_CHARACTER_CONSTANT: return false;
6926 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6927 case EXPR_STRING_LITERAL: return false;
6928 case EXPR_WIDE_STRING_LITERAL: return false;
6931 const call_expression_t *const call = &expr->call;
6932 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6935 switch (call->function->builtin_symbol.symbol->ID) {
6936 case T___builtin_va_end: return true;
6937 default: return false;
6941 /* Generate the warning if either the left or right hand side of a
6942 * conditional expression has no effect */
6943 case EXPR_CONDITIONAL: {
6944 const conditional_expression_t *const cond = &expr->conditional;
6946 expression_has_effect(cond->true_expression) &&
6947 expression_has_effect(cond->false_expression);
6950 case EXPR_SELECT: return false;
6951 case EXPR_ARRAY_ACCESS: return false;
6952 case EXPR_SIZEOF: return false;
6953 case EXPR_CLASSIFY_TYPE: return false;
6954 case EXPR_ALIGNOF: return false;
6956 case EXPR_FUNCNAME: return false;
6957 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6958 case EXPR_BUILTIN_CONSTANT_P: return false;
6959 case EXPR_BUILTIN_PREFETCH: return true;
6960 case EXPR_OFFSETOF: return false;
6961 case EXPR_VA_START: return true;
6962 case EXPR_VA_ARG: return true;
6963 case EXPR_STATEMENT: return true; // TODO
6964 case EXPR_COMPOUND_LITERAL: return false;
6966 case EXPR_UNARY_NEGATE: return false;
6967 case EXPR_UNARY_PLUS: return false;
6968 case EXPR_UNARY_BITWISE_NEGATE: return false;
6969 case EXPR_UNARY_NOT: return false;
6970 case EXPR_UNARY_DEREFERENCE: return false;
6971 case EXPR_UNARY_TAKE_ADDRESS: return false;
6972 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6973 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6974 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6975 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6977 /* Treat void casts as if they have an effect in order to being able to
6978 * suppress the warning */
6979 case EXPR_UNARY_CAST: {
6980 type_t *const type = skip_typeref(expr->base.type);
6981 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6984 case EXPR_UNARY_CAST_IMPLICIT: return true;
6985 case EXPR_UNARY_ASSUME: return true;
6987 case EXPR_BINARY_ADD: return false;
6988 case EXPR_BINARY_SUB: return false;
6989 case EXPR_BINARY_MUL: return false;
6990 case EXPR_BINARY_DIV: return false;
6991 case EXPR_BINARY_MOD: return false;
6992 case EXPR_BINARY_EQUAL: return false;
6993 case EXPR_BINARY_NOTEQUAL: return false;
6994 case EXPR_BINARY_LESS: return false;
6995 case EXPR_BINARY_LESSEQUAL: return false;
6996 case EXPR_BINARY_GREATER: return false;
6997 case EXPR_BINARY_GREATEREQUAL: return false;
6998 case EXPR_BINARY_BITWISE_AND: return false;
6999 case EXPR_BINARY_BITWISE_OR: return false;
7000 case EXPR_BINARY_BITWISE_XOR: return false;
7001 case EXPR_BINARY_SHIFTLEFT: return false;
7002 case EXPR_BINARY_SHIFTRIGHT: return false;
7003 case EXPR_BINARY_ASSIGN: return true;
7004 case EXPR_BINARY_MUL_ASSIGN: return true;
7005 case EXPR_BINARY_DIV_ASSIGN: return true;
7006 case EXPR_BINARY_MOD_ASSIGN: return true;
7007 case EXPR_BINARY_ADD_ASSIGN: return true;
7008 case EXPR_BINARY_SUB_ASSIGN: return true;
7009 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7010 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7011 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7012 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7013 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7015 /* Only examine the right hand side of && and ||, because the left hand
7016 * side already has the effect of controlling the execution of the right
7018 case EXPR_BINARY_LOGICAL_AND:
7019 case EXPR_BINARY_LOGICAL_OR:
7020 /* Only examine the right hand side of a comma expression, because the left
7021 * hand side has a separate warning */
7022 case EXPR_BINARY_COMMA:
7023 return expression_has_effect(expr->binary.right);
7025 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7026 case EXPR_BINARY_ISGREATER: return false;
7027 case EXPR_BINARY_ISGREATEREQUAL: return false;
7028 case EXPR_BINARY_ISLESS: return false;
7029 case EXPR_BINARY_ISLESSEQUAL: return false;
7030 case EXPR_BINARY_ISLESSGREATER: return false;
7031 case EXPR_BINARY_ISUNORDERED: return false;
7034 internal_errorf(HERE, "unexpected expression");
7037 static void semantic_comma(binary_expression_t *expression)
7039 if (warning.unused_value) {
7040 const expression_t *const left = expression->left;
7041 if (!expression_has_effect(left)) {
7042 warningf(&left->base.source_position,
7043 "left-hand operand of comma expression has no effect");
7046 expression->base.type = expression->right->base.type;
7049 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7050 static expression_t *parse_##binexpression_type(unsigned precedence, \
7051 expression_t *left) \
7054 source_position_t pos = *HERE; \
7056 expression_t *right = parse_sub_expression(precedence + lr); \
7058 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7059 binexpr->base.source_position = pos; \
7060 binexpr->binary.left = left; \
7061 binexpr->binary.right = right; \
7062 sfunc(&binexpr->binary); \
7067 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7068 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7069 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7070 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7071 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7072 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7073 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7074 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7075 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7077 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7078 semantic_comparison, 1)
7079 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7080 semantic_comparison, 1)
7081 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7082 semantic_comparison, 1)
7083 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7084 semantic_comparison, 1)
7086 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7087 semantic_binexpr_arithmetic, 1)
7088 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7089 semantic_binexpr_arithmetic, 1)
7090 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7091 semantic_binexpr_arithmetic, 1)
7092 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7093 semantic_logical_op, 1)
7094 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7095 semantic_logical_op, 1)
7096 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7097 semantic_shift_op, 1)
7098 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7099 semantic_shift_op, 1)
7100 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7101 semantic_arithmetic_addsubb_assign, 0)
7102 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7103 semantic_arithmetic_addsubb_assign, 0)
7104 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7105 semantic_arithmetic_assign, 0)
7106 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7107 semantic_arithmetic_assign, 0)
7108 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7109 semantic_arithmetic_assign, 0)
7110 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7111 semantic_arithmetic_assign, 0)
7112 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7113 semantic_arithmetic_assign, 0)
7114 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7115 semantic_arithmetic_assign, 0)
7116 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7117 semantic_arithmetic_assign, 0)
7118 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7119 semantic_arithmetic_assign, 0)
7121 static expression_t *parse_sub_expression(unsigned precedence)
7123 if(token.type < 0) {
7124 return expected_expression_error();
7127 expression_parser_function_t *parser
7128 = &expression_parsers[token.type];
7129 source_position_t source_position = token.source_position;
7132 if(parser->parser != NULL) {
7133 left = parser->parser(parser->precedence);
7135 left = parse_primary_expression();
7137 assert(left != NULL);
7138 left->base.source_position = source_position;
7141 if(token.type < 0) {
7142 return expected_expression_error();
7145 parser = &expression_parsers[token.type];
7146 if(parser->infix_parser == NULL)
7148 if(parser->infix_precedence < precedence)
7151 left = parser->infix_parser(parser->infix_precedence, left);
7153 assert(left != NULL);
7154 assert(left->kind != EXPR_UNKNOWN);
7155 left->base.source_position = source_position;
7162 * Parse an expression.
7164 static expression_t *parse_expression(void)
7166 return parse_sub_expression(1);
7170 * Register a parser for a prefix-like operator with given precedence.
7172 * @param parser the parser function
7173 * @param token_type the token type of the prefix token
7174 * @param precedence the precedence of the operator
7176 static void register_expression_parser(parse_expression_function parser,
7177 int token_type, unsigned precedence)
7179 expression_parser_function_t *entry = &expression_parsers[token_type];
7181 if(entry->parser != NULL) {
7182 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7183 panic("trying to register multiple expression parsers for a token");
7185 entry->parser = parser;
7186 entry->precedence = precedence;
7190 * Register a parser for an infix operator with given precedence.
7192 * @param parser the parser function
7193 * @param token_type the token type of the infix operator
7194 * @param precedence the precedence of the operator
7196 static void register_infix_parser(parse_expression_infix_function parser,
7197 int token_type, unsigned precedence)
7199 expression_parser_function_t *entry = &expression_parsers[token_type];
7201 if(entry->infix_parser != NULL) {
7202 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7203 panic("trying to register multiple infix expression parsers for a "
7206 entry->infix_parser = parser;
7207 entry->infix_precedence = precedence;
7211 * Initialize the expression parsers.
7213 static void init_expression_parsers(void)
7215 memset(&expression_parsers, 0, sizeof(expression_parsers));
7217 register_infix_parser(parse_array_expression, '[', 30);
7218 register_infix_parser(parse_call_expression, '(', 30);
7219 register_infix_parser(parse_select_expression, '.', 30);
7220 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7221 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7223 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7226 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7227 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7228 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7229 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7230 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7231 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7232 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7233 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7234 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7235 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7236 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7237 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7238 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7239 T_EXCLAMATIONMARKEQUAL, 13);
7240 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7241 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7242 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7243 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7244 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7245 register_infix_parser(parse_conditional_expression, '?', 7);
7246 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7247 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7248 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7249 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7250 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7251 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7252 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7253 T_LESSLESSEQUAL, 2);
7254 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7255 T_GREATERGREATEREQUAL, 2);
7256 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7258 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7260 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7263 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7265 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7266 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7267 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7268 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7269 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7270 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7271 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7273 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7275 register_expression_parser(parse_sizeof, T_sizeof, 25);
7276 register_expression_parser(parse_alignof, T___alignof__, 25);
7277 register_expression_parser(parse_extension, T___extension__, 25);
7278 register_expression_parser(parse_builtin_classify_type,
7279 T___builtin_classify_type, 25);
7283 * Parse a asm statement arguments specification.
7285 static asm_argument_t *parse_asm_arguments(bool is_out)
7287 asm_argument_t *result = NULL;
7288 asm_argument_t *last = NULL;
7290 while (token.type == T_STRING_LITERAL || token.type == '[') {
7291 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7292 memset(argument, 0, sizeof(argument[0]));
7294 if (token.type == '[') {
7296 if (token.type != T_IDENTIFIER) {
7297 parse_error_expected("while parsing asm argument",
7298 T_IDENTIFIER, NULL);
7301 argument->symbol = token.v.symbol;
7306 argument->constraints = parse_string_literals();
7308 expression_t *expression = parse_expression();
7309 argument->expression = expression;
7310 if (is_out && !is_lvalue(expression)) {
7311 errorf(&expression->base.source_position,
7312 "asm output argument is not an lvalue");
7316 set_address_taken(expression, true);
7319 last->next = argument;
7325 if (token.type != ',')
7336 * Parse a asm statement clobber specification.
7338 static asm_clobber_t *parse_asm_clobbers(void)
7340 asm_clobber_t *result = NULL;
7341 asm_clobber_t *last = NULL;
7343 while(token.type == T_STRING_LITERAL) {
7344 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7345 clobber->clobber = parse_string_literals();
7348 last->next = clobber;
7354 if(token.type != ',')
7363 * Parse an asm statement.
7365 static statement_t *parse_asm_statement(void)
7369 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7370 statement->base.source_position = token.source_position;
7372 asm_statement_t *asm_statement = &statement->asms;
7374 if(token.type == T_volatile) {
7376 asm_statement->is_volatile = true;
7380 add_anchor_token(')');
7381 add_anchor_token(':');
7382 asm_statement->asm_text = parse_string_literals();
7384 if(token.type != ':') {
7385 rem_anchor_token(':');
7390 asm_statement->outputs = parse_asm_arguments(true);
7391 if(token.type != ':') {
7392 rem_anchor_token(':');
7397 asm_statement->inputs = parse_asm_arguments(false);
7398 if(token.type != ':') {
7399 rem_anchor_token(':');
7402 rem_anchor_token(':');
7405 asm_statement->clobbers = parse_asm_clobbers();
7408 rem_anchor_token(')');
7413 return create_invalid_statement();
7417 * Parse a case statement.
7419 static statement_t *parse_case_statement(void)
7423 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7425 statement->base.source_position = token.source_position;
7426 statement->case_label.expression = parse_expression();
7428 if (c_mode & _GNUC) {
7429 if (token.type == T_DOTDOTDOT) {
7431 statement->case_label.end_range = parse_expression();
7437 if (! is_constant_expression(statement->case_label.expression)) {
7438 errorf(&statement->base.source_position,
7439 "case label does not reduce to an integer constant");
7441 /* TODO: check if the case label is already known */
7442 if (current_switch != NULL) {
7443 /* link all cases into the switch statement */
7444 if (current_switch->last_case == NULL) {
7445 current_switch->first_case =
7446 current_switch->last_case = &statement->case_label;
7448 current_switch->last_case->next = &statement->case_label;
7451 errorf(&statement->base.source_position,
7452 "case label not within a switch statement");
7455 statement->case_label.statement = parse_statement();
7459 return create_invalid_statement();
7463 * Finds an existing default label of a switch statement.
7465 static case_label_statement_t *
7466 find_default_label(const switch_statement_t *statement)
7468 case_label_statement_t *label = statement->first_case;
7469 for ( ; label != NULL; label = label->next) {
7470 if (label->expression == NULL)
7477 * Parse a default statement.
7479 static statement_t *parse_default_statement(void)
7483 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7485 statement->base.source_position = token.source_position;
7488 if (current_switch != NULL) {
7489 const case_label_statement_t *def_label = find_default_label(current_switch);
7490 if (def_label != NULL) {
7491 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7492 &def_label->base.source_position);
7494 /* link all cases into the switch statement */
7495 if (current_switch->last_case == NULL) {
7496 current_switch->first_case =
7497 current_switch->last_case = &statement->case_label;
7499 current_switch->last_case->next = &statement->case_label;
7503 errorf(&statement->base.source_position,
7504 "'default' label not within a switch statement");
7506 statement->case_label.statement = parse_statement();
7510 return create_invalid_statement();
7514 * Return the declaration for a given label symbol or create a new one.
7516 static declaration_t *get_label(symbol_t *symbol)
7518 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7519 assert(current_function != NULL);
7520 /* if we found a label in the same function, then we already created the
7522 if(candidate != NULL
7523 && candidate->parent_scope == ¤t_function->scope) {
7527 /* otherwise we need to create a new one */
7528 declaration_t *const declaration = allocate_declaration_zero();
7529 declaration->namespc = NAMESPACE_LABEL;
7530 declaration->symbol = symbol;
7532 label_push(declaration);
7538 * Parse a label statement.
7540 static statement_t *parse_label_statement(void)
7542 assert(token.type == T_IDENTIFIER);
7543 symbol_t *symbol = token.v.symbol;
7546 declaration_t *label = get_label(symbol);
7548 /* if source position is already set then the label is defined twice,
7549 * otherwise it was just mentioned in a goto so far */
7550 if(label->source_position.input_name != NULL) {
7551 errorf(HERE, "duplicate label '%Y' (declared %P)",
7552 symbol, &label->source_position);
7554 label->source_position = token.source_position;
7557 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7559 statement->base.source_position = token.source_position;
7560 statement->label.label = label;
7564 if(token.type == '}') {
7565 /* TODO only warn? */
7567 warningf(HERE, "label at end of compound statement");
7568 statement->label.statement = create_empty_statement();
7570 errorf(HERE, "label at end of compound statement");
7571 statement->label.statement = create_invalid_statement();
7575 if (token.type == ';') {
7576 /* eat an empty statement here, to avoid the warning about an empty
7577 * after a label. label:; is commonly used to have a label before
7579 statement->label.statement = create_empty_statement();
7582 statement->label.statement = parse_statement();
7586 /* remember the labels's in a list for later checking */
7587 if (label_last == NULL) {
7588 label_first = &statement->label;
7590 label_last->next = &statement->label;
7592 label_last = &statement->label;
7598 * Parse an if statement.
7600 static statement_t *parse_if(void)
7604 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7605 statement->base.source_position = token.source_position;
7608 add_anchor_token(')');
7609 statement->ifs.condition = parse_expression();
7610 rem_anchor_token(')');
7613 add_anchor_token(T_else);
7614 statement->ifs.true_statement = parse_statement();
7615 rem_anchor_token(T_else);
7617 if(token.type == T_else) {
7619 statement->ifs.false_statement = parse_statement();
7624 return create_invalid_statement();
7628 * Parse a switch statement.
7630 static statement_t *parse_switch(void)
7634 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7635 statement->base.source_position = token.source_position;
7638 expression_t *const expr = parse_expression();
7639 type_t * type = skip_typeref(expr->base.type);
7640 if (is_type_integer(type)) {
7641 type = promote_integer(type);
7642 } else if (is_type_valid(type)) {
7643 errorf(&expr->base.source_position,
7644 "switch quantity is not an integer, but '%T'", type);
7645 type = type_error_type;
7647 statement->switchs.expression = create_implicit_cast(expr, type);
7650 switch_statement_t *rem = current_switch;
7651 current_switch = &statement->switchs;
7652 statement->switchs.body = parse_statement();
7653 current_switch = rem;
7655 if(warning.switch_default &&
7656 find_default_label(&statement->switchs) == NULL) {
7657 warningf(&statement->base.source_position, "switch has no default case");
7662 return create_invalid_statement();
7665 static statement_t *parse_loop_body(statement_t *const loop)
7667 statement_t *const rem = current_loop;
7668 current_loop = loop;
7670 statement_t *const body = parse_statement();
7677 * Parse a while statement.
7679 static statement_t *parse_while(void)
7683 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7684 statement->base.source_position = token.source_position;
7687 add_anchor_token(')');
7688 statement->whiles.condition = parse_expression();
7689 rem_anchor_token(')');
7692 statement->whiles.body = parse_loop_body(statement);
7696 return create_invalid_statement();
7700 * Parse a do statement.
7702 static statement_t *parse_do(void)
7706 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7708 statement->base.source_position = token.source_position;
7710 add_anchor_token(T_while);
7711 statement->do_while.body = parse_loop_body(statement);
7712 rem_anchor_token(T_while);
7716 add_anchor_token(')');
7717 statement->do_while.condition = parse_expression();
7718 rem_anchor_token(')');
7724 return create_invalid_statement();
7728 * Parse a for statement.
7730 static statement_t *parse_for(void)
7734 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7735 statement->base.source_position = token.source_position;
7737 int top = environment_top();
7738 scope_t *last_scope = scope;
7739 set_scope(&statement->fors.scope);
7742 add_anchor_token(')');
7744 if(token.type != ';') {
7745 if(is_declaration_specifier(&token, false)) {
7746 parse_declaration(record_declaration);
7748 add_anchor_token(';');
7749 expression_t *const init = parse_expression();
7750 statement->fors.initialisation = init;
7751 if (warning.unused_value && !expression_has_effect(init)) {
7752 warningf(&init->base.source_position,
7753 "initialisation of 'for'-statement has no effect");
7755 rem_anchor_token(';');
7762 if(token.type != ';') {
7763 add_anchor_token(';');
7764 statement->fors.condition = parse_expression();
7765 rem_anchor_token(';');
7768 if(token.type != ')') {
7769 expression_t *const step = parse_expression();
7770 statement->fors.step = step;
7771 if (warning.unused_value && !expression_has_effect(step)) {
7772 warningf(&step->base.source_position,
7773 "step of 'for'-statement has no effect");
7776 rem_anchor_token(')');
7778 statement->fors.body = parse_loop_body(statement);
7780 assert(scope == &statement->fors.scope);
7781 set_scope(last_scope);
7782 environment_pop_to(top);
7787 rem_anchor_token(')');
7788 assert(scope == &statement->fors.scope);
7789 set_scope(last_scope);
7790 environment_pop_to(top);
7792 return create_invalid_statement();
7796 * Parse a goto statement.
7798 static statement_t *parse_goto(void)
7802 if(token.type != T_IDENTIFIER) {
7803 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7807 symbol_t *symbol = token.v.symbol;
7810 declaration_t *label = get_label(symbol);
7812 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7813 statement->base.source_position = token.source_position;
7815 statement->gotos.label = label;
7817 /* remember the goto's in a list for later checking */
7818 if (goto_last == NULL) {
7819 goto_first = &statement->gotos;
7821 goto_last->next = &statement->gotos;
7823 goto_last = &statement->gotos;
7829 return create_invalid_statement();
7833 * Parse a continue statement.
7835 static statement_t *parse_continue(void)
7837 statement_t *statement;
7838 if (current_loop == NULL) {
7839 errorf(HERE, "continue statement not within loop");
7840 statement = create_invalid_statement();
7842 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7844 statement->base.source_position = token.source_position;
7852 return create_invalid_statement();
7856 * Parse a break statement.
7858 static statement_t *parse_break(void)
7860 statement_t *statement;
7861 if (current_switch == NULL && current_loop == NULL) {
7862 errorf(HERE, "break statement not within loop or switch");
7863 statement = create_invalid_statement();
7865 statement = allocate_statement_zero(STATEMENT_BREAK);
7867 statement->base.source_position = token.source_position;
7875 return create_invalid_statement();
7879 * Parse a __leave statement.
7881 static statement_t *parse_leave(void)
7883 statement_t *statement;
7884 if (current_try == NULL) {
7885 errorf(HERE, "__leave statement not within __try");
7886 statement = create_invalid_statement();
7888 statement = allocate_statement_zero(STATEMENT_LEAVE);
7890 statement->base.source_position = token.source_position;
7898 return create_invalid_statement();
7902 * Check if a given declaration represents a local variable.
7904 static bool is_local_var_declaration(const declaration_t *declaration) {
7905 switch ((storage_class_tag_t) declaration->storage_class) {
7906 case STORAGE_CLASS_AUTO:
7907 case STORAGE_CLASS_REGISTER: {
7908 const type_t *type = skip_typeref(declaration->type);
7909 if(is_type_function(type)) {
7921 * Check if a given declaration represents a variable.
7923 static bool is_var_declaration(const declaration_t *declaration) {
7924 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7927 const type_t *type = skip_typeref(declaration->type);
7928 return !is_type_function(type);
7932 * Check if a given expression represents a local variable.
7934 static bool is_local_variable(const expression_t *expression)
7936 if (expression->base.kind != EXPR_REFERENCE) {
7939 const declaration_t *declaration = expression->reference.declaration;
7940 return is_local_var_declaration(declaration);
7944 * Check if a given expression represents a local variable and
7945 * return its declaration then, else return NULL.
7947 declaration_t *expr_is_variable(const expression_t *expression)
7949 if (expression->base.kind != EXPR_REFERENCE) {
7952 declaration_t *declaration = expression->reference.declaration;
7953 if (is_var_declaration(declaration))
7959 * Parse a return statement.
7961 static statement_t *parse_return(void)
7963 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7964 statement->base.source_position = token.source_position;
7968 expression_t *return_value = NULL;
7969 if(token.type != ';') {
7970 return_value = parse_expression();
7974 const type_t *const func_type = current_function->type;
7975 assert(is_type_function(func_type));
7976 type_t *const return_type = skip_typeref(func_type->function.return_type);
7978 if(return_value != NULL) {
7979 type_t *return_value_type = skip_typeref(return_value->base.type);
7981 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7982 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7983 warningf(&statement->base.source_position,
7984 "'return' with a value, in function returning void");
7985 return_value = NULL;
7987 assign_error_t error = semantic_assign(return_type, return_value);
7988 report_assign_error(error, return_type, return_value, "'return'",
7989 &statement->base.source_position);
7990 return_value = create_implicit_cast(return_value, return_type);
7992 /* check for returning address of a local var */
7993 if (return_value != NULL &&
7994 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7995 const expression_t *expression = return_value->unary.value;
7996 if (is_local_variable(expression)) {
7997 warningf(&statement->base.source_position,
7998 "function returns address of local variable");
8002 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8003 warningf(&statement->base.source_position,
8004 "'return' without value, in function returning non-void");
8007 statement->returns.value = return_value;
8011 return create_invalid_statement();
8015 * Parse a declaration statement.
8017 static statement_t *parse_declaration_statement(void)
8019 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8021 statement->base.source_position = token.source_position;
8023 declaration_t *before = last_declaration;
8024 parse_declaration(record_declaration);
8026 if(before == NULL) {
8027 statement->declaration.declarations_begin = scope->declarations;
8029 statement->declaration.declarations_begin = before->next;
8031 statement->declaration.declarations_end = last_declaration;
8037 * Parse an expression statement, ie. expr ';'.
8039 static statement_t *parse_expression_statement(void)
8041 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8043 statement->base.source_position = token.source_position;
8044 expression_t *const expr = parse_expression();
8045 statement->expression.expression = expr;
8051 return create_invalid_statement();
8055 * Parse a microsoft __try { } __finally { } or
8056 * __try{ } __except() { }
8058 static statement_t *parse_ms_try_statment(void) {
8059 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8061 statement->base.source_position = token.source_position;
8064 ms_try_statement_t *rem = current_try;
8065 current_try = &statement->ms_try;
8066 statement->ms_try.try_statement = parse_compound_statement(false);
8069 if(token.type == T___except) {
8072 add_anchor_token(')');
8073 expression_t *const expr = parse_expression();
8074 type_t * type = skip_typeref(expr->base.type);
8075 if (is_type_integer(type)) {
8076 type = promote_integer(type);
8077 } else if (is_type_valid(type)) {
8078 errorf(&expr->base.source_position,
8079 "__expect expression is not an integer, but '%T'", type);
8080 type = type_error_type;
8082 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8083 rem_anchor_token(')');
8085 statement->ms_try.final_statement = parse_compound_statement(false);
8086 } else if(token.type == T__finally) {
8088 statement->ms_try.final_statement = parse_compound_statement(false);
8090 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8091 return create_invalid_statement();
8095 return create_invalid_statement();
8099 * Parse a statement.
8100 * There's also parse_statement() which additionally checks for
8101 * "statement has no effect" warnings
8103 static statement_t *intern_parse_statement(void)
8105 statement_t *statement = NULL;
8107 /* declaration or statement */
8108 add_anchor_token(';');
8109 switch(token.type) {
8111 statement = parse_asm_statement();
8115 statement = parse_case_statement();
8119 statement = parse_default_statement();
8123 statement = parse_compound_statement(false);
8127 statement = parse_if();
8131 statement = parse_switch();
8135 statement = parse_while();
8139 statement = parse_do();
8143 statement = parse_for();
8147 statement = parse_goto();
8151 statement = parse_continue();
8155 statement = parse_break();
8159 statement = parse_leave();
8163 statement = parse_return();
8167 if(warning.empty_statement) {
8168 warningf(HERE, "statement is empty");
8170 statement = create_empty_statement();
8175 if(look_ahead(1)->type == ':') {
8176 statement = parse_label_statement();
8180 if(is_typedef_symbol(token.v.symbol)) {
8181 statement = parse_declaration_statement();
8185 statement = parse_expression_statement();
8188 case T___extension__:
8189 /* this can be a prefix to a declaration or an expression statement */
8190 /* we simply eat it now and parse the rest with tail recursion */
8193 } while(token.type == T___extension__);
8194 statement = parse_statement();
8198 statement = parse_declaration_statement();
8202 statement = parse_ms_try_statment();
8206 statement = parse_expression_statement();
8209 rem_anchor_token(';');
8211 assert(statement != NULL
8212 && statement->base.source_position.input_name != NULL);
8218 * parse a statement and emits "statement has no effect" warning if needed
8219 * (This is really a wrapper around intern_parse_statement with check for 1
8220 * single warning. It is needed, because for statement expressions we have
8221 * to avoid the warning on the last statement)
8223 static statement_t *parse_statement(void)
8225 statement_t *statement = intern_parse_statement();
8227 if(statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8228 expression_t *expression = statement->expression.expression;
8229 if(!expression_has_effect(expression)) {
8230 warningf(&expression->base.source_position,
8231 "statement has no effect");
8239 * Parse a compound statement.
8241 static statement_t *parse_compound_statement(bool inside_expression_statement)
8243 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8245 statement->base.source_position = token.source_position;
8248 add_anchor_token('}');
8250 int top = environment_top();
8251 scope_t *last_scope = scope;
8252 set_scope(&statement->compound.scope);
8254 statement_t *last_statement = NULL;
8256 while(token.type != '}' && token.type != T_EOF) {
8257 statement_t *sub_statement = intern_parse_statement();
8258 if(is_invalid_statement(sub_statement)) {
8259 /* an error occurred. if we are at an anchor, return */
8265 if(last_statement != NULL) {
8266 last_statement->base.next = sub_statement;
8268 statement->compound.statements = sub_statement;
8271 while(sub_statement->base.next != NULL)
8272 sub_statement = sub_statement->base.next;
8274 last_statement = sub_statement;
8277 if(token.type == '}') {
8280 errorf(&statement->base.source_position,
8281 "end of file while looking for closing '}'");
8284 /* look over all statements again to produce no effect warnings */
8285 if(warning.unused_value) {
8286 statement_t *sub_statement = statement->compound.statements;
8287 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8288 if(sub_statement->kind != STATEMENT_EXPRESSION)
8290 /* don't emit a warning for the last expression in an expression
8291 * statement as it has always an effect */
8292 if(inside_expression_statement && sub_statement->base.next == NULL)
8295 expression_t *expression = sub_statement->expression.expression;
8296 if(!expression_has_effect(expression)) {
8297 warningf(&expression->base.source_position,
8298 "statement has no effect");
8304 rem_anchor_token('}');
8305 assert(scope == &statement->compound.scope);
8306 set_scope(last_scope);
8307 environment_pop_to(top);
8313 * Initialize builtin types.
8315 static void initialize_builtin_types(void)
8317 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8318 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8319 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8320 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8321 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8322 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8323 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8324 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8326 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8327 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8328 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8329 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8333 * Check for unused global static functions and variables
8335 static void check_unused_globals(void)
8337 if (!warning.unused_function && !warning.unused_variable)
8340 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8341 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
8344 type_t *const type = decl->type;
8346 if (is_type_function(skip_typeref(type))) {
8347 if (!warning.unused_function || decl->is_inline)
8350 s = (decl->init.statement != NULL ? "defined" : "declared");
8352 if (!warning.unused_variable)
8358 warningf(&decl->source_position, "'%#T' %s but not used",
8359 type, decl->symbol, s);
8364 * Parse a translation unit.
8366 static void parse_translation_unit(void)
8368 while(token.type != T_EOF) {
8369 if (token.type == ';') {
8370 /* TODO error in strict mode */
8371 warningf(HERE, "stray ';' outside of function");
8374 parse_external_declaration();
8382 * @return the translation unit or NULL if errors occurred.
8384 void start_parsing(void)
8386 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8387 label_stack = NEW_ARR_F(stack_entry_t, 0);
8388 diagnostic_count = 0;
8392 type_set_output(stderr);
8393 ast_set_output(stderr);
8395 assert(unit == NULL);
8396 unit = allocate_ast_zero(sizeof(unit[0]));
8398 assert(global_scope == NULL);
8399 global_scope = &unit->scope;
8401 assert(scope == NULL);
8402 set_scope(&unit->scope);
8404 initialize_builtin_types();
8407 translation_unit_t *finish_parsing(void)
8409 assert(scope == &unit->scope);
8411 last_declaration = NULL;
8413 assert(global_scope == &unit->scope);
8414 check_unused_globals();
8415 global_scope = NULL;
8417 DEL_ARR_F(environment_stack);
8418 DEL_ARR_F(label_stack);
8420 translation_unit_t *result = unit;
8427 lookahead_bufpos = 0;
8428 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8431 parse_translation_unit();
8435 * Initialize the parser.
8437 void init_parser(void)
8440 /* add predefined symbols for extended-decl-modifier */
8441 sym_align = symbol_table_insert("align");
8442 sym_allocate = symbol_table_insert("allocate");
8443 sym_dllimport = symbol_table_insert("dllimport");
8444 sym_dllexport = symbol_table_insert("dllexport");
8445 sym_naked = symbol_table_insert("naked");
8446 sym_noinline = symbol_table_insert("noinline");
8447 sym_noreturn = symbol_table_insert("noreturn");
8448 sym_nothrow = symbol_table_insert("nothrow");
8449 sym_novtable = symbol_table_insert("novtable");
8450 sym_property = symbol_table_insert("property");
8451 sym_get = symbol_table_insert("get");
8452 sym_put = symbol_table_insert("put");
8453 sym_selectany = symbol_table_insert("selectany");
8454 sym_thread = symbol_table_insert("thread");
8455 sym_uuid = symbol_table_insert("uuid");
8456 sym_deprecated = symbol_table_insert("deprecated");
8457 sym_restrict = symbol_table_insert("restrict");
8458 sym_noalias = symbol_table_insert("noalias");
8460 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8462 init_expression_parsers();
8463 obstack_init(&temp_obst);
8465 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8466 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8470 * Terminate the parser.
8472 void exit_parser(void)
8474 obstack_free(&temp_obst, NULL);