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 /* __align__ may be used without an argument */
1618 if (attribute->have_arguments) {
1619 parse_gnu_attribute_const_arg(attribute);
1623 case GNU_AK_FORMAT_ARG:
1624 case GNU_AK_REGPARM:
1625 case GNU_AK_TRAP_EXIT:
1626 if(!attribute->have_arguments) {
1627 /* should have arguments */
1628 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1629 attribute->invalid = true;
1631 parse_gnu_attribute_const_arg(attribute);
1634 case GNU_AK_SECTION:
1635 case GNU_AK_SP_SWITCH:
1636 if(!attribute->have_arguments) {
1637 /* should have arguments */
1638 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1639 attribute->invalid = true;
1641 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1644 if(!attribute->have_arguments) {
1645 /* should have arguments */
1646 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1647 attribute->invalid = true;
1649 parse_gnu_attribute_format_args(attribute);
1651 case GNU_AK_WEAKREF:
1652 /* may have one string argument */
1653 if(attribute->have_arguments)
1654 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1656 case GNU_AK_NONNULL:
1657 if(attribute->have_arguments)
1658 parse_gnu_attribute_const_arg_list(attribute);
1660 case GNU_AK_TLS_MODEL:
1661 if(!attribute->have_arguments) {
1662 /* should have arguments */
1663 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1665 parse_gnu_attribute_tls_model_arg(attribute);
1667 case GNU_AK_VISIBILITY:
1668 if(!attribute->have_arguments) {
1669 /* should have arguments */
1670 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1672 parse_gnu_attribute_visibility_arg(attribute);
1675 if(!attribute->have_arguments) {
1676 /* should have arguments */
1677 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1679 parse_gnu_attribute_model_arg(attribute);
1683 if(!attribute->have_arguments) {
1684 /* should have arguments */
1685 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1687 parse_gnu_attribute_mode_arg(attribute);
1690 case GNU_AK_INTERRUPT:
1691 /* may have one string argument */
1692 if(attribute->have_arguments)
1693 parse_gnu_attribute_interrupt_arg(attribute);
1695 case GNU_AK_SENTINEL:
1696 /* may have one string argument */
1697 if(attribute->have_arguments)
1698 parse_gnu_attribute_const_arg(attribute);
1701 /* already handled */
1705 if(attribute != NULL) {
1707 last->next = attribute;
1710 head = last = attribute;
1714 if(token.type != ',')
1728 * Parse GNU attributes.
1730 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1732 decl_modifiers_t modifiers = 0;
1735 switch(token.type) {
1736 case T___attribute__: {
1737 modifiers |= parse_gnu_attribute(attributes);
1743 if(token.type != T_STRING_LITERAL) {
1744 parse_error_expected("while parsing assembler attribute",
1745 T_STRING_LITERAL, NULL);
1746 eat_until_matching_token('(');
1749 parse_string_literals();
1754 goto attributes_finished;
1758 attributes_finished:
1763 static designator_t *parse_designation(void)
1765 designator_t *result = NULL;
1766 designator_t *last = NULL;
1769 designator_t *designator;
1770 switch(token.type) {
1772 designator = allocate_ast_zero(sizeof(designator[0]));
1773 designator->source_position = token.source_position;
1775 add_anchor_token(']');
1776 designator->array_index = parse_constant_expression();
1777 rem_anchor_token(']');
1781 designator = allocate_ast_zero(sizeof(designator[0]));
1782 designator->source_position = token.source_position;
1784 if(token.type != T_IDENTIFIER) {
1785 parse_error_expected("while parsing designator",
1786 T_IDENTIFIER, NULL);
1789 designator->symbol = token.v.symbol;
1797 assert(designator != NULL);
1799 last->next = designator;
1801 result = designator;
1809 static initializer_t *initializer_from_string(array_type_t *type,
1810 const string_t *const string)
1812 /* TODO: check len vs. size of array type */
1815 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1816 initializer->string.string = *string;
1821 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1822 wide_string_t *const string)
1824 /* TODO: check len vs. size of array type */
1827 initializer_t *const initializer =
1828 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1829 initializer->wide_string.string = *string;
1835 * Build an initializer from a given expression.
1837 static initializer_t *initializer_from_expression(type_t *orig_type,
1838 expression_t *expression)
1840 /* TODO check that expression is a constant expression */
1842 /* § 6.7.8.14/15 char array may be initialized by string literals */
1843 type_t *type = skip_typeref(orig_type);
1844 type_t *expr_type_orig = expression->base.type;
1845 type_t *expr_type = skip_typeref(expr_type_orig);
1846 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1847 array_type_t *const array_type = &type->array;
1848 type_t *const element_type = skip_typeref(array_type->element_type);
1850 if (element_type->kind == TYPE_ATOMIC) {
1851 atomic_type_kind_t akind = element_type->atomic.akind;
1852 switch (expression->kind) {
1853 case EXPR_STRING_LITERAL:
1854 if (akind == ATOMIC_TYPE_CHAR
1855 || akind == ATOMIC_TYPE_SCHAR
1856 || akind == ATOMIC_TYPE_UCHAR) {
1857 return initializer_from_string(array_type,
1858 &expression->string.value);
1861 case EXPR_WIDE_STRING_LITERAL: {
1862 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1863 if (get_unqualified_type(element_type) == bare_wchar_type) {
1864 return initializer_from_wide_string(array_type,
1865 &expression->wide_string.value);
1875 assign_error_t error = semantic_assign(type, expression);
1876 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1878 report_assign_error(error, type, expression, "initializer",
1879 &expression->base.source_position);
1881 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1882 result->value.value = create_implicit_cast(expression, type);
1888 * Checks if a given expression can be used as an constant initializer.
1890 static bool is_initializer_constant(const expression_t *expression)
1892 return is_constant_expression(expression)
1893 || is_address_constant(expression);
1897 * Parses an scalar initializer.
1899 * § 6.7.8.11; eat {} without warning
1901 static initializer_t *parse_scalar_initializer(type_t *type,
1902 bool must_be_constant)
1904 /* there might be extra {} hierarchies */
1906 while(token.type == '{') {
1909 warningf(HERE, "extra curly braces around scalar initializer");
1914 expression_t *expression = parse_assignment_expression();
1915 if(must_be_constant && !is_initializer_constant(expression)) {
1916 errorf(&expression->base.source_position,
1917 "Initialisation expression '%E' is not constant\n",
1921 initializer_t *initializer = initializer_from_expression(type, expression);
1923 if(initializer == NULL) {
1924 errorf(&expression->base.source_position,
1925 "expression '%E' (type '%T') doesn't match expected type '%T'",
1926 expression, expression->base.type, type);
1931 bool additional_warning_displayed = false;
1933 if(token.type == ',') {
1936 if(token.type != '}') {
1937 if(!additional_warning_displayed) {
1938 warningf(HERE, "additional elements in scalar initializer");
1939 additional_warning_displayed = true;
1950 * An entry in the type path.
1952 typedef struct type_path_entry_t type_path_entry_t;
1953 struct type_path_entry_t {
1954 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1956 size_t index; /**< For array types: the current index. */
1957 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1962 * A type path expression a position inside compound or array types.
1964 typedef struct type_path_t type_path_t;
1965 struct type_path_t {
1966 type_path_entry_t *path; /**< An flexible array containing the current path. */
1967 type_t *top_type; /**< type of the element the path points */
1968 size_t max_index; /**< largest index in outermost array */
1972 * Prints a type path for debugging.
1974 static __attribute__((unused)) void debug_print_type_path(
1975 const type_path_t *path)
1977 size_t len = ARR_LEN(path->path);
1979 for(size_t i = 0; i < len; ++i) {
1980 const type_path_entry_t *entry = & path->path[i];
1982 type_t *type = skip_typeref(entry->type);
1983 if(is_type_compound(type)) {
1984 /* in gcc mode structs can have no members */
1985 if(entry->v.compound_entry == NULL) {
1989 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1990 } else if(is_type_array(type)) {
1991 fprintf(stderr, "[%zd]", entry->v.index);
1993 fprintf(stderr, "-INVALID-");
1996 if(path->top_type != NULL) {
1997 fprintf(stderr, " (");
1998 print_type(path->top_type);
1999 fprintf(stderr, ")");
2004 * Return the top type path entry, ie. in a path
2005 * (type).a.b returns the b.
2007 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2009 size_t len = ARR_LEN(path->path);
2011 return &path->path[len-1];
2015 * Enlarge the type path by an (empty) element.
2017 static type_path_entry_t *append_to_type_path(type_path_t *path)
2019 size_t len = ARR_LEN(path->path);
2020 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2022 type_path_entry_t *result = & path->path[len];
2023 memset(result, 0, sizeof(result[0]));
2028 * Descending into a sub-type. Enter the scope of the current
2031 static void descend_into_subtype(type_path_t *path)
2033 type_t *orig_top_type = path->top_type;
2034 type_t *top_type = skip_typeref(orig_top_type);
2036 assert(is_type_compound(top_type) || is_type_array(top_type));
2038 type_path_entry_t *top = append_to_type_path(path);
2039 top->type = top_type;
2041 if(is_type_compound(top_type)) {
2042 declaration_t *declaration = top_type->compound.declaration;
2043 declaration_t *entry = declaration->scope.declarations;
2044 top->v.compound_entry = entry;
2047 path->top_type = entry->type;
2049 path->top_type = NULL;
2052 assert(is_type_array(top_type));
2055 path->top_type = top_type->array.element_type;
2060 * Pop an entry from the given type path, ie. returning from
2061 * (type).a.b to (type).a
2063 static void ascend_from_subtype(type_path_t *path)
2065 type_path_entry_t *top = get_type_path_top(path);
2067 path->top_type = top->type;
2069 size_t len = ARR_LEN(path->path);
2070 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2074 * Pop entries from the given type path until the given
2075 * path level is reached.
2077 static void ascend_to(type_path_t *path, size_t top_path_level)
2079 size_t len = ARR_LEN(path->path);
2081 while(len > top_path_level) {
2082 ascend_from_subtype(path);
2083 len = ARR_LEN(path->path);
2087 static bool walk_designator(type_path_t *path, const designator_t *designator,
2088 bool used_in_offsetof)
2090 for( ; designator != NULL; designator = designator->next) {
2091 type_path_entry_t *top = get_type_path_top(path);
2092 type_t *orig_type = top->type;
2094 type_t *type = skip_typeref(orig_type);
2096 if(designator->symbol != NULL) {
2097 symbol_t *symbol = designator->symbol;
2098 if(!is_type_compound(type)) {
2099 if(is_type_valid(type)) {
2100 errorf(&designator->source_position,
2101 "'.%Y' designator used for non-compound type '%T'",
2107 declaration_t *declaration = type->compound.declaration;
2108 declaration_t *iter = declaration->scope.declarations;
2109 for( ; iter != NULL; iter = iter->next) {
2110 if(iter->symbol == symbol) {
2115 errorf(&designator->source_position,
2116 "'%T' has no member named '%Y'", orig_type, symbol);
2119 if(used_in_offsetof) {
2120 type_t *real_type = skip_typeref(iter->type);
2121 if(real_type->kind == TYPE_BITFIELD) {
2122 errorf(&designator->source_position,
2123 "offsetof designator '%Y' may not specify bitfield",
2129 top->type = orig_type;
2130 top->v.compound_entry = iter;
2131 orig_type = iter->type;
2133 expression_t *array_index = designator->array_index;
2134 assert(designator->array_index != NULL);
2136 if(!is_type_array(type)) {
2137 if(is_type_valid(type)) {
2138 errorf(&designator->source_position,
2139 "[%E] designator used for non-array type '%T'",
2140 array_index, orig_type);
2144 if(!is_type_valid(array_index->base.type)) {
2148 long index = fold_constant(array_index);
2149 if(!used_in_offsetof) {
2151 errorf(&designator->source_position,
2152 "array index [%E] must be positive", array_index);
2155 if(type->array.size_constant == true) {
2156 long array_size = type->array.size;
2157 if(index >= array_size) {
2158 errorf(&designator->source_position,
2159 "designator [%E] (%d) exceeds array size %d",
2160 array_index, index, array_size);
2166 top->type = orig_type;
2167 top->v.index = (size_t) index;
2168 orig_type = type->array.element_type;
2170 path->top_type = orig_type;
2172 if(designator->next != NULL) {
2173 descend_into_subtype(path);
2182 static void advance_current_object(type_path_t *path, size_t top_path_level)
2184 type_path_entry_t *top = get_type_path_top(path);
2186 type_t *type = skip_typeref(top->type);
2187 if(is_type_union(type)) {
2188 /* in unions only the first element is initialized */
2189 top->v.compound_entry = NULL;
2190 } else if(is_type_struct(type)) {
2191 declaration_t *entry = top->v.compound_entry;
2193 entry = entry->next;
2194 top->v.compound_entry = entry;
2196 path->top_type = entry->type;
2200 assert(is_type_array(type));
2204 if(!type->array.size_constant || top->v.index < type->array.size) {
2209 /* we're past the last member of the current sub-aggregate, try if we
2210 * can ascend in the type hierarchy and continue with another subobject */
2211 size_t len = ARR_LEN(path->path);
2213 if(len > top_path_level) {
2214 ascend_from_subtype(path);
2215 advance_current_object(path, top_path_level);
2217 path->top_type = NULL;
2222 * skip until token is found.
2224 static void skip_until(int type) {
2225 while(token.type != type) {
2226 if(token.type == T_EOF)
2233 * skip any {...} blocks until a closing bracket is reached.
2235 static void skip_initializers(void)
2237 if(token.type == '{')
2240 while(token.type != '}') {
2241 if(token.type == T_EOF)
2243 if(token.type == '{') {
2251 static initializer_t *create_empty_initializer(void)
2253 static initializer_t empty_initializer
2254 = { .list = { { INITIALIZER_LIST }, 0 } };
2255 return &empty_initializer;
2259 * Parse a part of an initialiser for a struct or union,
2261 static initializer_t *parse_sub_initializer(type_path_t *path,
2262 type_t *outer_type, size_t top_path_level,
2263 parse_initializer_env_t *env)
2265 if(token.type == '}') {
2266 /* empty initializer */
2267 return create_empty_initializer();
2270 type_t *orig_type = path->top_type;
2271 type_t *type = NULL;
2273 if (orig_type == NULL) {
2274 /* We are initializing an empty compound. */
2276 type = skip_typeref(orig_type);
2278 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2279 * initializers in this case. */
2280 if(!is_type_valid(type)) {
2281 skip_initializers();
2282 return create_empty_initializer();
2286 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2289 designator_t *designator = NULL;
2290 if(token.type == '.' || token.type == '[') {
2291 designator = parse_designation();
2293 /* reset path to toplevel, evaluate designator from there */
2294 ascend_to(path, top_path_level);
2295 if(!walk_designator(path, designator, false)) {
2296 /* can't continue after designation error */
2300 initializer_t *designator_initializer
2301 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2302 designator_initializer->designator.designator = designator;
2303 ARR_APP1(initializer_t*, initializers, designator_initializer);
2305 orig_type = path->top_type;
2306 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2311 if(token.type == '{') {
2312 if(type != NULL && is_type_scalar(type)) {
2313 sub = parse_scalar_initializer(type, env->must_be_constant);
2317 if (env->declaration != NULL)
2318 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2319 env->declaration->symbol);
2321 errorf(HERE, "extra brace group at end of initializer");
2323 descend_into_subtype(path);
2325 add_anchor_token('}');
2326 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2328 rem_anchor_token('}');
2331 ascend_from_subtype(path);
2335 goto error_parse_next;
2339 /* must be an expression */
2340 expression_t *expression = parse_assignment_expression();
2342 if(env->must_be_constant && !is_initializer_constant(expression)) {
2343 errorf(&expression->base.source_position,
2344 "Initialisation expression '%E' is not constant\n",
2349 /* we are already outside, ... */
2353 /* handle { "string" } special case */
2354 if((expression->kind == EXPR_STRING_LITERAL
2355 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2356 && outer_type != NULL) {
2357 sub = initializer_from_expression(outer_type, expression);
2359 if(token.type == ',') {
2362 if(token.type != '}') {
2363 warningf(HERE, "excessive elements in initializer for type '%T'",
2366 /* TODO: eat , ... */
2371 /* descend into subtypes until expression matches type */
2373 orig_type = path->top_type;
2374 type = skip_typeref(orig_type);
2376 sub = initializer_from_expression(orig_type, expression);
2380 if(!is_type_valid(type)) {
2383 if(is_type_scalar(type)) {
2384 errorf(&expression->base.source_position,
2385 "expression '%E' doesn't match expected type '%T'",
2386 expression, orig_type);
2390 descend_into_subtype(path);
2394 /* update largest index of top array */
2395 const type_path_entry_t *first = &path->path[0];
2396 type_t *first_type = first->type;
2397 first_type = skip_typeref(first_type);
2398 if(is_type_array(first_type)) {
2399 size_t index = first->v.index;
2400 if(index > path->max_index)
2401 path->max_index = index;
2405 /* append to initializers list */
2406 ARR_APP1(initializer_t*, initializers, sub);
2409 if(env->declaration != NULL)
2410 warningf(HERE, "excess elements in struct initializer for '%Y'",
2411 env->declaration->symbol);
2413 warningf(HERE, "excess elements in struct initializer");
2417 if(token.type == '}') {
2421 if(token.type == '}') {
2426 /* advance to the next declaration if we are not at the end */
2427 advance_current_object(path, top_path_level);
2428 orig_type = path->top_type;
2429 if(orig_type != NULL)
2430 type = skip_typeref(orig_type);
2436 size_t len = ARR_LEN(initializers);
2437 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2438 initializer_t *result = allocate_ast_zero(size);
2439 result->kind = INITIALIZER_LIST;
2440 result->list.len = len;
2441 memcpy(&result->list.initializers, initializers,
2442 len * sizeof(initializers[0]));
2444 DEL_ARR_F(initializers);
2445 ascend_to(path, top_path_level+1);
2450 skip_initializers();
2451 DEL_ARR_F(initializers);
2452 ascend_to(path, top_path_level+1);
2457 * Parses an initializer. Parsers either a compound literal
2458 * (env->declaration == NULL) or an initializer of a declaration.
2460 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2462 type_t *type = skip_typeref(env->type);
2463 initializer_t *result = NULL;
2466 if(is_type_scalar(type)) {
2467 result = parse_scalar_initializer(type, env->must_be_constant);
2468 } else if(token.type == '{') {
2472 memset(&path, 0, sizeof(path));
2473 path.top_type = env->type;
2474 path.path = NEW_ARR_F(type_path_entry_t, 0);
2476 descend_into_subtype(&path);
2478 add_anchor_token('}');
2479 result = parse_sub_initializer(&path, env->type, 1, env);
2480 rem_anchor_token('}');
2482 max_index = path.max_index;
2483 DEL_ARR_F(path.path);
2487 /* parse_scalar_initializer() also works in this case: we simply
2488 * have an expression without {} around it */
2489 result = parse_scalar_initializer(type, env->must_be_constant);
2492 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2493 * the array type size */
2494 if(is_type_array(type) && type->array.size_expression == NULL
2495 && result != NULL) {
2497 switch (result->kind) {
2498 case INITIALIZER_LIST:
2499 size = max_index + 1;
2502 case INITIALIZER_STRING:
2503 size = result->string.string.size;
2506 case INITIALIZER_WIDE_STRING:
2507 size = result->wide_string.string.size;
2510 case INITIALIZER_DESIGNATOR:
2511 case INITIALIZER_VALUE:
2512 /* can happen for parse errors */
2517 internal_errorf(HERE, "invalid initializer type");
2520 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2521 cnst->base.type = type_size_t;
2522 cnst->conste.v.int_value = size;
2524 type_t *new_type = duplicate_type(type);
2526 new_type->array.size_expression = cnst;
2527 new_type->array.size_constant = true;
2528 new_type->array.size = size;
2529 env->type = new_type;
2537 static declaration_t *append_declaration(declaration_t *declaration);
2539 static declaration_t *parse_compound_type_specifier(bool is_struct)
2541 gnu_attribute_t *attributes = NULL;
2542 decl_modifiers_t modifiers = 0;
2549 symbol_t *symbol = NULL;
2550 declaration_t *declaration = NULL;
2552 if (token.type == T___attribute__) {
2553 modifiers |= parse_attributes(&attributes);
2556 if(token.type == T_IDENTIFIER) {
2557 symbol = token.v.symbol;
2561 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2563 declaration = get_declaration(symbol, NAMESPACE_UNION);
2565 } else if(token.type != '{') {
2567 parse_error_expected("while parsing struct type specifier",
2568 T_IDENTIFIER, '{', NULL);
2570 parse_error_expected("while parsing union type specifier",
2571 T_IDENTIFIER, '{', NULL);
2577 if(declaration == NULL) {
2578 declaration = allocate_declaration_zero();
2579 declaration->namespc =
2580 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2581 declaration->source_position = token.source_position;
2582 declaration->symbol = symbol;
2583 declaration->parent_scope = scope;
2584 if (symbol != NULL) {
2585 environment_push(declaration);
2587 append_declaration(declaration);
2590 if(token.type == '{') {
2591 if (declaration->init.complete) {
2592 assert(symbol != NULL);
2593 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2594 is_struct ? "struct" : "union", symbol,
2595 &declaration->source_position);
2596 declaration->scope.declarations = NULL;
2598 declaration->init.complete = true;
2600 parse_compound_type_entries(declaration);
2601 modifiers |= parse_attributes(&attributes);
2604 declaration->modifiers |= modifiers;
2608 static void parse_enum_entries(type_t *const enum_type)
2612 if(token.type == '}') {
2614 errorf(HERE, "empty enum not allowed");
2618 add_anchor_token('}');
2620 if(token.type != T_IDENTIFIER) {
2621 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2623 rem_anchor_token('}');
2627 declaration_t *const entry = allocate_declaration_zero();
2628 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2629 entry->type = enum_type;
2630 entry->symbol = token.v.symbol;
2631 entry->source_position = token.source_position;
2634 if(token.type == '=') {
2636 expression_t *value = parse_constant_expression();
2638 value = create_implicit_cast(value, enum_type);
2639 entry->init.enum_value = value;
2644 record_declaration(entry);
2646 if(token.type != ',')
2649 } while(token.type != '}');
2650 rem_anchor_token('}');
2658 static type_t *parse_enum_specifier(void)
2660 gnu_attribute_t *attributes = NULL;
2661 declaration_t *declaration;
2665 if(token.type == T_IDENTIFIER) {
2666 symbol = token.v.symbol;
2669 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2670 } else if(token.type != '{') {
2671 parse_error_expected("while parsing enum type specifier",
2672 T_IDENTIFIER, '{', NULL);
2679 if(declaration == NULL) {
2680 declaration = allocate_declaration_zero();
2681 declaration->namespc = NAMESPACE_ENUM;
2682 declaration->source_position = token.source_position;
2683 declaration->symbol = symbol;
2684 declaration->parent_scope = scope;
2687 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2688 type->enumt.declaration = declaration;
2690 if(token.type == '{') {
2691 if(declaration->init.complete) {
2692 errorf(HERE, "multiple definitions of enum %Y", symbol);
2694 if (symbol != NULL) {
2695 environment_push(declaration);
2697 append_declaration(declaration);
2698 declaration->init.complete = true;
2700 parse_enum_entries(type);
2701 parse_attributes(&attributes);
2708 * if a symbol is a typedef to another type, return true
2710 static bool is_typedef_symbol(symbol_t *symbol)
2712 const declaration_t *const declaration =
2713 get_declaration(symbol, NAMESPACE_NORMAL);
2715 declaration != NULL &&
2716 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2719 static type_t *parse_typeof(void)
2726 add_anchor_token(')');
2728 expression_t *expression = NULL;
2731 switch(token.type) {
2732 case T___extension__:
2733 /* this can be a prefix to a typename or an expression */
2734 /* we simply eat it now. */
2737 } while(token.type == T___extension__);
2741 if(is_typedef_symbol(token.v.symbol)) {
2742 type = parse_typename();
2744 expression = parse_expression();
2745 type = expression->base.type;
2750 type = parse_typename();
2754 expression = parse_expression();
2755 type = expression->base.type;
2759 rem_anchor_token(')');
2762 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2763 typeof_type->typeoft.expression = expression;
2764 typeof_type->typeoft.typeof_type = type;
2772 SPECIFIER_SIGNED = 1 << 0,
2773 SPECIFIER_UNSIGNED = 1 << 1,
2774 SPECIFIER_LONG = 1 << 2,
2775 SPECIFIER_INT = 1 << 3,
2776 SPECIFIER_DOUBLE = 1 << 4,
2777 SPECIFIER_CHAR = 1 << 5,
2778 SPECIFIER_SHORT = 1 << 6,
2779 SPECIFIER_LONG_LONG = 1 << 7,
2780 SPECIFIER_FLOAT = 1 << 8,
2781 SPECIFIER_BOOL = 1 << 9,
2782 SPECIFIER_VOID = 1 << 10,
2783 SPECIFIER_INT8 = 1 << 11,
2784 SPECIFIER_INT16 = 1 << 12,
2785 SPECIFIER_INT32 = 1 << 13,
2786 SPECIFIER_INT64 = 1 << 14,
2787 SPECIFIER_INT128 = 1 << 15,
2788 SPECIFIER_COMPLEX = 1 << 16,
2789 SPECIFIER_IMAGINARY = 1 << 17,
2792 static type_t *create_builtin_type(symbol_t *const symbol,
2793 type_t *const real_type)
2795 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2796 type->builtin.symbol = symbol;
2797 type->builtin.real_type = real_type;
2799 type_t *result = typehash_insert(type);
2800 if(type != result) {
2807 static type_t *get_typedef_type(symbol_t *symbol)
2809 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2810 if(declaration == NULL ||
2811 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2814 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2815 type->typedeft.declaration = declaration;
2821 * check for the allowed MS alignment values.
2823 static bool check_elignment_value(long long intvalue) {
2824 if(intvalue < 1 || intvalue > 8192) {
2825 errorf(HERE, "illegal alignment value");
2828 unsigned v = (unsigned)intvalue;
2829 for(unsigned i = 1; i <= 8192; i += i) {
2833 errorf(HERE, "alignment must be power of two");
2837 #define DET_MOD(name, tag) do { \
2838 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2839 *modifiers |= tag; \
2842 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2844 decl_modifiers_t *modifiers = &specifiers->modifiers;
2847 if(token.type == T_restrict) {
2849 DET_MOD(restrict, DM_RESTRICT);
2851 } else if(token.type != T_IDENTIFIER)
2853 symbol_t *symbol = token.v.symbol;
2854 if(symbol == sym_align) {
2857 if(token.type != T_INTEGER)
2859 if(check_elignment_value(token.v.intvalue)) {
2860 if(specifiers->alignment != 0)
2861 warningf(HERE, "align used more than once");
2862 specifiers->alignment = (unsigned char)token.v.intvalue;
2866 } else if(symbol == sym_allocate) {
2869 if(token.type != T_IDENTIFIER)
2871 (void)token.v.symbol;
2873 } else if(symbol == sym_dllimport) {
2875 DET_MOD(dllimport, DM_DLLIMPORT);
2876 } else if(symbol == sym_dllexport) {
2878 DET_MOD(dllexport, DM_DLLEXPORT);
2879 } else if(symbol == sym_thread) {
2881 DET_MOD(thread, DM_THREAD);
2882 } else if(symbol == sym_naked) {
2884 DET_MOD(naked, DM_NAKED);
2885 } else if(symbol == sym_noinline) {
2887 DET_MOD(noinline, DM_NOINLINE);
2888 } else if(symbol == sym_noreturn) {
2890 DET_MOD(noreturn, DM_NORETURN);
2891 } else if(symbol == sym_nothrow) {
2893 DET_MOD(nothrow, DM_NOTHROW);
2894 } else if(symbol == sym_novtable) {
2896 DET_MOD(novtable, DM_NOVTABLE);
2897 } else if(symbol == sym_property) {
2901 bool is_get = false;
2902 if(token.type != T_IDENTIFIER)
2904 if(token.v.symbol == sym_get) {
2906 } else if(token.v.symbol == sym_put) {
2908 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2913 if(token.type != T_IDENTIFIER)
2916 if(specifiers->get_property_sym != NULL) {
2917 errorf(HERE, "get property name already specified");
2919 specifiers->get_property_sym = token.v.symbol;
2922 if(specifiers->put_property_sym != NULL) {
2923 errorf(HERE, "put property name already specified");
2925 specifiers->put_property_sym = token.v.symbol;
2929 if(token.type == ',') {
2936 } else if(symbol == sym_selectany) {
2938 DET_MOD(selectany, DM_SELECTANY);
2939 } else if(symbol == sym_uuid) {
2942 if(token.type != T_STRING_LITERAL)
2946 } else if(symbol == sym_deprecated) {
2948 if(specifiers->deprecated != 0)
2949 warningf(HERE, "deprecated used more than once");
2950 specifiers->deprecated = 1;
2951 if(token.type == '(') {
2953 if(token.type == T_STRING_LITERAL) {
2954 specifiers->deprecated_string = token.v.string.begin;
2957 errorf(HERE, "string literal expected");
2961 } else if(symbol == sym_noalias) {
2963 DET_MOD(noalias, DM_NOALIAS);
2965 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2967 if(token.type == '(')
2971 if (token.type == ',')
2978 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2980 type_t *type = NULL;
2981 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2982 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
2983 unsigned type_specifiers = 0;
2986 specifiers->source_position = token.source_position;
2989 switch(token.type) {
2992 #define MATCH_STORAGE_CLASS(token, class) \
2994 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2995 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2997 specifiers->declared_storage_class = class; \
3001 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3002 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3003 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3004 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3005 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3010 add_anchor_token(')');
3011 parse_microsoft_extended_decl_modifier(specifiers);
3012 rem_anchor_token(')');
3017 switch (specifiers->declared_storage_class) {
3018 case STORAGE_CLASS_NONE:
3019 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3022 case STORAGE_CLASS_EXTERN:
3023 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3026 case STORAGE_CLASS_STATIC:
3027 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3031 errorf(HERE, "multiple storage classes in declaration specifiers");
3037 /* type qualifiers */
3038 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3040 qualifiers |= qualifier; \
3044 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3045 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3046 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3047 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3048 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3049 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3050 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3051 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3053 case T___extension__:
3058 /* type specifiers */
3059 #define MATCH_SPECIFIER(token, specifier, name) \
3062 if(type_specifiers & specifier) { \
3063 errorf(HERE, "multiple " name " type specifiers given"); \
3065 type_specifiers |= specifier; \
3069 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3070 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3071 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3072 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3073 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3074 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3075 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3076 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3077 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3078 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3079 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3080 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3081 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3082 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3083 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3084 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3086 case T__forceinline:
3087 /* only in microsoft mode */
3088 specifiers->modifiers |= DM_FORCEINLINE;
3092 specifiers->is_inline = true;
3097 if(type_specifiers & SPECIFIER_LONG_LONG) {
3098 errorf(HERE, "multiple type specifiers given");
3099 } else if(type_specifiers & SPECIFIER_LONG) {
3100 type_specifiers |= SPECIFIER_LONG_LONG;
3102 type_specifiers |= SPECIFIER_LONG;
3107 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3109 type->compound.declaration = parse_compound_type_specifier(true);
3113 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3114 type->compound.declaration = parse_compound_type_specifier(false);
3115 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3116 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3120 type = parse_enum_specifier();
3123 type = parse_typeof();
3125 case T___builtin_va_list:
3126 type = duplicate_type(type_valist);
3130 case T___attribute__:
3131 specifiers->modifiers
3132 |= parse_attributes(&specifiers->gnu_attributes);
3133 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3134 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3137 case T_IDENTIFIER: {
3138 /* only parse identifier if we haven't found a type yet */
3139 if(type != NULL || type_specifiers != 0)
3140 goto finish_specifiers;
3142 type_t *typedef_type = get_typedef_type(token.v.symbol);
3144 if(typedef_type == NULL)
3145 goto finish_specifiers;
3148 type = typedef_type;
3152 /* function specifier */
3154 goto finish_specifiers;
3161 atomic_type_kind_t atomic_type;
3163 /* match valid basic types */
3164 switch(type_specifiers) {
3165 case SPECIFIER_VOID:
3166 atomic_type = ATOMIC_TYPE_VOID;
3168 case SPECIFIER_CHAR:
3169 atomic_type = ATOMIC_TYPE_CHAR;
3171 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3172 atomic_type = ATOMIC_TYPE_SCHAR;
3174 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3175 atomic_type = ATOMIC_TYPE_UCHAR;
3177 case SPECIFIER_SHORT:
3178 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3179 case SPECIFIER_SHORT | SPECIFIER_INT:
3180 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3181 atomic_type = ATOMIC_TYPE_SHORT;
3183 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3184 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3185 atomic_type = ATOMIC_TYPE_USHORT;
3188 case SPECIFIER_SIGNED:
3189 case SPECIFIER_SIGNED | SPECIFIER_INT:
3190 atomic_type = ATOMIC_TYPE_INT;
3192 case SPECIFIER_UNSIGNED:
3193 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3194 atomic_type = ATOMIC_TYPE_UINT;
3196 case SPECIFIER_LONG:
3197 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3198 case SPECIFIER_LONG | SPECIFIER_INT:
3199 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3200 atomic_type = ATOMIC_TYPE_LONG;
3202 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3203 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3204 atomic_type = ATOMIC_TYPE_ULONG;
3206 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3207 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3208 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3209 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3211 atomic_type = ATOMIC_TYPE_LONGLONG;
3213 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3214 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3216 atomic_type = ATOMIC_TYPE_ULONGLONG;
3219 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3220 atomic_type = unsigned_int8_type_kind;
3223 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3224 atomic_type = unsigned_int16_type_kind;
3227 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3228 atomic_type = unsigned_int32_type_kind;
3231 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3232 atomic_type = unsigned_int64_type_kind;
3235 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3236 atomic_type = unsigned_int128_type_kind;
3239 case SPECIFIER_INT8:
3240 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3241 atomic_type = int8_type_kind;
3244 case SPECIFIER_INT16:
3245 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3246 atomic_type = int16_type_kind;
3249 case SPECIFIER_INT32:
3250 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3251 atomic_type = int32_type_kind;
3254 case SPECIFIER_INT64:
3255 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3256 atomic_type = int64_type_kind;
3259 case SPECIFIER_INT128:
3260 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3261 atomic_type = int128_type_kind;
3264 case SPECIFIER_FLOAT:
3265 atomic_type = ATOMIC_TYPE_FLOAT;
3267 case SPECIFIER_DOUBLE:
3268 atomic_type = ATOMIC_TYPE_DOUBLE;
3270 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3271 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3273 case SPECIFIER_BOOL:
3274 atomic_type = ATOMIC_TYPE_BOOL;
3276 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3277 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3278 atomic_type = ATOMIC_TYPE_FLOAT;
3280 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3281 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3282 atomic_type = ATOMIC_TYPE_DOUBLE;
3284 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3285 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3286 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3289 /* invalid specifier combination, give an error message */
3290 if(type_specifiers == 0) {
3291 if (! strict_mode) {
3292 if (warning.implicit_int) {
3293 warningf(HERE, "no type specifiers in declaration, using 'int'");
3295 atomic_type = ATOMIC_TYPE_INT;
3298 errorf(HERE, "no type specifiers given in declaration");
3300 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3301 (type_specifiers & SPECIFIER_UNSIGNED)) {
3302 errorf(HERE, "signed and unsigned specifiers gives");
3303 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3304 errorf(HERE, "only integer types can be signed or unsigned");
3306 errorf(HERE, "multiple datatypes in declaration");
3308 atomic_type = ATOMIC_TYPE_INVALID;
3311 if(type_specifiers & SPECIFIER_COMPLEX &&
3312 atomic_type != ATOMIC_TYPE_INVALID) {
3313 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3314 type->complex.akind = atomic_type;
3315 } else if(type_specifiers & SPECIFIER_IMAGINARY &&
3316 atomic_type != ATOMIC_TYPE_INVALID) {
3317 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3318 type->imaginary.akind = atomic_type;
3320 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3321 type->atomic.akind = atomic_type;
3325 if(type_specifiers != 0) {
3326 errorf(HERE, "multiple datatypes in declaration");
3330 /* FIXME: check type qualifiers here */
3332 type->base.qualifiers = qualifiers;
3333 type->base.modifiers = modifiers;
3335 type_t *result = typehash_insert(type);
3336 if(newtype && result != type) {
3340 specifiers->type = result;
3345 static type_qualifiers_t parse_type_qualifiers(void)
3347 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3350 switch(token.type) {
3351 /* type qualifiers */
3352 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3353 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3354 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3355 /* microsoft extended type modifiers */
3356 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3357 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3358 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3359 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3360 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3368 static declaration_t *parse_identifier_list(void)
3370 declaration_t *declarations = NULL;
3371 declaration_t *last_declaration = NULL;
3373 declaration_t *const declaration = allocate_declaration_zero();
3374 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3375 declaration->source_position = token.source_position;
3376 declaration->symbol = token.v.symbol;
3379 if(last_declaration != NULL) {
3380 last_declaration->next = declaration;
3382 declarations = declaration;
3384 last_declaration = declaration;
3386 if (token.type != ',') {
3390 } while(token.type == T_IDENTIFIER);
3392 return declarations;
3395 static void semantic_parameter(declaration_t *declaration)
3397 /* TODO: improve error messages */
3399 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3400 errorf(HERE, "typedef not allowed in parameter list");
3401 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3402 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3403 errorf(HERE, "parameter may only have none or register storage class");
3406 type_t *const orig_type = declaration->type;
3407 type_t * type = skip_typeref(orig_type);
3409 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3410 * into a pointer. § 6.7.5.3 (7) */
3411 if (is_type_array(type)) {
3412 type_t *const element_type = type->array.element_type;
3414 type = make_pointer_type(element_type, type->base.qualifiers);
3416 declaration->type = type;
3419 if(is_type_incomplete(type)) {
3420 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3421 orig_type, declaration->symbol);
3425 static declaration_t *parse_parameter(void)
3427 declaration_specifiers_t specifiers;
3428 memset(&specifiers, 0, sizeof(specifiers));
3430 parse_declaration_specifiers(&specifiers);
3432 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3437 static declaration_t *parse_parameters(function_type_t *type)
3439 declaration_t *declarations = NULL;
3442 add_anchor_token(')');
3443 int saved_comma_state = save_and_reset_anchor_state(',');
3445 if(token.type == T_IDENTIFIER) {
3446 symbol_t *symbol = token.v.symbol;
3447 if(!is_typedef_symbol(symbol)) {
3448 type->kr_style_parameters = true;
3449 declarations = parse_identifier_list();
3450 goto parameters_finished;
3454 if(token.type == ')') {
3455 type->unspecified_parameters = 1;
3456 goto parameters_finished;
3459 declaration_t *declaration;
3460 declaration_t *last_declaration = NULL;
3461 function_parameter_t *parameter;
3462 function_parameter_t *last_parameter = NULL;
3465 switch(token.type) {
3469 goto parameters_finished;
3472 case T___extension__:
3474 declaration = parse_parameter();
3476 /* func(void) is not a parameter */
3477 if (last_parameter == NULL
3478 && token.type == ')'
3479 && declaration->symbol == NULL
3480 && skip_typeref(declaration->type) == type_void) {
3481 goto parameters_finished;
3483 semantic_parameter(declaration);
3485 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3486 memset(parameter, 0, sizeof(parameter[0]));
3487 parameter->type = declaration->type;
3489 if(last_parameter != NULL) {
3490 last_declaration->next = declaration;
3491 last_parameter->next = parameter;
3493 type->parameters = parameter;
3494 declarations = declaration;
3496 last_parameter = parameter;
3497 last_declaration = declaration;
3501 goto parameters_finished;
3503 if (token.type != ',') {
3504 goto parameters_finished;
3510 parameters_finished:
3511 rem_anchor_token(')');
3514 restore_anchor_state(',', saved_comma_state);
3515 return declarations;
3518 restore_anchor_state(',', saved_comma_state);
3527 } construct_type_kind_t;
3529 typedef struct construct_type_t construct_type_t;
3530 struct construct_type_t {
3531 construct_type_kind_t kind;
3532 construct_type_t *next;
3535 typedef struct parsed_pointer_t parsed_pointer_t;
3536 struct parsed_pointer_t {
3537 construct_type_t construct_type;
3538 type_qualifiers_t type_qualifiers;
3541 typedef struct construct_function_type_t construct_function_type_t;
3542 struct construct_function_type_t {
3543 construct_type_t construct_type;
3544 type_t *function_type;
3547 typedef struct parsed_array_t parsed_array_t;
3548 struct parsed_array_t {
3549 construct_type_t construct_type;
3550 type_qualifiers_t type_qualifiers;
3556 typedef struct construct_base_type_t construct_base_type_t;
3557 struct construct_base_type_t {
3558 construct_type_t construct_type;
3562 static construct_type_t *parse_pointer_declarator(void)
3566 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3567 memset(pointer, 0, sizeof(pointer[0]));
3568 pointer->construct_type.kind = CONSTRUCT_POINTER;
3569 pointer->type_qualifiers = parse_type_qualifiers();
3571 return (construct_type_t*) pointer;
3574 static construct_type_t *parse_array_declarator(void)
3577 add_anchor_token(']');
3579 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3580 memset(array, 0, sizeof(array[0]));
3581 array->construct_type.kind = CONSTRUCT_ARRAY;
3583 if(token.type == T_static) {
3584 array->is_static = true;
3588 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3589 if(type_qualifiers != 0) {
3590 if(token.type == T_static) {
3591 array->is_static = true;
3595 array->type_qualifiers = type_qualifiers;
3597 if(token.type == '*' && look_ahead(1)->type == ']') {
3598 array->is_variable = true;
3600 } else if(token.type != ']') {
3601 array->size = parse_assignment_expression();
3604 rem_anchor_token(']');
3607 return (construct_type_t*) array;
3612 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3615 if(declaration != NULL) {
3616 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3618 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3621 declaration_t *parameters = parse_parameters(&type->function);
3622 if(declaration != NULL) {
3623 declaration->scope.declarations = parameters;
3626 construct_function_type_t *construct_function_type =
3627 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3628 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3629 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3630 construct_function_type->function_type = type;
3632 return (construct_type_t*) construct_function_type;
3635 static void fix_declaration_type(declaration_t *declaration)
3637 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3638 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3640 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3641 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3643 if (declaration->type->base.modifiers == type_modifiers)
3646 type_t *copy = duplicate_type(declaration->type);
3647 copy->base.modifiers = type_modifiers;
3649 type_t *result = typehash_insert(copy);
3650 if (result != copy) {
3651 obstack_free(type_obst, copy);
3654 declaration->type = result;
3657 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3658 bool may_be_abstract)
3660 /* construct a single linked list of construct_type_t's which describe
3661 * how to construct the final declarator type */
3662 construct_type_t *first = NULL;
3663 construct_type_t *last = NULL;
3664 gnu_attribute_t *attributes = NULL;
3666 decl_modifiers_t modifiers = parse_attributes(&attributes);
3669 while(token.type == '*') {
3670 construct_type_t *type = parse_pointer_declarator();
3680 /* TODO: find out if this is correct */
3681 modifiers |= parse_attributes(&attributes);
3684 construct_type_t *inner_types = NULL;
3686 switch(token.type) {
3688 if(declaration == NULL) {
3689 errorf(HERE, "no identifier expected in typename");
3691 declaration->symbol = token.v.symbol;
3692 declaration->source_position = token.source_position;
3698 add_anchor_token(')');
3699 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3700 rem_anchor_token(')');
3706 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3707 /* avoid a loop in the outermost scope, because eat_statement doesn't
3709 if(token.type == '}' && current_function == NULL) {
3717 construct_type_t *p = last;
3720 construct_type_t *type;
3721 switch(token.type) {
3723 type = parse_function_declarator(declaration);
3726 type = parse_array_declarator();
3729 goto declarator_finished;
3732 /* insert in the middle of the list (behind p) */
3734 type->next = p->next;
3745 declarator_finished:
3746 modifiers |= parse_attributes(&attributes);
3747 if (declaration != NULL) {
3748 declaration->modifiers |= modifiers;
3751 /* append inner_types at the end of the list, we don't to set last anymore
3752 * as it's not needed anymore */
3754 assert(first == NULL);
3755 first = inner_types;
3757 last->next = inner_types;
3765 static type_t *construct_declarator_type(construct_type_t *construct_list,
3768 construct_type_t *iter = construct_list;
3769 for( ; iter != NULL; iter = iter->next) {
3770 switch(iter->kind) {
3771 case CONSTRUCT_INVALID:
3772 internal_errorf(HERE, "invalid type construction found");
3773 case CONSTRUCT_FUNCTION: {
3774 construct_function_type_t *construct_function_type
3775 = (construct_function_type_t*) iter;
3777 type_t *function_type = construct_function_type->function_type;
3779 function_type->function.return_type = type;
3781 type_t *skipped_return_type = skip_typeref(type);
3782 if (is_type_function(skipped_return_type)) {
3783 errorf(HERE, "function returning function is not allowed");
3784 type = type_error_type;
3785 } else if (is_type_array(skipped_return_type)) {
3786 errorf(HERE, "function returning array is not allowed");
3787 type = type_error_type;
3789 type = function_type;
3794 case CONSTRUCT_POINTER: {
3795 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3796 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3797 pointer_type->pointer.points_to = type;
3798 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3800 type = pointer_type;
3804 case CONSTRUCT_ARRAY: {
3805 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3806 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3808 expression_t *size_expression = parsed_array->size;
3809 if(size_expression != NULL) {
3811 = create_implicit_cast(size_expression, type_size_t);
3814 array_type->base.qualifiers = parsed_array->type_qualifiers;
3815 array_type->array.element_type = type;
3816 array_type->array.is_static = parsed_array->is_static;
3817 array_type->array.is_variable = parsed_array->is_variable;
3818 array_type->array.size_expression = size_expression;
3820 if(size_expression != NULL) {
3821 if(is_constant_expression(size_expression)) {
3822 array_type->array.size_constant = true;
3823 array_type->array.size
3824 = fold_constant(size_expression);
3826 array_type->array.is_vla = true;
3830 type_t *skipped_type = skip_typeref(type);
3831 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3832 errorf(HERE, "array of void is not allowed");
3833 type = type_error_type;
3841 type_t *hashed_type = typehash_insert(type);
3842 if(hashed_type != type) {
3843 /* the function type was constructed earlier freeing it here will
3844 * destroy other types... */
3845 if(iter->kind != CONSTRUCT_FUNCTION) {
3855 static declaration_t *parse_declarator(
3856 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3858 declaration_t *const declaration = allocate_declaration_zero();
3859 declaration->declared_storage_class = specifiers->declared_storage_class;
3860 declaration->modifiers = specifiers->modifiers;
3861 declaration->deprecated = specifiers->deprecated;
3862 declaration->deprecated_string = specifiers->deprecated_string;
3863 declaration->get_property_sym = specifiers->get_property_sym;
3864 declaration->put_property_sym = specifiers->put_property_sym;
3865 declaration->is_inline = specifiers->is_inline;
3867 declaration->storage_class = specifiers->declared_storage_class;
3868 if(declaration->storage_class == STORAGE_CLASS_NONE
3869 && scope != global_scope) {
3870 declaration->storage_class = STORAGE_CLASS_AUTO;
3873 if(specifiers->alignment != 0) {
3874 /* TODO: add checks here */
3875 declaration->alignment = specifiers->alignment;
3878 construct_type_t *construct_type
3879 = parse_inner_declarator(declaration, may_be_abstract);
3880 type_t *const type = specifiers->type;
3881 declaration->type = construct_declarator_type(construct_type, type);
3883 fix_declaration_type(declaration);
3885 if(construct_type != NULL) {
3886 obstack_free(&temp_obst, construct_type);
3892 static type_t *parse_abstract_declarator(type_t *base_type)
3894 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3896 type_t *result = construct_declarator_type(construct_type, base_type);
3897 if(construct_type != NULL) {
3898 obstack_free(&temp_obst, construct_type);
3904 static declaration_t *append_declaration(declaration_t* const declaration)
3906 if (last_declaration != NULL) {
3907 last_declaration->next = declaration;
3909 scope->declarations = declaration;
3911 last_declaration = declaration;
3916 * Check if the declaration of main is suspicious. main should be a
3917 * function with external linkage, returning int, taking either zero
3918 * arguments, two, or three arguments of appropriate types, ie.
3920 * int main([ int argc, char **argv [, char **env ] ]).
3922 * @param decl the declaration to check
3923 * @param type the function type of the declaration
3925 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3927 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3928 warningf(&decl->source_position,
3929 "'main' is normally a non-static function");
3931 if (skip_typeref(func_type->return_type) != type_int) {
3932 warningf(&decl->source_position,
3933 "return type of 'main' should be 'int', but is '%T'",
3934 func_type->return_type);
3936 const function_parameter_t *parm = func_type->parameters;
3938 type_t *const first_type = parm->type;
3939 if (!types_compatible(skip_typeref(first_type), type_int)) {
3940 warningf(&decl->source_position,
3941 "first argument of 'main' should be 'int', but is '%T'", first_type);
3945 type_t *const second_type = parm->type;
3946 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3947 warningf(&decl->source_position,
3948 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3952 type_t *const third_type = parm->type;
3953 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3954 warningf(&decl->source_position,
3955 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3959 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3963 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3969 * Check if a symbol is the equal to "main".
3971 static bool is_sym_main(const symbol_t *const sym)
3973 return strcmp(sym->string, "main") == 0;
3976 static declaration_t *internal_record_declaration(
3977 declaration_t *const declaration,
3978 const bool is_function_definition)
3980 const symbol_t *const symbol = declaration->symbol;
3981 const namespace_t namespc = (namespace_t)declaration->namespc;
3983 assert(declaration->symbol != NULL);
3984 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3986 type_t *const orig_type = declaration->type;
3987 type_t *const type = skip_typeref(orig_type);
3988 if (is_type_function(type) &&
3989 type->function.unspecified_parameters &&
3990 warning.strict_prototypes &&
3991 previous_declaration == NULL) {
3992 warningf(&declaration->source_position,
3993 "function declaration '%#T' is not a prototype",
3994 orig_type, declaration->symbol);
3997 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3998 check_type_of_main(declaration, &type->function);
4001 assert(declaration != previous_declaration);
4002 if (previous_declaration != NULL
4003 && previous_declaration->parent_scope == scope) {
4004 /* can happen for K&R style declarations */
4005 if (previous_declaration->type == NULL) {
4006 previous_declaration->type = declaration->type;
4009 const type_t *prev_type = skip_typeref(previous_declaration->type);
4010 if (!types_compatible(type, prev_type)) {
4011 errorf(&declaration->source_position,
4012 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4013 orig_type, symbol, previous_declaration->type, symbol,
4014 &previous_declaration->source_position);
4016 unsigned old_storage_class = previous_declaration->storage_class;
4017 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4018 errorf(&declaration->source_position,
4019 "redeclaration of enum entry '%Y' (declared %P)",
4020 symbol, &previous_declaration->source_position);
4021 return previous_declaration;
4024 unsigned new_storage_class = declaration->storage_class;
4026 if (is_type_incomplete(prev_type)) {
4027 previous_declaration->type = type;
4031 /* pretend no storage class means extern for function
4032 * declarations (except if the previous declaration is neither
4033 * none nor extern) */
4034 if (is_type_function(type)) {
4035 if (prev_type->function.unspecified_parameters) {
4036 previous_declaration->type = type;
4040 switch (old_storage_class) {
4041 case STORAGE_CLASS_NONE:
4042 old_storage_class = STORAGE_CLASS_EXTERN;
4045 case STORAGE_CLASS_EXTERN:
4046 if (is_function_definition) {
4047 if (warning.missing_prototypes &&
4048 prev_type->function.unspecified_parameters &&
4049 !is_sym_main(symbol)) {
4050 warningf(&declaration->source_position,
4051 "no previous prototype for '%#T'",
4054 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4055 new_storage_class = STORAGE_CLASS_EXTERN;
4064 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4065 new_storage_class == STORAGE_CLASS_EXTERN) {
4066 warn_redundant_declaration:
4067 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4068 warningf(&declaration->source_position,
4069 "redundant declaration for '%Y' (declared %P)",
4070 symbol, &previous_declaration->source_position);
4072 } else if (current_function == NULL) {
4073 if (old_storage_class != STORAGE_CLASS_STATIC &&
4074 new_storage_class == STORAGE_CLASS_STATIC) {
4075 errorf(&declaration->source_position,
4076 "static declaration of '%Y' follows non-static declaration (declared %P)",
4077 symbol, &previous_declaration->source_position);
4078 } else if (old_storage_class != STORAGE_CLASS_EXTERN
4079 && !is_function_definition) {
4080 goto warn_redundant_declaration;
4081 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4082 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4083 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4085 } else if (old_storage_class == new_storage_class) {
4086 errorf(&declaration->source_position,
4087 "redeclaration of '%Y' (declared %P)",
4088 symbol, &previous_declaration->source_position);
4090 errorf(&declaration->source_position,
4091 "redeclaration of '%Y' with different linkage (declared %P)",
4092 symbol, &previous_declaration->source_position);
4096 if (declaration->is_inline)
4097 previous_declaration->is_inline = true;
4098 return previous_declaration;
4099 } else if (is_function_definition) {
4100 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4101 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4102 warningf(&declaration->source_position,
4103 "no previous prototype for '%#T'", orig_type, symbol);
4104 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4105 warningf(&declaration->source_position,
4106 "no previous declaration for '%#T'", orig_type,
4110 } else if (warning.missing_declarations &&
4111 scope == global_scope &&
4112 !is_type_function(type) && (
4113 declaration->storage_class == STORAGE_CLASS_NONE ||
4114 declaration->storage_class == STORAGE_CLASS_THREAD
4116 warningf(&declaration->source_position,
4117 "no previous declaration for '%#T'", orig_type, symbol);
4120 assert(declaration->parent_scope == NULL);
4121 assert(scope != NULL);
4123 declaration->parent_scope = scope;
4125 environment_push(declaration);
4126 return append_declaration(declaration);
4129 static declaration_t *record_declaration(declaration_t *declaration)
4131 return internal_record_declaration(declaration, false);
4134 static declaration_t *record_function_definition(declaration_t *declaration)
4136 return internal_record_declaration(declaration, true);
4139 static void parser_error_multiple_definition(declaration_t *declaration,
4140 const source_position_t *source_position)
4142 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4143 declaration->symbol, &declaration->source_position);
4146 static bool is_declaration_specifier(const token_t *token,
4147 bool only_specifiers_qualifiers)
4149 switch(token->type) {
4154 return is_typedef_symbol(token->v.symbol);
4156 case T___extension__:
4158 return !only_specifiers_qualifiers;
4165 static void parse_init_declarator_rest(declaration_t *declaration)
4169 type_t *orig_type = declaration->type;
4170 type_t *type = skip_typeref(orig_type);
4172 if(declaration->init.initializer != NULL) {
4173 parser_error_multiple_definition(declaration, HERE);
4176 bool must_be_constant = false;
4177 if(declaration->storage_class == STORAGE_CLASS_STATIC
4178 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4179 || declaration->parent_scope == global_scope) {
4180 must_be_constant = true;
4183 parse_initializer_env_t env;
4184 env.type = orig_type;
4185 env.must_be_constant = must_be_constant;
4186 env.declaration = declaration;
4188 initializer_t *initializer = parse_initializer(&env);
4190 if(env.type != orig_type) {
4191 orig_type = env.type;
4192 type = skip_typeref(orig_type);
4193 declaration->type = env.type;
4196 if(is_type_function(type)) {
4197 errorf(&declaration->source_position,
4198 "initializers not allowed for function types at declator '%Y' (type '%T')",
4199 declaration->symbol, orig_type);
4201 declaration->init.initializer = initializer;
4205 /* parse rest of a declaration without any declarator */
4206 static void parse_anonymous_declaration_rest(
4207 const declaration_specifiers_t *specifiers,
4208 parsed_declaration_func finished_declaration)
4212 declaration_t *const declaration = allocate_declaration_zero();
4213 declaration->type = specifiers->type;
4214 declaration->declared_storage_class = specifiers->declared_storage_class;
4215 declaration->source_position = specifiers->source_position;
4216 declaration->modifiers = specifiers->modifiers;
4218 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4219 warningf(&declaration->source_position,
4220 "useless storage class in empty declaration");
4222 declaration->storage_class = STORAGE_CLASS_NONE;
4224 type_t *type = declaration->type;
4225 switch (type->kind) {
4226 case TYPE_COMPOUND_STRUCT:
4227 case TYPE_COMPOUND_UNION: {
4228 if (type->compound.declaration->symbol == NULL) {
4229 warningf(&declaration->source_position,
4230 "unnamed struct/union that defines no instances");
4239 warningf(&declaration->source_position, "empty declaration");
4243 finished_declaration(declaration);
4246 static void parse_declaration_rest(declaration_t *ndeclaration,
4247 const declaration_specifiers_t *specifiers,
4248 parsed_declaration_func finished_declaration)
4250 add_anchor_token(';');
4251 add_anchor_token('=');
4252 add_anchor_token(',');
4254 declaration_t *declaration = finished_declaration(ndeclaration);
4256 type_t *orig_type = declaration->type;
4257 type_t *type = skip_typeref(orig_type);
4259 if (type->kind != TYPE_FUNCTION &&
4260 declaration->is_inline &&
4261 is_type_valid(type)) {
4262 warningf(&declaration->source_position,
4263 "variable '%Y' declared 'inline'\n", declaration->symbol);
4266 if(token.type == '=') {
4267 parse_init_declarator_rest(declaration);
4270 if(token.type != ',')
4274 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4279 rem_anchor_token(';');
4280 rem_anchor_token('=');
4281 rem_anchor_token(',');
4284 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4286 symbol_t *symbol = declaration->symbol;
4287 if(symbol == NULL) {
4288 errorf(HERE, "anonymous declaration not valid as function parameter");
4291 namespace_t namespc = (namespace_t) declaration->namespc;
4292 if(namespc != NAMESPACE_NORMAL) {
4293 return record_declaration(declaration);
4296 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4297 if(previous_declaration == NULL ||
4298 previous_declaration->parent_scope != scope) {
4299 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4304 if(previous_declaration->type == NULL) {
4305 previous_declaration->type = declaration->type;
4306 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4307 previous_declaration->storage_class = declaration->storage_class;
4308 previous_declaration->parent_scope = scope;
4309 return previous_declaration;
4311 return record_declaration(declaration);
4315 static void parse_declaration(parsed_declaration_func finished_declaration)
4317 declaration_specifiers_t specifiers;
4318 memset(&specifiers, 0, sizeof(specifiers));
4319 parse_declaration_specifiers(&specifiers);
4321 if(token.type == ';') {
4322 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4324 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4325 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4329 static type_t *get_default_promoted_type(type_t *orig_type)
4331 type_t *result = orig_type;
4333 type_t *type = skip_typeref(orig_type);
4334 if(is_type_integer(type)) {
4335 result = promote_integer(type);
4336 } else if(type == type_float) {
4337 result = type_double;
4343 static void parse_kr_declaration_list(declaration_t *declaration)
4345 type_t *type = skip_typeref(declaration->type);
4346 if (!is_type_function(type))
4349 if (!type->function.kr_style_parameters)
4352 /* push function parameters */
4353 int top = environment_top();
4354 scope_t *last_scope = scope;
4355 set_scope(&declaration->scope);
4357 declaration_t *parameter = declaration->scope.declarations;
4358 for ( ; parameter != NULL; parameter = parameter->next) {
4359 assert(parameter->parent_scope == NULL);
4360 parameter->parent_scope = scope;
4361 environment_push(parameter);
4364 /* parse declaration list */
4365 while (is_declaration_specifier(&token, false)) {
4366 parse_declaration(finished_kr_declaration);
4369 /* pop function parameters */
4370 assert(scope == &declaration->scope);
4371 set_scope(last_scope);
4372 environment_pop_to(top);
4374 /* update function type */
4375 type_t *new_type = duplicate_type(type);
4377 function_parameter_t *parameters = NULL;
4378 function_parameter_t *last_parameter = NULL;
4380 declaration_t *parameter_declaration = declaration->scope.declarations;
4381 for( ; parameter_declaration != NULL;
4382 parameter_declaration = parameter_declaration->next) {
4383 type_t *parameter_type = parameter_declaration->type;
4384 if(parameter_type == NULL) {
4386 errorf(HERE, "no type specified for function parameter '%Y'",
4387 parameter_declaration->symbol);
4389 if (warning.implicit_int) {
4390 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4391 parameter_declaration->symbol);
4393 parameter_type = type_int;
4394 parameter_declaration->type = parameter_type;
4398 semantic_parameter(parameter_declaration);
4399 parameter_type = parameter_declaration->type;
4402 * we need the default promoted types for the function type
4404 parameter_type = get_default_promoted_type(parameter_type);
4406 function_parameter_t *function_parameter
4407 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4408 memset(function_parameter, 0, sizeof(function_parameter[0]));
4410 function_parameter->type = parameter_type;
4411 if(last_parameter != NULL) {
4412 last_parameter->next = function_parameter;
4414 parameters = function_parameter;
4416 last_parameter = function_parameter;
4419 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4421 new_type->function.parameters = parameters;
4422 new_type->function.unspecified_parameters = true;
4424 type = typehash_insert(new_type);
4425 if(type != new_type) {
4426 obstack_free(type_obst, new_type);
4429 declaration->type = type;
4432 static bool first_err = true;
4435 * When called with first_err set, prints the name of the current function,
4438 static void print_in_function(void) {
4441 diagnosticf("%s: In function '%Y':\n",
4442 current_function->source_position.input_name,
4443 current_function->symbol);
4448 * Check if all labels are defined in the current function.
4449 * Check if all labels are used in the current function.
4451 static void check_labels(void)
4453 for (const goto_statement_t *goto_statement = goto_first;
4454 goto_statement != NULL;
4455 goto_statement = goto_statement->next) {
4456 declaration_t *label = goto_statement->label;
4459 if (label->source_position.input_name == NULL) {
4460 print_in_function();
4461 errorf(&goto_statement->base.source_position,
4462 "label '%Y' used but not defined", label->symbol);
4465 goto_first = goto_last = NULL;
4467 if (warning.unused_label) {
4468 for (const label_statement_t *label_statement = label_first;
4469 label_statement != NULL;
4470 label_statement = label_statement->next) {
4471 const declaration_t *label = label_statement->label;
4473 if (! label->used) {
4474 print_in_function();
4475 warningf(&label_statement->base.source_position,
4476 "label '%Y' defined but not used", label->symbol);
4480 label_first = label_last = NULL;
4484 * Check declarations of current_function for unused entities.
4486 static void check_declarations(void)
4488 if (warning.unused_parameter) {
4489 const scope_t *scope = ¤t_function->scope;
4491 const declaration_t *parameter = scope->declarations;
4492 for (; parameter != NULL; parameter = parameter->next) {
4493 if (! parameter->used) {
4494 print_in_function();
4495 warningf(¶meter->source_position,
4496 "unused parameter '%Y'", parameter->symbol);
4500 if (warning.unused_variable) {
4504 static void parse_external_declaration(void)
4506 /* function-definitions and declarations both start with declaration
4508 declaration_specifiers_t specifiers;
4509 memset(&specifiers, 0, sizeof(specifiers));
4511 add_anchor_token(';');
4512 parse_declaration_specifiers(&specifiers);
4513 rem_anchor_token(';');
4515 /* must be a declaration */
4516 if(token.type == ';') {
4517 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4521 add_anchor_token(',');
4522 add_anchor_token('=');
4523 rem_anchor_token(';');
4525 /* declarator is common to both function-definitions and declarations */
4526 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4528 rem_anchor_token(',');
4529 rem_anchor_token('=');
4530 rem_anchor_token(';');
4532 /* must be a declaration */
4533 if(token.type == ',' || token.type == '=' || token.type == ';') {
4534 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4538 /* must be a function definition */
4539 parse_kr_declaration_list(ndeclaration);
4541 if(token.type != '{') {
4542 parse_error_expected("while parsing function definition", '{', NULL);
4543 eat_until_matching_token(';');
4547 type_t *type = ndeclaration->type;
4549 /* note that we don't skip typerefs: the standard doesn't allow them here
4550 * (so we can't use is_type_function here) */
4551 if(type->kind != TYPE_FUNCTION) {
4552 if (is_type_valid(type)) {
4553 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4554 type, ndeclaration->symbol);
4560 /* § 6.7.5.3 (14) a function definition with () means no
4561 * parameters (and not unspecified parameters) */
4562 if(type->function.unspecified_parameters
4563 && type->function.parameters == NULL
4564 && !type->function.kr_style_parameters) {
4565 type_t *duplicate = duplicate_type(type);
4566 duplicate->function.unspecified_parameters = false;
4568 type = typehash_insert(duplicate);
4569 if(type != duplicate) {
4570 obstack_free(type_obst, duplicate);
4572 ndeclaration->type = type;
4575 declaration_t *const declaration = record_function_definition(ndeclaration);
4576 if(ndeclaration != declaration) {
4577 declaration->scope = ndeclaration->scope;
4579 type = skip_typeref(declaration->type);
4581 /* push function parameters and switch scope */
4582 int top = environment_top();
4583 scope_t *last_scope = scope;
4584 set_scope(&declaration->scope);
4586 declaration_t *parameter = declaration->scope.declarations;
4587 for( ; parameter != NULL; parameter = parameter->next) {
4588 if(parameter->parent_scope == &ndeclaration->scope) {
4589 parameter->parent_scope = scope;
4591 assert(parameter->parent_scope == NULL
4592 || parameter->parent_scope == scope);
4593 parameter->parent_scope = scope;
4594 if (parameter->symbol == NULL) {
4595 errorf(&ndeclaration->source_position, "parameter name omitted");
4598 environment_push(parameter);
4601 if(declaration->init.statement != NULL) {
4602 parser_error_multiple_definition(declaration, HERE);
4604 goto end_of_parse_external_declaration;
4606 /* parse function body */
4607 int label_stack_top = label_top();
4608 declaration_t *old_current_function = current_function;
4609 current_function = declaration;
4611 declaration->init.statement = parse_compound_statement(false);
4614 check_declarations();
4616 assert(current_function == declaration);
4617 current_function = old_current_function;
4618 label_pop_to(label_stack_top);
4621 end_of_parse_external_declaration:
4622 assert(scope == &declaration->scope);
4623 set_scope(last_scope);
4624 environment_pop_to(top);
4627 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4628 source_position_t *source_position)
4630 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4632 type->bitfield.base_type = base_type;
4633 type->bitfield.size = size;
4638 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4641 declaration_t *iter = compound_declaration->scope.declarations;
4642 for( ; iter != NULL; iter = iter->next) {
4643 if(iter->namespc != NAMESPACE_NORMAL)
4646 if(iter->symbol == NULL) {
4647 type_t *type = skip_typeref(iter->type);
4648 if(is_type_compound(type)) {
4649 declaration_t *result
4650 = find_compound_entry(type->compound.declaration, symbol);
4657 if(iter->symbol == symbol) {
4665 static void parse_compound_declarators(declaration_t *struct_declaration,
4666 const declaration_specifiers_t *specifiers)
4668 declaration_t *last_declaration = struct_declaration->scope.declarations;
4669 if(last_declaration != NULL) {
4670 while(last_declaration->next != NULL) {
4671 last_declaration = last_declaration->next;
4676 declaration_t *declaration;
4678 if(token.type == ':') {
4679 source_position_t source_position = *HERE;
4682 type_t *base_type = specifiers->type;
4683 expression_t *size = parse_constant_expression();
4685 if(!is_type_integer(skip_typeref(base_type))) {
4686 errorf(HERE, "bitfield base type '%T' is not an integer type",
4690 type_t *type = make_bitfield_type(base_type, size, &source_position);
4692 declaration = allocate_declaration_zero();
4693 declaration->namespc = NAMESPACE_NORMAL;
4694 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4695 declaration->storage_class = STORAGE_CLASS_NONE;
4696 declaration->source_position = source_position;
4697 declaration->modifiers = specifiers->modifiers;
4698 declaration->type = type;
4700 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4702 type_t *orig_type = declaration->type;
4703 type_t *type = skip_typeref(orig_type);
4705 if(token.type == ':') {
4706 source_position_t source_position = *HERE;
4708 expression_t *size = parse_constant_expression();
4710 if(!is_type_integer(type)) {
4711 errorf(HERE, "bitfield base type '%T' is not an "
4712 "integer type", orig_type);
4715 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4716 declaration->type = bitfield_type;
4718 /* TODO we ignore arrays for now... what is missing is a check
4719 * that they're at the end of the struct */
4720 if(is_type_incomplete(type) && !is_type_array(type)) {
4722 "compound member '%Y' has incomplete type '%T'",
4723 declaration->symbol, orig_type);
4724 } else if(is_type_function(type)) {
4725 errorf(HERE, "compound member '%Y' must not have function "
4726 "type '%T'", declaration->symbol, orig_type);
4731 /* make sure we don't define a symbol multiple times */
4732 symbol_t *symbol = declaration->symbol;
4733 if(symbol != NULL) {
4734 declaration_t *prev_decl
4735 = find_compound_entry(struct_declaration, symbol);
4737 if(prev_decl != NULL) {
4738 assert(prev_decl->symbol == symbol);
4739 errorf(&declaration->source_position,
4740 "multiple declarations of symbol '%Y' (declared %P)",
4741 symbol, &prev_decl->source_position);
4745 /* append declaration */
4746 if(last_declaration != NULL) {
4747 last_declaration->next = declaration;
4749 struct_declaration->scope.declarations = declaration;
4751 last_declaration = declaration;
4753 if(token.type != ',')
4763 static void parse_compound_type_entries(declaration_t *compound_declaration)
4766 add_anchor_token('}');
4768 while(token.type != '}' && token.type != T_EOF) {
4769 declaration_specifiers_t specifiers;
4770 memset(&specifiers, 0, sizeof(specifiers));
4771 parse_declaration_specifiers(&specifiers);
4773 parse_compound_declarators(compound_declaration, &specifiers);
4775 rem_anchor_token('}');
4777 if(token.type == T_EOF) {
4778 errorf(HERE, "EOF while parsing struct");
4783 static type_t *parse_typename(void)
4785 declaration_specifiers_t specifiers;
4786 memset(&specifiers, 0, sizeof(specifiers));
4787 parse_declaration_specifiers(&specifiers);
4788 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4789 /* TODO: improve error message, user does probably not know what a
4790 * storage class is...
4792 errorf(HERE, "typename may not have a storage class");
4795 type_t *result = parse_abstract_declarator(specifiers.type);
4803 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4804 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4805 expression_t *left);
4807 typedef struct expression_parser_function_t expression_parser_function_t;
4808 struct expression_parser_function_t {
4809 unsigned precedence;
4810 parse_expression_function parser;
4811 unsigned infix_precedence;
4812 parse_expression_infix_function infix_parser;
4815 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4818 * Prints an error message if an expression was expected but not read
4820 static expression_t *expected_expression_error(void)
4822 /* skip the error message if the error token was read */
4823 if (token.type != T_ERROR) {
4824 errorf(HERE, "expected expression, got token '%K'", &token);
4828 return create_invalid_expression();
4832 * Parse a string constant.
4834 static expression_t *parse_string_const(void)
4837 if (token.type == T_STRING_LITERAL) {
4838 string_t res = token.v.string;
4840 while (token.type == T_STRING_LITERAL) {
4841 res = concat_strings(&res, &token.v.string);
4844 if (token.type != T_WIDE_STRING_LITERAL) {
4845 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4846 /* note: that we use type_char_ptr here, which is already the
4847 * automatic converted type. revert_automatic_type_conversion
4848 * will construct the array type */
4849 cnst->base.type = type_char_ptr;
4850 cnst->string.value = res;
4854 wres = concat_string_wide_string(&res, &token.v.wide_string);
4856 wres = token.v.wide_string;
4861 switch (token.type) {
4862 case T_WIDE_STRING_LITERAL:
4863 wres = concat_wide_strings(&wres, &token.v.wide_string);
4866 case T_STRING_LITERAL:
4867 wres = concat_wide_string_string(&wres, &token.v.string);
4871 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4872 cnst->base.type = type_wchar_t_ptr;
4873 cnst->wide_string.value = wres;
4882 * Parse an integer constant.
4884 static expression_t *parse_int_const(void)
4886 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4887 cnst->base.source_position = *HERE;
4888 cnst->base.type = token.datatype;
4889 cnst->conste.v.int_value = token.v.intvalue;
4897 * Parse a character constant.
4899 static expression_t *parse_character_constant(void)
4901 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4903 cnst->base.source_position = *HERE;
4904 cnst->base.type = token.datatype;
4905 cnst->conste.v.character = token.v.string;
4907 if (cnst->conste.v.character.size != 1) {
4908 if (warning.multichar && (c_mode & _GNUC)) {
4910 warningf(HERE, "multi-character character constant");
4912 errorf(HERE, "more than 1 characters in character constant");
4921 * Parse a wide character constant.
4923 static expression_t *parse_wide_character_constant(void)
4925 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4927 cnst->base.source_position = *HERE;
4928 cnst->base.type = token.datatype;
4929 cnst->conste.v.wide_character = token.v.wide_string;
4931 if (cnst->conste.v.wide_character.size != 1) {
4932 if (warning.multichar && (c_mode & _GNUC)) {
4934 warningf(HERE, "multi-character character constant");
4936 errorf(HERE, "more than 1 characters in character constant");
4945 * Parse a float constant.
4947 static expression_t *parse_float_const(void)
4949 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4950 cnst->base.type = token.datatype;
4951 cnst->conste.v.float_value = token.v.floatvalue;
4958 static declaration_t *create_implicit_function(symbol_t *symbol,
4959 const source_position_t *source_position)
4961 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4962 ntype->function.return_type = type_int;
4963 ntype->function.unspecified_parameters = true;
4965 type_t *type = typehash_insert(ntype);
4970 declaration_t *const declaration = allocate_declaration_zero();
4971 declaration->storage_class = STORAGE_CLASS_EXTERN;
4972 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4973 declaration->type = type;
4974 declaration->symbol = symbol;
4975 declaration->source_position = *source_position;
4977 bool strict_prototypes_old = warning.strict_prototypes;
4978 warning.strict_prototypes = false;
4979 record_declaration(declaration);
4980 warning.strict_prototypes = strict_prototypes_old;
4986 * Creates a return_type (func)(argument_type) function type if not
4989 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
4990 type_t *argument_type2)
4992 function_parameter_t *parameter2
4993 = obstack_alloc(type_obst, sizeof(parameter2[0]));
4994 memset(parameter2, 0, sizeof(parameter2[0]));
4995 parameter2->type = argument_type2;
4997 function_parameter_t *parameter1
4998 = obstack_alloc(type_obst, sizeof(parameter1[0]));
4999 memset(parameter1, 0, sizeof(parameter1[0]));
5000 parameter1->type = argument_type1;
5001 parameter1->next = parameter2;
5003 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5004 type->function.return_type = return_type;
5005 type->function.parameters = parameter1;
5007 type_t *result = typehash_insert(type);
5008 if(result != type) {
5016 * Creates a return_type (func)(argument_type) function type if not
5019 * @param return_type the return type
5020 * @param argument_type the argument type
5022 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5024 function_parameter_t *parameter
5025 = obstack_alloc(type_obst, sizeof(parameter[0]));
5026 memset(parameter, 0, sizeof(parameter[0]));
5027 parameter->type = argument_type;
5029 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5030 type->function.return_type = return_type;
5031 type->function.parameters = parameter;
5033 type_t *result = typehash_insert(type);
5034 if(result != type) {
5041 static type_t *make_function_0_type(type_t *return_type)
5043 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5044 type->function.return_type = return_type;
5045 type->function.parameters = NULL;
5047 type_t *result = typehash_insert(type);
5048 if(result != type) {
5056 * Creates a function type for some function like builtins.
5058 * @param symbol the symbol describing the builtin
5060 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5062 switch(symbol->ID) {
5063 case T___builtin_alloca:
5064 return make_function_1_type(type_void_ptr, type_size_t);
5065 case T___builtin_huge_val:
5066 return make_function_0_type(type_double);
5067 case T___builtin_nan:
5068 return make_function_1_type(type_double, type_char_ptr);
5069 case T___builtin_nanf:
5070 return make_function_1_type(type_float, type_char_ptr);
5071 case T___builtin_nand:
5072 return make_function_1_type(type_long_double, type_char_ptr);
5073 case T___builtin_va_end:
5074 return make_function_1_type(type_void, type_valist);
5075 case T___builtin_expect:
5076 return make_function_2_type(type_long, type_long, type_long);
5078 internal_errorf(HERE, "not implemented builtin symbol found");
5083 * Performs automatic type cast as described in § 6.3.2.1.
5085 * @param orig_type the original type
5087 static type_t *automatic_type_conversion(type_t *orig_type)
5089 type_t *type = skip_typeref(orig_type);
5090 if(is_type_array(type)) {
5091 array_type_t *array_type = &type->array;
5092 type_t *element_type = array_type->element_type;
5093 unsigned qualifiers = array_type->base.qualifiers;
5095 return make_pointer_type(element_type, qualifiers);
5098 if(is_type_function(type)) {
5099 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5106 * reverts the automatic casts of array to pointer types and function
5107 * to function-pointer types as defined § 6.3.2.1
5109 type_t *revert_automatic_type_conversion(const expression_t *expression)
5111 switch (expression->kind) {
5112 case EXPR_REFERENCE: return expression->reference.declaration->type;
5113 case EXPR_SELECT: return expression->select.compound_entry->type;
5115 case EXPR_UNARY_DEREFERENCE: {
5116 const expression_t *const value = expression->unary.value;
5117 type_t *const type = skip_typeref(value->base.type);
5118 assert(is_type_pointer(type));
5119 return type->pointer.points_to;
5122 case EXPR_BUILTIN_SYMBOL:
5123 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5125 case EXPR_ARRAY_ACCESS: {
5126 const expression_t *array_ref = expression->array_access.array_ref;
5127 type_t *type_left = skip_typeref(array_ref->base.type);
5128 if (!is_type_valid(type_left))
5130 assert(is_type_pointer(type_left));
5131 return type_left->pointer.points_to;
5134 case EXPR_STRING_LITERAL: {
5135 size_t size = expression->string.value.size;
5136 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5139 case EXPR_WIDE_STRING_LITERAL: {
5140 size_t size = expression->wide_string.value.size;
5141 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5144 case EXPR_COMPOUND_LITERAL:
5145 return expression->compound_literal.type;
5150 return expression->base.type;
5153 static expression_t *parse_reference(void)
5155 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5157 reference_expression_t *ref = &expression->reference;
5158 symbol_t *const symbol = token.v.symbol;
5160 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5162 source_position_t source_position = token.source_position;
5165 if(declaration == NULL) {
5166 if (! strict_mode && token.type == '(') {
5167 /* an implicitly defined function */
5168 if (warning.implicit_function_declaration) {
5169 warningf(HERE, "implicit declaration of function '%Y'",
5173 declaration = create_implicit_function(symbol,
5176 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5177 return create_invalid_expression();
5181 type_t *type = declaration->type;
5183 /* we always do the auto-type conversions; the & and sizeof parser contains
5184 * code to revert this! */
5185 type = automatic_type_conversion(type);
5187 ref->declaration = declaration;
5188 ref->base.type = type;
5190 /* this declaration is used */
5191 declaration->used = true;
5193 /* check for deprecated functions */
5194 if(declaration->deprecated != 0) {
5195 const char *prefix = "";
5196 if (is_type_function(declaration->type))
5197 prefix = "function ";
5199 if (declaration->deprecated_string != NULL) {
5200 warningf(&source_position,
5201 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5202 declaration->deprecated_string);
5204 warningf(&source_position,
5205 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5212 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5216 /* TODO check if explicit cast is allowed and issue warnings/errors */
5219 static expression_t *parse_compound_literal(type_t *type)
5221 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5223 parse_initializer_env_t env;
5225 env.declaration = NULL;
5226 env.must_be_constant = false;
5227 initializer_t *initializer = parse_initializer(&env);
5230 expression->compound_literal.initializer = initializer;
5231 expression->compound_literal.type = type;
5232 expression->base.type = automatic_type_conversion(type);
5238 * Parse a cast expression.
5240 static expression_t *parse_cast(void)
5242 source_position_t source_position = token.source_position;
5244 type_t *type = parse_typename();
5246 /* matching add_anchor_token() is at call site */
5247 rem_anchor_token(')');
5250 if(token.type == '{') {
5251 return parse_compound_literal(type);
5254 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5255 cast->base.source_position = source_position;
5257 expression_t *value = parse_sub_expression(20);
5259 check_cast_allowed(value, type);
5261 cast->base.type = type;
5262 cast->unary.value = value;
5266 return create_invalid_expression();
5270 * Parse a statement expression.
5272 static expression_t *parse_statement_expression(void)
5274 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5276 statement_t *statement = parse_compound_statement(true);
5277 expression->statement.statement = statement;
5278 expression->base.source_position = statement->base.source_position;
5280 /* find last statement and use its type */
5281 type_t *type = type_void;
5282 const statement_t *stmt = statement->compound.statements;
5284 while (stmt->base.next != NULL)
5285 stmt = stmt->base.next;
5287 if (stmt->kind == STATEMENT_EXPRESSION) {
5288 type = stmt->expression.expression->base.type;
5291 warningf(&expression->base.source_position, "empty statement expression ({})");
5293 expression->base.type = type;
5299 return create_invalid_expression();
5303 * Parse a braced expression.
5305 static expression_t *parse_brace_expression(void)
5308 add_anchor_token(')');
5310 switch(token.type) {
5312 /* gcc extension: a statement expression */
5313 return parse_statement_expression();
5317 return parse_cast();
5319 if(is_typedef_symbol(token.v.symbol)) {
5320 return parse_cast();
5324 expression_t *result = parse_expression();
5325 rem_anchor_token(')');
5330 return create_invalid_expression();
5333 static expression_t *parse_function_keyword(void)
5338 if (current_function == NULL) {
5339 errorf(HERE, "'__func__' used outside of a function");
5342 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5343 expression->base.type = type_char_ptr;
5344 expression->funcname.kind = FUNCNAME_FUNCTION;
5349 static expression_t *parse_pretty_function_keyword(void)
5351 eat(T___PRETTY_FUNCTION__);
5353 if (current_function == NULL) {
5354 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5357 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5358 expression->base.type = type_char_ptr;
5359 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5364 static expression_t *parse_funcsig_keyword(void)
5368 if (current_function == NULL) {
5369 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5372 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5373 expression->base.type = type_char_ptr;
5374 expression->funcname.kind = FUNCNAME_FUNCSIG;
5379 static expression_t *parse_funcdname_keyword(void)
5381 eat(T___FUNCDNAME__);
5383 if (current_function == NULL) {
5384 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5387 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5388 expression->base.type = type_char_ptr;
5389 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5394 static designator_t *parse_designator(void)
5396 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5397 result->source_position = *HERE;
5399 if(token.type != T_IDENTIFIER) {
5400 parse_error_expected("while parsing member designator",
5401 T_IDENTIFIER, NULL);
5404 result->symbol = token.v.symbol;
5407 designator_t *last_designator = result;
5409 if(token.type == '.') {
5411 if(token.type != T_IDENTIFIER) {
5412 parse_error_expected("while parsing member designator",
5413 T_IDENTIFIER, NULL);
5416 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5417 designator->source_position = *HERE;
5418 designator->symbol = token.v.symbol;
5421 last_designator->next = designator;
5422 last_designator = designator;
5425 if(token.type == '[') {
5427 add_anchor_token(']');
5428 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5429 designator->source_position = *HERE;
5430 designator->array_index = parse_expression();
5431 rem_anchor_token(']');
5433 if(designator->array_index == NULL) {
5437 last_designator->next = designator;
5438 last_designator = designator;
5450 * Parse the __builtin_offsetof() expression.
5452 static expression_t *parse_offsetof(void)
5454 eat(T___builtin_offsetof);
5456 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5457 expression->base.type = type_size_t;
5460 add_anchor_token(',');
5461 type_t *type = parse_typename();
5462 rem_anchor_token(',');
5464 add_anchor_token(')');
5465 designator_t *designator = parse_designator();
5466 rem_anchor_token(')');
5469 expression->offsetofe.type = type;
5470 expression->offsetofe.designator = designator;
5473 memset(&path, 0, sizeof(path));
5474 path.top_type = type;
5475 path.path = NEW_ARR_F(type_path_entry_t, 0);
5477 descend_into_subtype(&path);
5479 if(!walk_designator(&path, designator, true)) {
5480 return create_invalid_expression();
5483 DEL_ARR_F(path.path);
5487 return create_invalid_expression();
5491 * Parses a _builtin_va_start() expression.
5493 static expression_t *parse_va_start(void)
5495 eat(T___builtin_va_start);
5497 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5500 add_anchor_token(',');
5501 expression->va_starte.ap = parse_assignment_expression();
5502 rem_anchor_token(',');
5504 expression_t *const expr = parse_assignment_expression();
5505 if (expr->kind == EXPR_REFERENCE) {
5506 declaration_t *const decl = expr->reference.declaration;
5508 return create_invalid_expression();
5509 if (decl->parent_scope == ¤t_function->scope &&
5510 decl->next == NULL) {
5511 expression->va_starte.parameter = decl;
5516 errorf(&expr->base.source_position,
5517 "second argument of 'va_start' must be last parameter of the current function");
5519 return create_invalid_expression();
5523 * Parses a _builtin_va_arg() expression.
5525 static expression_t *parse_va_arg(void)
5527 eat(T___builtin_va_arg);
5529 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5532 expression->va_arge.ap = parse_assignment_expression();
5534 expression->base.type = parse_typename();
5539 return create_invalid_expression();
5542 static expression_t *parse_builtin_symbol(void)
5544 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5546 symbol_t *symbol = token.v.symbol;
5548 expression->builtin_symbol.symbol = symbol;
5551 type_t *type = get_builtin_symbol_type(symbol);
5552 type = automatic_type_conversion(type);
5554 expression->base.type = type;
5559 * Parses a __builtin_constant() expression.
5561 static expression_t *parse_builtin_constant(void)
5563 eat(T___builtin_constant_p);
5565 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5568 add_anchor_token(')');
5569 expression->builtin_constant.value = parse_assignment_expression();
5570 rem_anchor_token(')');
5572 expression->base.type = type_int;
5576 return create_invalid_expression();
5580 * Parses a __builtin_prefetch() expression.
5582 static expression_t *parse_builtin_prefetch(void)
5584 eat(T___builtin_prefetch);
5586 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5589 add_anchor_token(')');
5590 expression->builtin_prefetch.adr = parse_assignment_expression();
5591 if (token.type == ',') {
5593 expression->builtin_prefetch.rw = parse_assignment_expression();
5595 if (token.type == ',') {
5597 expression->builtin_prefetch.locality = parse_assignment_expression();
5599 rem_anchor_token(')');
5601 expression->base.type = type_void;
5605 return create_invalid_expression();
5609 * Parses a __builtin_is_*() compare expression.
5611 static expression_t *parse_compare_builtin(void)
5613 expression_t *expression;
5615 switch(token.type) {
5616 case T___builtin_isgreater:
5617 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5619 case T___builtin_isgreaterequal:
5620 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5622 case T___builtin_isless:
5623 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5625 case T___builtin_islessequal:
5626 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5628 case T___builtin_islessgreater:
5629 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5631 case T___builtin_isunordered:
5632 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5635 internal_errorf(HERE, "invalid compare builtin found");
5638 expression->base.source_position = *HERE;
5642 expression->binary.left = parse_assignment_expression();
5644 expression->binary.right = parse_assignment_expression();
5647 type_t *const orig_type_left = expression->binary.left->base.type;
5648 type_t *const orig_type_right = expression->binary.right->base.type;
5650 type_t *const type_left = skip_typeref(orig_type_left);
5651 type_t *const type_right = skip_typeref(orig_type_right);
5652 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5653 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5654 type_error_incompatible("invalid operands in comparison",
5655 &expression->base.source_position, orig_type_left, orig_type_right);
5658 semantic_comparison(&expression->binary);
5663 return create_invalid_expression();
5668 * Parses a __builtin_expect() expression.
5670 static expression_t *parse_builtin_expect(void)
5672 eat(T___builtin_expect);
5674 expression_t *expression
5675 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5678 expression->binary.left = parse_assignment_expression();
5680 expression->binary.right = parse_constant_expression();
5683 expression->base.type = expression->binary.left->base.type;
5687 return create_invalid_expression();
5692 * Parses a MS assume() expression.
5694 static expression_t *parse_assume(void) {
5697 expression_t *expression
5698 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5701 add_anchor_token(')');
5702 expression->unary.value = parse_assignment_expression();
5703 rem_anchor_token(')');
5706 expression->base.type = type_void;
5709 return create_invalid_expression();
5713 * Parse a microsoft __noop expression.
5715 static expression_t *parse_noop_expression(void) {
5716 source_position_t source_position = *HERE;
5719 if (token.type == '(') {
5720 /* parse arguments */
5722 add_anchor_token(')');
5723 add_anchor_token(',');
5725 if(token.type != ')') {
5727 (void)parse_assignment_expression();
5728 if(token.type != ',')
5734 rem_anchor_token(',');
5735 rem_anchor_token(')');
5738 /* the result is a (int)0 */
5739 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5740 cnst->base.source_position = source_position;
5741 cnst->base.type = type_int;
5742 cnst->conste.v.int_value = 0;
5743 cnst->conste.is_ms_noop = true;
5748 return create_invalid_expression();
5752 * Parses a primary expression.
5754 static expression_t *parse_primary_expression(void)
5756 switch (token.type) {
5757 case T_INTEGER: return parse_int_const();
5758 case T_CHARACTER_CONSTANT: return parse_character_constant();
5759 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5760 case T_FLOATINGPOINT: return parse_float_const();
5761 case T_STRING_LITERAL:
5762 case T_WIDE_STRING_LITERAL: return parse_string_const();
5763 case T_IDENTIFIER: return parse_reference();
5764 case T___FUNCTION__:
5765 case T___func__: return parse_function_keyword();
5766 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5767 case T___FUNCSIG__: return parse_funcsig_keyword();
5768 case T___FUNCDNAME__: return parse_funcdname_keyword();
5769 case T___builtin_offsetof: return parse_offsetof();
5770 case T___builtin_va_start: return parse_va_start();
5771 case T___builtin_va_arg: return parse_va_arg();
5772 case T___builtin_expect:
5773 case T___builtin_alloca:
5774 case T___builtin_nan:
5775 case T___builtin_nand:
5776 case T___builtin_nanf:
5777 case T___builtin_huge_val:
5778 case T___builtin_va_end: return parse_builtin_symbol();
5779 case T___builtin_isgreater:
5780 case T___builtin_isgreaterequal:
5781 case T___builtin_isless:
5782 case T___builtin_islessequal:
5783 case T___builtin_islessgreater:
5784 case T___builtin_isunordered: return parse_compare_builtin();
5785 case T___builtin_constant_p: return parse_builtin_constant();
5786 case T___builtin_prefetch: return parse_builtin_prefetch();
5787 case T__assume: return parse_assume();
5789 case '(': return parse_brace_expression();
5790 case T___noop: return parse_noop_expression();
5793 errorf(HERE, "unexpected token %K, expected an expression", &token);
5794 return create_invalid_expression();
5798 * Check if the expression has the character type and issue a warning then.
5800 static void check_for_char_index_type(const expression_t *expression) {
5801 type_t *const type = expression->base.type;
5802 const type_t *const base_type = skip_typeref(type);
5804 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5805 warning.char_subscripts) {
5806 warningf(&expression->base.source_position,
5807 "array subscript has type '%T'", type);
5811 static expression_t *parse_array_expression(unsigned precedence,
5817 add_anchor_token(']');
5819 expression_t *inside = parse_expression();
5821 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5823 array_access_expression_t *array_access = &expression->array_access;
5825 type_t *const orig_type_left = left->base.type;
5826 type_t *const orig_type_inside = inside->base.type;
5828 type_t *const type_left = skip_typeref(orig_type_left);
5829 type_t *const type_inside = skip_typeref(orig_type_inside);
5831 type_t *return_type;
5832 if (is_type_pointer(type_left)) {
5833 return_type = type_left->pointer.points_to;
5834 array_access->array_ref = left;
5835 array_access->index = inside;
5836 check_for_char_index_type(inside);
5837 } else if (is_type_pointer(type_inside)) {
5838 return_type = type_inside->pointer.points_to;
5839 array_access->array_ref = inside;
5840 array_access->index = left;
5841 array_access->flipped = true;
5842 check_for_char_index_type(left);
5844 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5846 "array access on object with non-pointer types '%T', '%T'",
5847 orig_type_left, orig_type_inside);
5849 return_type = type_error_type;
5850 array_access->array_ref = create_invalid_expression();
5853 rem_anchor_token(']');
5854 if(token.type != ']') {
5855 parse_error_expected("Problem while parsing array access", ']', NULL);
5860 return_type = automatic_type_conversion(return_type);
5861 expression->base.type = return_type;
5866 static expression_t *parse_typeprop(expression_kind_t const kind,
5867 source_position_t const pos,
5868 unsigned const precedence)
5870 expression_t *tp_expression = allocate_expression_zero(kind);
5871 tp_expression->base.type = type_size_t;
5872 tp_expression->base.source_position = pos;
5874 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5876 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5878 add_anchor_token(')');
5879 type_t* const orig_type = parse_typename();
5880 tp_expression->typeprop.type = orig_type;
5882 type_t const* const type = skip_typeref(orig_type);
5883 char const* const wrong_type =
5884 is_type_incomplete(type) ? "incomplete" :
5885 type->kind == TYPE_FUNCTION ? "function designator" :
5886 type->kind == TYPE_BITFIELD ? "bitfield" :
5888 if (wrong_type != NULL) {
5889 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5890 what, wrong_type, type);
5893 rem_anchor_token(')');
5896 expression_t *expression = parse_sub_expression(precedence);
5898 type_t* const orig_type = revert_automatic_type_conversion(expression);
5899 expression->base.type = orig_type;
5901 type_t const* const type = skip_typeref(orig_type);
5902 char const* const wrong_type =
5903 is_type_incomplete(type) ? "incomplete" :
5904 type->kind == TYPE_FUNCTION ? "function designator" :
5905 type->kind == TYPE_BITFIELD ? "bitfield" :
5907 if (wrong_type != NULL) {
5908 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5911 tp_expression->typeprop.type = expression->base.type;
5912 tp_expression->typeprop.tp_expression = expression;
5915 return tp_expression;
5917 return create_invalid_expression();
5920 static expression_t *parse_sizeof(unsigned precedence)
5922 source_position_t pos = *HERE;
5924 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5927 static expression_t *parse_alignof(unsigned precedence)
5929 source_position_t pos = *HERE;
5931 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5934 static expression_t *parse_select_expression(unsigned precedence,
5935 expression_t *compound)
5938 assert(token.type == '.' || token.type == T_MINUSGREATER);
5940 bool is_pointer = (token.type == T_MINUSGREATER);
5943 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5944 select->select.compound = compound;
5946 if (token.type != T_IDENTIFIER) {
5947 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5950 symbol_t *symbol = token.v.symbol;
5951 select->select.symbol = symbol;
5954 type_t *const orig_type = compound->base.type;
5955 type_t *const type = skip_typeref(orig_type);
5957 type_t *type_left = type;
5959 if (!is_type_pointer(type)) {
5960 if (is_type_valid(type)) {
5961 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5963 return create_invalid_expression();
5965 type_left = type->pointer.points_to;
5967 type_left = skip_typeref(type_left);
5969 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5970 type_left->kind != TYPE_COMPOUND_UNION) {
5971 if (is_type_valid(type_left)) {
5972 errorf(HERE, "request for member '%Y' in something not a struct or "
5973 "union, but '%T'", symbol, type_left);
5975 return create_invalid_expression();
5978 declaration_t *const declaration = type_left->compound.declaration;
5980 if (!declaration->init.complete) {
5981 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5983 return create_invalid_expression();
5986 declaration_t *iter = find_compound_entry(declaration, symbol);
5988 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5989 return create_invalid_expression();
5992 /* we always do the auto-type conversions; the & and sizeof parser contains
5993 * code to revert this! */
5994 type_t *expression_type = automatic_type_conversion(iter->type);
5996 select->select.compound_entry = iter;
5997 select->base.type = expression_type;
5999 type_t *skipped = skip_typeref(iter->type);
6000 if (skipped->kind == TYPE_BITFIELD) {
6001 select->base.type = skipped->bitfield.base_type;
6007 static void check_call_argument(const function_parameter_t *parameter,
6008 call_argument_t *argument)
6010 type_t *expected_type = parameter->type;
6011 type_t *expected_type_skip = skip_typeref(expected_type);
6012 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6013 expression_t *arg_expr = argument->expression;
6015 /* handle transparent union gnu extension */
6016 if (is_type_union(expected_type_skip)
6017 && (expected_type_skip->base.modifiers
6018 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6019 declaration_t *union_decl = expected_type_skip->compound.declaration;
6021 declaration_t *declaration = union_decl->scope.declarations;
6022 type_t *best_type = NULL;
6023 for ( ; declaration != NULL; declaration = declaration->next) {
6024 type_t *decl_type = declaration->type;
6025 error = semantic_assign(decl_type, arg_expr);
6026 if (error == ASSIGN_ERROR_INCOMPATIBLE
6027 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6030 if (error == ASSIGN_SUCCESS) {
6031 best_type = decl_type;
6032 } else if (best_type == NULL) {
6033 best_type = decl_type;
6037 if (best_type != NULL) {
6038 expected_type = best_type;
6042 error = semantic_assign(expected_type, arg_expr);
6043 argument->expression = create_implicit_cast(argument->expression,
6046 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6047 report_assign_error(error, expected_type, arg_expr, "function call",
6048 &arg_expr->base.source_position);
6052 * Parse a call expression, ie. expression '( ... )'.
6054 * @param expression the function address
6056 static expression_t *parse_call_expression(unsigned precedence,
6057 expression_t *expression)
6060 expression_t *result = allocate_expression_zero(EXPR_CALL);
6061 result->base.source_position = expression->base.source_position;
6063 call_expression_t *call = &result->call;
6064 call->function = expression;
6066 type_t *const orig_type = expression->base.type;
6067 type_t *const type = skip_typeref(orig_type);
6069 function_type_t *function_type = NULL;
6070 if (is_type_pointer(type)) {
6071 type_t *const to_type = skip_typeref(type->pointer.points_to);
6073 if (is_type_function(to_type)) {
6074 function_type = &to_type->function;
6075 call->base.type = function_type->return_type;
6079 if (function_type == NULL && is_type_valid(type)) {
6080 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6083 /* parse arguments */
6085 add_anchor_token(')');
6086 add_anchor_token(',');
6088 if(token.type != ')') {
6089 call_argument_t *last_argument = NULL;
6092 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6094 argument->expression = parse_assignment_expression();
6095 if(last_argument == NULL) {
6096 call->arguments = argument;
6098 last_argument->next = argument;
6100 last_argument = argument;
6102 if(token.type != ',')
6107 rem_anchor_token(',');
6108 rem_anchor_token(')');
6111 if(function_type == NULL)
6114 function_parameter_t *parameter = function_type->parameters;
6115 call_argument_t *argument = call->arguments;
6116 if (!function_type->unspecified_parameters) {
6117 for( ; parameter != NULL && argument != NULL;
6118 parameter = parameter->next, argument = argument->next) {
6119 check_call_argument(parameter, argument);
6122 if (parameter != NULL) {
6123 errorf(HERE, "too few arguments to function '%E'", expression);
6124 } else if (argument != NULL && !function_type->variadic) {
6125 errorf(HERE, "too many arguments to function '%E'", expression);
6129 /* do default promotion */
6130 for( ; argument != NULL; argument = argument->next) {
6131 type_t *type = argument->expression->base.type;
6133 type = get_default_promoted_type(type);
6135 argument->expression
6136 = create_implicit_cast(argument->expression, type);
6139 check_format(&result->call);
6143 return create_invalid_expression();
6146 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6148 static bool same_compound_type(const type_t *type1, const type_t *type2)
6151 is_type_compound(type1) &&
6152 type1->kind == type2->kind &&
6153 type1->compound.declaration == type2->compound.declaration;
6157 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6159 * @param expression the conditional expression
6161 static expression_t *parse_conditional_expression(unsigned precedence,
6162 expression_t *expression)
6165 add_anchor_token(':');
6167 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6169 conditional_expression_t *conditional = &result->conditional;
6170 conditional->condition = expression;
6173 type_t *const condition_type_orig = expression->base.type;
6174 type_t *const condition_type = skip_typeref(condition_type_orig);
6175 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6176 type_error("expected a scalar type in conditional condition",
6177 &expression->base.source_position, condition_type_orig);
6180 expression_t *true_expression = parse_expression();
6181 rem_anchor_token(':');
6183 expression_t *false_expression = parse_sub_expression(precedence);
6185 type_t *const orig_true_type = true_expression->base.type;
6186 type_t *const orig_false_type = false_expression->base.type;
6187 type_t *const true_type = skip_typeref(orig_true_type);
6188 type_t *const false_type = skip_typeref(orig_false_type);
6191 type_t *result_type;
6192 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6193 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6194 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6195 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6196 warningf(&expression->base.source_position,
6197 "ISO C forbids conditional expression with only one void side");
6199 result_type = type_void;
6200 } else if (is_type_arithmetic(true_type)
6201 && is_type_arithmetic(false_type)) {
6202 result_type = semantic_arithmetic(true_type, false_type);
6204 true_expression = create_implicit_cast(true_expression, result_type);
6205 false_expression = create_implicit_cast(false_expression, result_type);
6207 conditional->true_expression = true_expression;
6208 conditional->false_expression = false_expression;
6209 conditional->base.type = result_type;
6210 } else if (same_compound_type(true_type, false_type)) {
6211 /* just take 1 of the 2 types */
6212 result_type = true_type;
6213 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6214 type_t *pointer_type;
6216 expression_t *other_expression;
6217 if (is_type_pointer(true_type) &&
6218 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6219 pointer_type = true_type;
6220 other_type = false_type;
6221 other_expression = false_expression;
6223 pointer_type = false_type;
6224 other_type = true_type;
6225 other_expression = true_expression;
6228 if (is_null_pointer_constant(other_expression)) {
6229 result_type = pointer_type;
6230 } else if (is_type_pointer(other_type)) {
6231 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6232 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6235 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6236 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6238 } else if (types_compatible(get_unqualified_type(to1),
6239 get_unqualified_type(to2))) {
6242 warningf(&expression->base.source_position,
6243 "pointer types '%T' and '%T' in conditional expression are incompatible",
6244 true_type, false_type);
6248 type_t *const copy = duplicate_type(to);
6249 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6251 type_t *const type = typehash_insert(copy);
6255 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6256 } else if(is_type_integer(other_type)) {
6257 warningf(&expression->base.source_position,
6258 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6259 result_type = pointer_type;
6261 type_error_incompatible("while parsing conditional",
6262 &expression->base.source_position, true_type, false_type);
6263 result_type = type_error_type;
6266 /* TODO: one pointer to void*, other some pointer */
6268 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6269 type_error_incompatible("while parsing conditional",
6270 &expression->base.source_position, true_type,
6273 result_type = type_error_type;
6276 conditional->true_expression
6277 = create_implicit_cast(true_expression, result_type);
6278 conditional->false_expression
6279 = create_implicit_cast(false_expression, result_type);
6280 conditional->base.type = result_type;
6283 return create_invalid_expression();
6287 * Parse an extension expression.
6289 static expression_t *parse_extension(unsigned precedence)
6291 eat(T___extension__);
6293 /* TODO enable extensions */
6294 expression_t *expression = parse_sub_expression(precedence);
6295 /* TODO disable extensions */
6300 * Parse a __builtin_classify_type() expression.
6302 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6304 eat(T___builtin_classify_type);
6306 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6307 result->base.type = type_int;
6310 add_anchor_token(')');
6311 expression_t *expression = parse_sub_expression(precedence);
6312 rem_anchor_token(')');
6314 result->classify_type.type_expression = expression;
6318 return create_invalid_expression();
6321 static void check_pointer_arithmetic(const source_position_t *source_position,
6322 type_t *pointer_type,
6323 type_t *orig_pointer_type)
6325 type_t *points_to = pointer_type->pointer.points_to;
6326 points_to = skip_typeref(points_to);
6328 if (is_type_incomplete(points_to) &&
6330 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6331 errorf(source_position,
6332 "arithmetic with pointer to incomplete type '%T' not allowed",
6334 } else if (is_type_function(points_to)) {
6335 errorf(source_position,
6336 "arithmetic with pointer to function type '%T' not allowed",
6341 static void semantic_incdec(unary_expression_t *expression)
6343 type_t *const orig_type = expression->value->base.type;
6344 type_t *const type = skip_typeref(orig_type);
6345 if (is_type_pointer(type)) {
6346 check_pointer_arithmetic(&expression->base.source_position,
6348 } else if (!is_type_real(type) && is_type_valid(type)) {
6349 /* TODO: improve error message */
6350 errorf(HERE, "operation needs an arithmetic or pointer type");
6352 expression->base.type = orig_type;
6355 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6357 type_t *const orig_type = expression->value->base.type;
6358 type_t *const type = skip_typeref(orig_type);
6359 if(!is_type_arithmetic(type)) {
6360 if (is_type_valid(type)) {
6361 /* TODO: improve error message */
6362 errorf(HERE, "operation needs an arithmetic type");
6367 expression->base.type = orig_type;
6370 static void semantic_unexpr_scalar(unary_expression_t *expression)
6372 type_t *const orig_type = expression->value->base.type;
6373 type_t *const type = skip_typeref(orig_type);
6374 if (!is_type_scalar(type)) {
6375 if (is_type_valid(type)) {
6376 errorf(HERE, "operand of ! must be of scalar type");
6381 expression->base.type = orig_type;
6384 static void semantic_unexpr_integer(unary_expression_t *expression)
6386 type_t *const orig_type = expression->value->base.type;
6387 type_t *const type = skip_typeref(orig_type);
6388 if (!is_type_integer(type)) {
6389 if (is_type_valid(type)) {
6390 errorf(HERE, "operand of ~ must be of integer type");
6395 expression->base.type = orig_type;
6398 static void semantic_dereference(unary_expression_t *expression)
6400 type_t *const orig_type = expression->value->base.type;
6401 type_t *const type = skip_typeref(orig_type);
6402 if(!is_type_pointer(type)) {
6403 if (is_type_valid(type)) {
6404 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6409 type_t *result_type = type->pointer.points_to;
6410 result_type = automatic_type_conversion(result_type);
6411 expression->base.type = result_type;
6414 static void set_address_taken(expression_t *expression, bool may_be_register)
6416 if(expression->kind != EXPR_REFERENCE)
6419 declaration_t *const declaration = expression->reference.declaration;
6420 /* happens for parse errors */
6421 if(declaration == NULL)
6424 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6425 errorf(&expression->base.source_position,
6426 "address of register variable '%Y' requested",
6427 declaration->symbol);
6429 declaration->address_taken = 1;
6434 * Check the semantic of the address taken expression.
6436 static void semantic_take_addr(unary_expression_t *expression)
6438 expression_t *value = expression->value;
6439 value->base.type = revert_automatic_type_conversion(value);
6441 type_t *orig_type = value->base.type;
6442 if(!is_type_valid(orig_type))
6445 set_address_taken(value, false);
6447 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6450 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6451 static expression_t *parse_##unexpression_type(unsigned precedence) \
6455 expression_t *unary_expression \
6456 = allocate_expression_zero(unexpression_type); \
6457 unary_expression->base.source_position = *HERE; \
6458 unary_expression->unary.value = parse_sub_expression(precedence); \
6460 sfunc(&unary_expression->unary); \
6462 return unary_expression; \
6465 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6466 semantic_unexpr_arithmetic)
6467 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6468 semantic_unexpr_arithmetic)
6469 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6470 semantic_unexpr_scalar)
6471 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6472 semantic_dereference)
6473 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6475 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6476 semantic_unexpr_integer)
6477 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6479 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6482 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6484 static expression_t *parse_##unexpression_type(unsigned precedence, \
6485 expression_t *left) \
6487 (void) precedence; \
6490 expression_t *unary_expression \
6491 = allocate_expression_zero(unexpression_type); \
6492 unary_expression->unary.value = left; \
6494 sfunc(&unary_expression->unary); \
6496 return unary_expression; \
6499 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6500 EXPR_UNARY_POSTFIX_INCREMENT,
6502 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6503 EXPR_UNARY_POSTFIX_DECREMENT,
6506 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6508 /* TODO: handle complex + imaginary types */
6510 /* § 6.3.1.8 Usual arithmetic conversions */
6511 if(type_left == type_long_double || type_right == type_long_double) {
6512 return type_long_double;
6513 } else if(type_left == type_double || type_right == type_double) {
6515 } else if(type_left == type_float || type_right == type_float) {
6519 type_right = promote_integer(type_right);
6520 type_left = promote_integer(type_left);
6522 if(type_left == type_right)
6525 bool signed_left = is_type_signed(type_left);
6526 bool signed_right = is_type_signed(type_right);
6527 int rank_left = get_rank(type_left);
6528 int rank_right = get_rank(type_right);
6529 if(rank_left < rank_right) {
6530 if(signed_left == signed_right || !signed_right) {
6536 if(signed_left == signed_right || !signed_left) {
6545 * Check the semantic restrictions for a binary expression.
6547 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6549 expression_t *const left = expression->left;
6550 expression_t *const right = expression->right;
6551 type_t *const orig_type_left = left->base.type;
6552 type_t *const orig_type_right = right->base.type;
6553 type_t *const type_left = skip_typeref(orig_type_left);
6554 type_t *const type_right = skip_typeref(orig_type_right);
6556 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6557 /* TODO: improve error message */
6558 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6559 errorf(HERE, "operation needs arithmetic types");
6564 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6565 expression->left = create_implicit_cast(left, arithmetic_type);
6566 expression->right = create_implicit_cast(right, arithmetic_type);
6567 expression->base.type = arithmetic_type;
6570 static void semantic_shift_op(binary_expression_t *expression)
6572 expression_t *const left = expression->left;
6573 expression_t *const right = expression->right;
6574 type_t *const orig_type_left = left->base.type;
6575 type_t *const orig_type_right = right->base.type;
6576 type_t * type_left = skip_typeref(orig_type_left);
6577 type_t * type_right = skip_typeref(orig_type_right);
6579 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6580 /* TODO: improve error message */
6581 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6582 errorf(HERE, "operation needs integer types");
6587 type_left = promote_integer(type_left);
6588 type_right = promote_integer(type_right);
6590 expression->left = create_implicit_cast(left, type_left);
6591 expression->right = create_implicit_cast(right, type_right);
6592 expression->base.type = type_left;
6595 static void semantic_add(binary_expression_t *expression)
6597 expression_t *const left = expression->left;
6598 expression_t *const right = expression->right;
6599 type_t *const orig_type_left = left->base.type;
6600 type_t *const orig_type_right = right->base.type;
6601 type_t *const type_left = skip_typeref(orig_type_left);
6602 type_t *const type_right = skip_typeref(orig_type_right);
6605 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6606 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6607 expression->left = create_implicit_cast(left, arithmetic_type);
6608 expression->right = create_implicit_cast(right, arithmetic_type);
6609 expression->base.type = arithmetic_type;
6611 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6612 check_pointer_arithmetic(&expression->base.source_position,
6613 type_left, orig_type_left);
6614 expression->base.type = type_left;
6615 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6616 check_pointer_arithmetic(&expression->base.source_position,
6617 type_right, orig_type_right);
6618 expression->base.type = type_right;
6619 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6620 errorf(&expression->base.source_position,
6621 "invalid operands to binary + ('%T', '%T')",
6622 orig_type_left, orig_type_right);
6626 static void semantic_sub(binary_expression_t *expression)
6628 expression_t *const left = expression->left;
6629 expression_t *const right = expression->right;
6630 type_t *const orig_type_left = left->base.type;
6631 type_t *const orig_type_right = right->base.type;
6632 type_t *const type_left = skip_typeref(orig_type_left);
6633 type_t *const type_right = skip_typeref(orig_type_right);
6636 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6637 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6638 expression->left = create_implicit_cast(left, arithmetic_type);
6639 expression->right = create_implicit_cast(right, arithmetic_type);
6640 expression->base.type = arithmetic_type;
6642 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6643 check_pointer_arithmetic(&expression->base.source_position,
6644 type_left, orig_type_left);
6645 expression->base.type = type_left;
6646 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6647 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6648 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6649 if (!types_compatible(unqual_left, unqual_right)) {
6650 errorf(&expression->base.source_position,
6651 "subtracting pointers to incompatible types '%T' and '%T'",
6652 orig_type_left, orig_type_right);
6653 } else if (!is_type_object(unqual_left)) {
6654 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6655 warningf(&expression->base.source_position,
6656 "subtracting pointers to void");
6658 errorf(&expression->base.source_position,
6659 "subtracting pointers to non-object types '%T'",
6663 expression->base.type = type_ptrdiff_t;
6664 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6665 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6666 orig_type_left, orig_type_right);
6671 * Check the semantics of comparison expressions.
6673 * @param expression The expression to check.
6675 static void semantic_comparison(binary_expression_t *expression)
6677 expression_t *left = expression->left;
6678 expression_t *right = expression->right;
6679 type_t *orig_type_left = left->base.type;
6680 type_t *orig_type_right = right->base.type;
6682 type_t *type_left = skip_typeref(orig_type_left);
6683 type_t *type_right = skip_typeref(orig_type_right);
6685 /* TODO non-arithmetic types */
6686 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6687 /* test for signed vs unsigned compares */
6688 if (warning.sign_compare &&
6689 (expression->base.kind != EXPR_BINARY_EQUAL &&
6690 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6691 (is_type_signed(type_left) != is_type_signed(type_right))) {
6693 /* check if 1 of the operands is a constant, in this case we just
6694 * check wether we can safely represent the resulting constant in
6695 * the type of the other operand. */
6696 expression_t *const_expr = NULL;
6697 expression_t *other_expr = NULL;
6699 if(is_constant_expression(left)) {
6702 } else if(is_constant_expression(right)) {
6707 if(const_expr != NULL) {
6708 type_t *other_type = skip_typeref(other_expr->base.type);
6709 long val = fold_constant(const_expr);
6710 /* TODO: check if val can be represented by other_type */
6714 warningf(&expression->base.source_position,
6715 "comparison between signed and unsigned");
6717 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6718 expression->left = create_implicit_cast(left, arithmetic_type);
6719 expression->right = create_implicit_cast(right, arithmetic_type);
6720 expression->base.type = arithmetic_type;
6721 if (warning.float_equal &&
6722 (expression->base.kind == EXPR_BINARY_EQUAL ||
6723 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6724 is_type_float(arithmetic_type)) {
6725 warningf(&expression->base.source_position,
6726 "comparing floating point with == or != is unsafe");
6728 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6729 /* TODO check compatibility */
6730 } else if (is_type_pointer(type_left)) {
6731 expression->right = create_implicit_cast(right, type_left);
6732 } else if (is_type_pointer(type_right)) {
6733 expression->left = create_implicit_cast(left, type_right);
6734 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6735 type_error_incompatible("invalid operands in comparison",
6736 &expression->base.source_position,
6737 type_left, type_right);
6739 expression->base.type = type_int;
6743 * Checks if a compound type has constant fields.
6745 static bool has_const_fields(const compound_type_t *type)
6747 const scope_t *scope = &type->declaration->scope;
6748 const declaration_t *declaration = scope->declarations;
6750 for (; declaration != NULL; declaration = declaration->next) {
6751 if (declaration->namespc != NAMESPACE_NORMAL)
6754 const type_t *decl_type = skip_typeref(declaration->type);
6755 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6762 static bool is_lvalue(const expression_t *expression)
6764 switch (expression->kind) {
6765 case EXPR_REFERENCE:
6766 case EXPR_ARRAY_ACCESS:
6768 case EXPR_UNARY_DEREFERENCE:
6776 static bool is_valid_assignment_lhs(expression_t const* const left)
6778 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6779 type_t *const type_left = skip_typeref(orig_type_left);
6781 if (!is_lvalue(left)) {
6782 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6787 if (is_type_array(type_left)) {
6788 errorf(HERE, "cannot assign to arrays ('%E')", left);
6791 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6792 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6796 if (is_type_incomplete(type_left)) {
6797 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6798 left, orig_type_left);
6801 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6802 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6803 left, orig_type_left);
6810 static void semantic_arithmetic_assign(binary_expression_t *expression)
6812 expression_t *left = expression->left;
6813 expression_t *right = expression->right;
6814 type_t *orig_type_left = left->base.type;
6815 type_t *orig_type_right = right->base.type;
6817 if (!is_valid_assignment_lhs(left))
6820 type_t *type_left = skip_typeref(orig_type_left);
6821 type_t *type_right = skip_typeref(orig_type_right);
6823 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6824 /* TODO: improve error message */
6825 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6826 errorf(HERE, "operation needs arithmetic types");
6831 /* combined instructions are tricky. We can't create an implicit cast on
6832 * the left side, because we need the uncasted form for the store.
6833 * The ast2firm pass has to know that left_type must be right_type
6834 * for the arithmetic operation and create a cast by itself */
6835 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6836 expression->right = create_implicit_cast(right, arithmetic_type);
6837 expression->base.type = type_left;
6840 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6842 expression_t *const left = expression->left;
6843 expression_t *const right = expression->right;
6844 type_t *const orig_type_left = left->base.type;
6845 type_t *const orig_type_right = right->base.type;
6846 type_t *const type_left = skip_typeref(orig_type_left);
6847 type_t *const type_right = skip_typeref(orig_type_right);
6849 if (!is_valid_assignment_lhs(left))
6852 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6853 /* combined instructions are tricky. We can't create an implicit cast on
6854 * the left side, because we need the uncasted form for the store.
6855 * The ast2firm pass has to know that left_type must be right_type
6856 * for the arithmetic operation and create a cast by itself */
6857 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6858 expression->right = create_implicit_cast(right, arithmetic_type);
6859 expression->base.type = type_left;
6860 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6861 check_pointer_arithmetic(&expression->base.source_position,
6862 type_left, orig_type_left);
6863 expression->base.type = type_left;
6864 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6865 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6870 * Check the semantic restrictions of a logical expression.
6872 static void semantic_logical_op(binary_expression_t *expression)
6874 expression_t *const left = expression->left;
6875 expression_t *const right = expression->right;
6876 type_t *const orig_type_left = left->base.type;
6877 type_t *const orig_type_right = right->base.type;
6878 type_t *const type_left = skip_typeref(orig_type_left);
6879 type_t *const type_right = skip_typeref(orig_type_right);
6881 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6882 /* TODO: improve error message */
6883 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6884 errorf(HERE, "operation needs scalar types");
6889 expression->base.type = type_int;
6893 * Check the semantic restrictions of a binary assign expression.
6895 static void semantic_binexpr_assign(binary_expression_t *expression)
6897 expression_t *left = expression->left;
6898 type_t *orig_type_left = left->base.type;
6900 type_t *type_left = revert_automatic_type_conversion(left);
6901 type_left = skip_typeref(orig_type_left);
6903 if (!is_valid_assignment_lhs(left))
6906 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6907 report_assign_error(error, orig_type_left, expression->right,
6908 "assignment", &left->base.source_position);
6909 expression->right = create_implicit_cast(expression->right, orig_type_left);
6910 expression->base.type = orig_type_left;
6914 * Determine if the outermost operation (or parts thereof) of the given
6915 * expression has no effect in order to generate a warning about this fact.
6916 * Therefore in some cases this only examines some of the operands of the
6917 * expression (see comments in the function and examples below).
6919 * f() + 23; // warning, because + has no effect
6920 * x || f(); // no warning, because x controls execution of f()
6921 * x ? y : f(); // warning, because y has no effect
6922 * (void)x; // no warning to be able to suppress the warning
6923 * This function can NOT be used for an "expression has definitely no effect"-
6925 static bool expression_has_effect(const expression_t *const expr)
6927 switch (expr->kind) {
6928 case EXPR_UNKNOWN: break;
6929 case EXPR_INVALID: return true; /* do NOT warn */
6930 case EXPR_REFERENCE: return false;
6931 /* suppress the warning for microsoft __noop operations */
6932 case EXPR_CONST: return expr->conste.is_ms_noop;
6933 case EXPR_CHARACTER_CONSTANT: return false;
6934 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6935 case EXPR_STRING_LITERAL: return false;
6936 case EXPR_WIDE_STRING_LITERAL: return false;
6939 const call_expression_t *const call = &expr->call;
6940 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6943 switch (call->function->builtin_symbol.symbol->ID) {
6944 case T___builtin_va_end: return true;
6945 default: return false;
6949 /* Generate the warning if either the left or right hand side of a
6950 * conditional expression has no effect */
6951 case EXPR_CONDITIONAL: {
6952 const conditional_expression_t *const cond = &expr->conditional;
6954 expression_has_effect(cond->true_expression) &&
6955 expression_has_effect(cond->false_expression);
6958 case EXPR_SELECT: return false;
6959 case EXPR_ARRAY_ACCESS: return false;
6960 case EXPR_SIZEOF: return false;
6961 case EXPR_CLASSIFY_TYPE: return false;
6962 case EXPR_ALIGNOF: return false;
6964 case EXPR_FUNCNAME: return false;
6965 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6966 case EXPR_BUILTIN_CONSTANT_P: return false;
6967 case EXPR_BUILTIN_PREFETCH: return true;
6968 case EXPR_OFFSETOF: return false;
6969 case EXPR_VA_START: return true;
6970 case EXPR_VA_ARG: return true;
6971 case EXPR_STATEMENT: return true; // TODO
6972 case EXPR_COMPOUND_LITERAL: return false;
6974 case EXPR_UNARY_NEGATE: return false;
6975 case EXPR_UNARY_PLUS: return false;
6976 case EXPR_UNARY_BITWISE_NEGATE: return false;
6977 case EXPR_UNARY_NOT: return false;
6978 case EXPR_UNARY_DEREFERENCE: return false;
6979 case EXPR_UNARY_TAKE_ADDRESS: return false;
6980 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6981 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6982 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6983 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6985 /* Treat void casts as if they have an effect in order to being able to
6986 * suppress the warning */
6987 case EXPR_UNARY_CAST: {
6988 type_t *const type = skip_typeref(expr->base.type);
6989 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6992 case EXPR_UNARY_CAST_IMPLICIT: return true;
6993 case EXPR_UNARY_ASSUME: return true;
6995 case EXPR_BINARY_ADD: return false;
6996 case EXPR_BINARY_SUB: return false;
6997 case EXPR_BINARY_MUL: return false;
6998 case EXPR_BINARY_DIV: return false;
6999 case EXPR_BINARY_MOD: return false;
7000 case EXPR_BINARY_EQUAL: return false;
7001 case EXPR_BINARY_NOTEQUAL: return false;
7002 case EXPR_BINARY_LESS: return false;
7003 case EXPR_BINARY_LESSEQUAL: return false;
7004 case EXPR_BINARY_GREATER: return false;
7005 case EXPR_BINARY_GREATEREQUAL: return false;
7006 case EXPR_BINARY_BITWISE_AND: return false;
7007 case EXPR_BINARY_BITWISE_OR: return false;
7008 case EXPR_BINARY_BITWISE_XOR: return false;
7009 case EXPR_BINARY_SHIFTLEFT: return false;
7010 case EXPR_BINARY_SHIFTRIGHT: return false;
7011 case EXPR_BINARY_ASSIGN: return true;
7012 case EXPR_BINARY_MUL_ASSIGN: return true;
7013 case EXPR_BINARY_DIV_ASSIGN: return true;
7014 case EXPR_BINARY_MOD_ASSIGN: return true;
7015 case EXPR_BINARY_ADD_ASSIGN: return true;
7016 case EXPR_BINARY_SUB_ASSIGN: return true;
7017 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7018 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7019 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7020 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7021 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7023 /* Only examine the right hand side of && and ||, because the left hand
7024 * side already has the effect of controlling the execution of the right
7026 case EXPR_BINARY_LOGICAL_AND:
7027 case EXPR_BINARY_LOGICAL_OR:
7028 /* Only examine the right hand side of a comma expression, because the left
7029 * hand side has a separate warning */
7030 case EXPR_BINARY_COMMA:
7031 return expression_has_effect(expr->binary.right);
7033 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7034 case EXPR_BINARY_ISGREATER: return false;
7035 case EXPR_BINARY_ISGREATEREQUAL: return false;
7036 case EXPR_BINARY_ISLESS: return false;
7037 case EXPR_BINARY_ISLESSEQUAL: return false;
7038 case EXPR_BINARY_ISLESSGREATER: return false;
7039 case EXPR_BINARY_ISUNORDERED: return false;
7042 internal_errorf(HERE, "unexpected expression");
7045 static void semantic_comma(binary_expression_t *expression)
7047 if (warning.unused_value) {
7048 const expression_t *const left = expression->left;
7049 if (!expression_has_effect(left)) {
7050 warningf(&left->base.source_position,
7051 "left-hand operand of comma expression has no effect");
7054 expression->base.type = expression->right->base.type;
7057 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7058 static expression_t *parse_##binexpression_type(unsigned precedence, \
7059 expression_t *left) \
7062 source_position_t pos = *HERE; \
7064 expression_t *right = parse_sub_expression(precedence + lr); \
7066 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7067 binexpr->base.source_position = pos; \
7068 binexpr->binary.left = left; \
7069 binexpr->binary.right = right; \
7070 sfunc(&binexpr->binary); \
7075 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7076 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7077 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7078 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7079 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7080 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7081 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7082 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7083 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7085 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7086 semantic_comparison, 1)
7087 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7088 semantic_comparison, 1)
7089 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7090 semantic_comparison, 1)
7091 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7092 semantic_comparison, 1)
7094 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7095 semantic_binexpr_arithmetic, 1)
7096 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7097 semantic_binexpr_arithmetic, 1)
7098 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7099 semantic_binexpr_arithmetic, 1)
7100 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7101 semantic_logical_op, 1)
7102 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7103 semantic_logical_op, 1)
7104 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7105 semantic_shift_op, 1)
7106 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7107 semantic_shift_op, 1)
7108 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7109 semantic_arithmetic_addsubb_assign, 0)
7110 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7111 semantic_arithmetic_addsubb_assign, 0)
7112 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7113 semantic_arithmetic_assign, 0)
7114 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7115 semantic_arithmetic_assign, 0)
7116 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7117 semantic_arithmetic_assign, 0)
7118 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7119 semantic_arithmetic_assign, 0)
7120 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7121 semantic_arithmetic_assign, 0)
7122 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7123 semantic_arithmetic_assign, 0)
7124 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7125 semantic_arithmetic_assign, 0)
7126 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7127 semantic_arithmetic_assign, 0)
7129 static expression_t *parse_sub_expression(unsigned precedence)
7131 if(token.type < 0) {
7132 return expected_expression_error();
7135 expression_parser_function_t *parser
7136 = &expression_parsers[token.type];
7137 source_position_t source_position = token.source_position;
7140 if(parser->parser != NULL) {
7141 left = parser->parser(parser->precedence);
7143 left = parse_primary_expression();
7145 assert(left != NULL);
7146 left->base.source_position = source_position;
7149 if(token.type < 0) {
7150 return expected_expression_error();
7153 parser = &expression_parsers[token.type];
7154 if(parser->infix_parser == NULL)
7156 if(parser->infix_precedence < precedence)
7159 left = parser->infix_parser(parser->infix_precedence, left);
7161 assert(left != NULL);
7162 assert(left->kind != EXPR_UNKNOWN);
7163 left->base.source_position = source_position;
7170 * Parse an expression.
7172 static expression_t *parse_expression(void)
7174 return parse_sub_expression(1);
7178 * Register a parser for a prefix-like operator with given precedence.
7180 * @param parser the parser function
7181 * @param token_type the token type of the prefix token
7182 * @param precedence the precedence of the operator
7184 static void register_expression_parser(parse_expression_function parser,
7185 int token_type, unsigned precedence)
7187 expression_parser_function_t *entry = &expression_parsers[token_type];
7189 if(entry->parser != NULL) {
7190 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7191 panic("trying to register multiple expression parsers for a token");
7193 entry->parser = parser;
7194 entry->precedence = precedence;
7198 * Register a parser for an infix operator with given precedence.
7200 * @param parser the parser function
7201 * @param token_type the token type of the infix operator
7202 * @param precedence the precedence of the operator
7204 static void register_infix_parser(parse_expression_infix_function parser,
7205 int token_type, unsigned precedence)
7207 expression_parser_function_t *entry = &expression_parsers[token_type];
7209 if(entry->infix_parser != NULL) {
7210 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7211 panic("trying to register multiple infix expression parsers for a "
7214 entry->infix_parser = parser;
7215 entry->infix_precedence = precedence;
7219 * Initialize the expression parsers.
7221 static void init_expression_parsers(void)
7223 memset(&expression_parsers, 0, sizeof(expression_parsers));
7225 register_infix_parser(parse_array_expression, '[', 30);
7226 register_infix_parser(parse_call_expression, '(', 30);
7227 register_infix_parser(parse_select_expression, '.', 30);
7228 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7229 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7231 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7234 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7235 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7236 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7237 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7238 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7239 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7240 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7241 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7242 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7243 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7244 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7245 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7246 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7247 T_EXCLAMATIONMARKEQUAL, 13);
7248 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7249 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7250 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7251 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7252 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7253 register_infix_parser(parse_conditional_expression, '?', 7);
7254 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7255 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7256 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7257 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7258 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7259 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7260 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7261 T_LESSLESSEQUAL, 2);
7262 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7263 T_GREATERGREATEREQUAL, 2);
7264 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7266 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7268 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7271 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7273 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7274 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7275 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7276 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7277 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7278 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7279 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7281 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7283 register_expression_parser(parse_sizeof, T_sizeof, 25);
7284 register_expression_parser(parse_alignof, T___alignof__, 25);
7285 register_expression_parser(parse_extension, T___extension__, 25);
7286 register_expression_parser(parse_builtin_classify_type,
7287 T___builtin_classify_type, 25);
7291 * Parse a asm statement arguments specification.
7293 static asm_argument_t *parse_asm_arguments(bool is_out)
7295 asm_argument_t *result = NULL;
7296 asm_argument_t *last = NULL;
7298 while (token.type == T_STRING_LITERAL || token.type == '[') {
7299 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7300 memset(argument, 0, sizeof(argument[0]));
7302 if (token.type == '[') {
7304 if (token.type != T_IDENTIFIER) {
7305 parse_error_expected("while parsing asm argument",
7306 T_IDENTIFIER, NULL);
7309 argument->symbol = token.v.symbol;
7314 argument->constraints = parse_string_literals();
7316 expression_t *expression = parse_expression();
7317 argument->expression = expression;
7318 if (is_out && !is_lvalue(expression)) {
7319 errorf(&expression->base.source_position,
7320 "asm output argument is not an lvalue");
7324 set_address_taken(expression, true);
7327 last->next = argument;
7333 if (token.type != ',')
7344 * Parse a asm statement clobber specification.
7346 static asm_clobber_t *parse_asm_clobbers(void)
7348 asm_clobber_t *result = NULL;
7349 asm_clobber_t *last = NULL;
7351 while(token.type == T_STRING_LITERAL) {
7352 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7353 clobber->clobber = parse_string_literals();
7356 last->next = clobber;
7362 if(token.type != ',')
7371 * Parse an asm statement.
7373 static statement_t *parse_asm_statement(void)
7377 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7378 statement->base.source_position = token.source_position;
7380 asm_statement_t *asm_statement = &statement->asms;
7382 if(token.type == T_volatile) {
7384 asm_statement->is_volatile = true;
7388 add_anchor_token(')');
7389 add_anchor_token(':');
7390 asm_statement->asm_text = parse_string_literals();
7392 if(token.type != ':') {
7393 rem_anchor_token(':');
7398 asm_statement->outputs = parse_asm_arguments(true);
7399 if(token.type != ':') {
7400 rem_anchor_token(':');
7405 asm_statement->inputs = parse_asm_arguments(false);
7406 if(token.type != ':') {
7407 rem_anchor_token(':');
7410 rem_anchor_token(':');
7413 asm_statement->clobbers = parse_asm_clobbers();
7416 rem_anchor_token(')');
7421 return create_invalid_statement();
7425 * Parse a case statement.
7427 static statement_t *parse_case_statement(void)
7431 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7433 statement->base.source_position = token.source_position;
7434 statement->case_label.expression = parse_expression();
7436 if (c_mode & _GNUC) {
7437 if (token.type == T_DOTDOTDOT) {
7439 statement->case_label.end_range = parse_expression();
7445 if (! is_constant_expression(statement->case_label.expression)) {
7446 errorf(&statement->base.source_position,
7447 "case label does not reduce to an integer constant");
7449 /* TODO: check if the case label is already known */
7450 if (current_switch != NULL) {
7451 /* link all cases into the switch statement */
7452 if (current_switch->last_case == NULL) {
7453 current_switch->first_case =
7454 current_switch->last_case = &statement->case_label;
7456 current_switch->last_case->next = &statement->case_label;
7459 errorf(&statement->base.source_position,
7460 "case label not within a switch statement");
7463 statement->case_label.statement = parse_statement();
7467 return create_invalid_statement();
7471 * Finds an existing default label of a switch statement.
7473 static case_label_statement_t *
7474 find_default_label(const switch_statement_t *statement)
7476 case_label_statement_t *label = statement->first_case;
7477 for ( ; label != NULL; label = label->next) {
7478 if (label->expression == NULL)
7485 * Parse a default statement.
7487 static statement_t *parse_default_statement(void)
7491 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7493 statement->base.source_position = token.source_position;
7496 if (current_switch != NULL) {
7497 const case_label_statement_t *def_label = find_default_label(current_switch);
7498 if (def_label != NULL) {
7499 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7500 &def_label->base.source_position);
7502 /* link all cases into the switch statement */
7503 if (current_switch->last_case == NULL) {
7504 current_switch->first_case =
7505 current_switch->last_case = &statement->case_label;
7507 current_switch->last_case->next = &statement->case_label;
7511 errorf(&statement->base.source_position,
7512 "'default' label not within a switch statement");
7514 statement->case_label.statement = parse_statement();
7518 return create_invalid_statement();
7522 * Return the declaration for a given label symbol or create a new one.
7524 static declaration_t *get_label(symbol_t *symbol)
7526 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7527 assert(current_function != NULL);
7528 /* if we found a label in the same function, then we already created the
7530 if(candidate != NULL
7531 && candidate->parent_scope == ¤t_function->scope) {
7535 /* otherwise we need to create a new one */
7536 declaration_t *const declaration = allocate_declaration_zero();
7537 declaration->namespc = NAMESPACE_LABEL;
7538 declaration->symbol = symbol;
7540 label_push(declaration);
7546 * Parse a label statement.
7548 static statement_t *parse_label_statement(void)
7550 assert(token.type == T_IDENTIFIER);
7551 symbol_t *symbol = token.v.symbol;
7554 declaration_t *label = get_label(symbol);
7556 /* if source position is already set then the label is defined twice,
7557 * otherwise it was just mentioned in a goto so far */
7558 if(label->source_position.input_name != NULL) {
7559 errorf(HERE, "duplicate label '%Y' (declared %P)",
7560 symbol, &label->source_position);
7562 label->source_position = token.source_position;
7565 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7567 statement->base.source_position = token.source_position;
7568 statement->label.label = label;
7572 if(token.type == '}') {
7573 /* TODO only warn? */
7575 warningf(HERE, "label at end of compound statement");
7576 statement->label.statement = create_empty_statement();
7578 errorf(HERE, "label at end of compound statement");
7579 statement->label.statement = create_invalid_statement();
7583 if (token.type == ';') {
7584 /* eat an empty statement here, to avoid the warning about an empty
7585 * after a label. label:; is commonly used to have a label before
7587 statement->label.statement = create_empty_statement();
7590 statement->label.statement = parse_statement();
7594 /* remember the labels's in a list for later checking */
7595 if (label_last == NULL) {
7596 label_first = &statement->label;
7598 label_last->next = &statement->label;
7600 label_last = &statement->label;
7606 * Parse an if statement.
7608 static statement_t *parse_if(void)
7612 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7613 statement->base.source_position = token.source_position;
7616 add_anchor_token(')');
7617 statement->ifs.condition = parse_expression();
7618 rem_anchor_token(')');
7621 add_anchor_token(T_else);
7622 statement->ifs.true_statement = parse_statement();
7623 rem_anchor_token(T_else);
7625 if(token.type == T_else) {
7627 statement->ifs.false_statement = parse_statement();
7632 return create_invalid_statement();
7636 * Parse a switch statement.
7638 static statement_t *parse_switch(void)
7642 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7643 statement->base.source_position = token.source_position;
7646 expression_t *const expr = parse_expression();
7647 type_t * type = skip_typeref(expr->base.type);
7648 if (is_type_integer(type)) {
7649 type = promote_integer(type);
7650 } else if (is_type_valid(type)) {
7651 errorf(&expr->base.source_position,
7652 "switch quantity is not an integer, but '%T'", type);
7653 type = type_error_type;
7655 statement->switchs.expression = create_implicit_cast(expr, type);
7658 switch_statement_t *rem = current_switch;
7659 current_switch = &statement->switchs;
7660 statement->switchs.body = parse_statement();
7661 current_switch = rem;
7663 if(warning.switch_default &&
7664 find_default_label(&statement->switchs) == NULL) {
7665 warningf(&statement->base.source_position, "switch has no default case");
7670 return create_invalid_statement();
7673 static statement_t *parse_loop_body(statement_t *const loop)
7675 statement_t *const rem = current_loop;
7676 current_loop = loop;
7678 statement_t *const body = parse_statement();
7685 * Parse a while statement.
7687 static statement_t *parse_while(void)
7691 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7692 statement->base.source_position = token.source_position;
7695 add_anchor_token(')');
7696 statement->whiles.condition = parse_expression();
7697 rem_anchor_token(')');
7700 statement->whiles.body = parse_loop_body(statement);
7704 return create_invalid_statement();
7708 * Parse a do statement.
7710 static statement_t *parse_do(void)
7714 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7716 statement->base.source_position = token.source_position;
7718 add_anchor_token(T_while);
7719 statement->do_while.body = parse_loop_body(statement);
7720 rem_anchor_token(T_while);
7724 add_anchor_token(')');
7725 statement->do_while.condition = parse_expression();
7726 rem_anchor_token(')');
7732 return create_invalid_statement();
7736 * Parse a for statement.
7738 static statement_t *parse_for(void)
7742 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7743 statement->base.source_position = token.source_position;
7745 int top = environment_top();
7746 scope_t *last_scope = scope;
7747 set_scope(&statement->fors.scope);
7750 add_anchor_token(')');
7752 if(token.type != ';') {
7753 if(is_declaration_specifier(&token, false)) {
7754 parse_declaration(record_declaration);
7756 add_anchor_token(';');
7757 expression_t *const init = parse_expression();
7758 statement->fors.initialisation = init;
7759 if (warning.unused_value && !expression_has_effect(init)) {
7760 warningf(&init->base.source_position,
7761 "initialisation of 'for'-statement has no effect");
7763 rem_anchor_token(';');
7770 if(token.type != ';') {
7771 add_anchor_token(';');
7772 statement->fors.condition = parse_expression();
7773 rem_anchor_token(';');
7776 if(token.type != ')') {
7777 expression_t *const step = parse_expression();
7778 statement->fors.step = step;
7779 if (warning.unused_value && !expression_has_effect(step)) {
7780 warningf(&step->base.source_position,
7781 "step of 'for'-statement has no effect");
7784 rem_anchor_token(')');
7786 statement->fors.body = parse_loop_body(statement);
7788 assert(scope == &statement->fors.scope);
7789 set_scope(last_scope);
7790 environment_pop_to(top);
7795 rem_anchor_token(')');
7796 assert(scope == &statement->fors.scope);
7797 set_scope(last_scope);
7798 environment_pop_to(top);
7800 return create_invalid_statement();
7804 * Parse a goto statement.
7806 static statement_t *parse_goto(void)
7810 if(token.type != T_IDENTIFIER) {
7811 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7815 symbol_t *symbol = token.v.symbol;
7818 declaration_t *label = get_label(symbol);
7820 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7821 statement->base.source_position = token.source_position;
7823 statement->gotos.label = label;
7825 /* remember the goto's in a list for later checking */
7826 if (goto_last == NULL) {
7827 goto_first = &statement->gotos;
7829 goto_last->next = &statement->gotos;
7831 goto_last = &statement->gotos;
7837 return create_invalid_statement();
7841 * Parse a continue statement.
7843 static statement_t *parse_continue(void)
7845 statement_t *statement;
7846 if (current_loop == NULL) {
7847 errorf(HERE, "continue statement not within loop");
7848 statement = create_invalid_statement();
7850 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7852 statement->base.source_position = token.source_position;
7860 return create_invalid_statement();
7864 * Parse a break statement.
7866 static statement_t *parse_break(void)
7868 statement_t *statement;
7869 if (current_switch == NULL && current_loop == NULL) {
7870 errorf(HERE, "break statement not within loop or switch");
7871 statement = create_invalid_statement();
7873 statement = allocate_statement_zero(STATEMENT_BREAK);
7875 statement->base.source_position = token.source_position;
7883 return create_invalid_statement();
7887 * Parse a __leave statement.
7889 static statement_t *parse_leave(void)
7891 statement_t *statement;
7892 if (current_try == NULL) {
7893 errorf(HERE, "__leave statement not within __try");
7894 statement = create_invalid_statement();
7896 statement = allocate_statement_zero(STATEMENT_LEAVE);
7898 statement->base.source_position = token.source_position;
7906 return create_invalid_statement();
7910 * Check if a given declaration represents a local variable.
7912 static bool is_local_var_declaration(const declaration_t *declaration) {
7913 switch ((storage_class_tag_t) declaration->storage_class) {
7914 case STORAGE_CLASS_AUTO:
7915 case STORAGE_CLASS_REGISTER: {
7916 const type_t *type = skip_typeref(declaration->type);
7917 if(is_type_function(type)) {
7929 * Check if a given declaration represents a variable.
7931 static bool is_var_declaration(const declaration_t *declaration) {
7932 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7935 const type_t *type = skip_typeref(declaration->type);
7936 return !is_type_function(type);
7940 * Check if a given expression represents a local variable.
7942 static bool is_local_variable(const expression_t *expression)
7944 if (expression->base.kind != EXPR_REFERENCE) {
7947 const declaration_t *declaration = expression->reference.declaration;
7948 return is_local_var_declaration(declaration);
7952 * Check if a given expression represents a local variable and
7953 * return its declaration then, else return NULL.
7955 declaration_t *expr_is_variable(const expression_t *expression)
7957 if (expression->base.kind != EXPR_REFERENCE) {
7960 declaration_t *declaration = expression->reference.declaration;
7961 if (is_var_declaration(declaration))
7967 * Parse a return statement.
7969 static statement_t *parse_return(void)
7971 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7972 statement->base.source_position = token.source_position;
7976 expression_t *return_value = NULL;
7977 if(token.type != ';') {
7978 return_value = parse_expression();
7982 const type_t *const func_type = current_function->type;
7983 assert(is_type_function(func_type));
7984 type_t *const return_type = skip_typeref(func_type->function.return_type);
7986 if(return_value != NULL) {
7987 type_t *return_value_type = skip_typeref(return_value->base.type);
7989 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7990 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7991 warningf(&statement->base.source_position,
7992 "'return' with a value, in function returning void");
7993 return_value = NULL;
7995 assign_error_t error = semantic_assign(return_type, return_value);
7996 report_assign_error(error, return_type, return_value, "'return'",
7997 &statement->base.source_position);
7998 return_value = create_implicit_cast(return_value, return_type);
8000 /* check for returning address of a local var */
8001 if (return_value != NULL &&
8002 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8003 const expression_t *expression = return_value->unary.value;
8004 if (is_local_variable(expression)) {
8005 warningf(&statement->base.source_position,
8006 "function returns address of local variable");
8010 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8011 warningf(&statement->base.source_position,
8012 "'return' without value, in function returning non-void");
8015 statement->returns.value = return_value;
8019 return create_invalid_statement();
8023 * Parse a declaration statement.
8025 static statement_t *parse_declaration_statement(void)
8027 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8029 statement->base.source_position = token.source_position;
8031 declaration_t *before = last_declaration;
8032 parse_declaration(record_declaration);
8034 if(before == NULL) {
8035 statement->declaration.declarations_begin = scope->declarations;
8037 statement->declaration.declarations_begin = before->next;
8039 statement->declaration.declarations_end = last_declaration;
8045 * Parse an expression statement, ie. expr ';'.
8047 static statement_t *parse_expression_statement(void)
8049 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8051 statement->base.source_position = token.source_position;
8052 expression_t *const expr = parse_expression();
8053 statement->expression.expression = expr;
8059 return create_invalid_statement();
8063 * Parse a microsoft __try { } __finally { } or
8064 * __try{ } __except() { }
8066 static statement_t *parse_ms_try_statment(void) {
8067 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8069 statement->base.source_position = token.source_position;
8072 ms_try_statement_t *rem = current_try;
8073 current_try = &statement->ms_try;
8074 statement->ms_try.try_statement = parse_compound_statement(false);
8077 if(token.type == T___except) {
8080 add_anchor_token(')');
8081 expression_t *const expr = parse_expression();
8082 type_t * type = skip_typeref(expr->base.type);
8083 if (is_type_integer(type)) {
8084 type = promote_integer(type);
8085 } else if (is_type_valid(type)) {
8086 errorf(&expr->base.source_position,
8087 "__expect expression is not an integer, but '%T'", type);
8088 type = type_error_type;
8090 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8091 rem_anchor_token(')');
8093 statement->ms_try.final_statement = parse_compound_statement(false);
8094 } else if(token.type == T__finally) {
8096 statement->ms_try.final_statement = parse_compound_statement(false);
8098 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8099 return create_invalid_statement();
8103 return create_invalid_statement();
8107 * Parse a statement.
8108 * There's also parse_statement() which additionally checks for
8109 * "statement has no effect" warnings
8111 static statement_t *intern_parse_statement(void)
8113 statement_t *statement = NULL;
8115 /* declaration or statement */
8116 add_anchor_token(';');
8117 switch(token.type) {
8119 statement = parse_asm_statement();
8123 statement = parse_case_statement();
8127 statement = parse_default_statement();
8131 statement = parse_compound_statement(false);
8135 statement = parse_if();
8139 statement = parse_switch();
8143 statement = parse_while();
8147 statement = parse_do();
8151 statement = parse_for();
8155 statement = parse_goto();
8159 statement = parse_continue();
8163 statement = parse_break();
8167 statement = parse_leave();
8171 statement = parse_return();
8175 if(warning.empty_statement) {
8176 warningf(HERE, "statement is empty");
8178 statement = create_empty_statement();
8183 if(look_ahead(1)->type == ':') {
8184 statement = parse_label_statement();
8188 if(is_typedef_symbol(token.v.symbol)) {
8189 statement = parse_declaration_statement();
8193 statement = parse_expression_statement();
8196 case T___extension__:
8197 /* this can be a prefix to a declaration or an expression statement */
8198 /* we simply eat it now and parse the rest with tail recursion */
8201 } while(token.type == T___extension__);
8202 statement = parse_statement();
8206 statement = parse_declaration_statement();
8210 statement = parse_ms_try_statment();
8214 statement = parse_expression_statement();
8217 rem_anchor_token(';');
8219 assert(statement != NULL
8220 && statement->base.source_position.input_name != NULL);
8226 * parse a statement and emits "statement has no effect" warning if needed
8227 * (This is really a wrapper around intern_parse_statement with check for 1
8228 * single warning. It is needed, because for statement expressions we have
8229 * to avoid the warning on the last statement)
8231 static statement_t *parse_statement(void)
8233 statement_t *statement = intern_parse_statement();
8235 if(statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8236 expression_t *expression = statement->expression.expression;
8237 if(!expression_has_effect(expression)) {
8238 warningf(&expression->base.source_position,
8239 "statement has no effect");
8247 * Parse a compound statement.
8249 static statement_t *parse_compound_statement(bool inside_expression_statement)
8251 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8253 statement->base.source_position = token.source_position;
8256 add_anchor_token('}');
8258 int top = environment_top();
8259 scope_t *last_scope = scope;
8260 set_scope(&statement->compound.scope);
8262 statement_t *last_statement = NULL;
8264 while(token.type != '}' && token.type != T_EOF) {
8265 statement_t *sub_statement = intern_parse_statement();
8266 if(is_invalid_statement(sub_statement)) {
8267 /* an error occurred. if we are at an anchor, return */
8273 if(last_statement != NULL) {
8274 last_statement->base.next = sub_statement;
8276 statement->compound.statements = sub_statement;
8279 while(sub_statement->base.next != NULL)
8280 sub_statement = sub_statement->base.next;
8282 last_statement = sub_statement;
8285 if(token.type == '}') {
8288 errorf(&statement->base.source_position,
8289 "end of file while looking for closing '}'");
8292 /* look over all statements again to produce no effect warnings */
8293 if(warning.unused_value) {
8294 statement_t *sub_statement = statement->compound.statements;
8295 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8296 if(sub_statement->kind != STATEMENT_EXPRESSION)
8298 /* don't emit a warning for the last expression in an expression
8299 * statement as it has always an effect */
8300 if(inside_expression_statement && sub_statement->base.next == NULL)
8303 expression_t *expression = sub_statement->expression.expression;
8304 if(!expression_has_effect(expression)) {
8305 warningf(&expression->base.source_position,
8306 "statement has no effect");
8312 rem_anchor_token('}');
8313 assert(scope == &statement->compound.scope);
8314 set_scope(last_scope);
8315 environment_pop_to(top);
8321 * Initialize builtin types.
8323 static void initialize_builtin_types(void)
8325 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8326 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8327 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8328 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8329 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8330 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8331 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8332 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8334 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8335 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8336 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8337 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8341 * Check for unused global static functions and variables
8343 static void check_unused_globals(void)
8345 if (!warning.unused_function && !warning.unused_variable)
8348 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8349 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
8352 type_t *const type = decl->type;
8354 if (is_type_function(skip_typeref(type))) {
8355 if (!warning.unused_function || decl->is_inline)
8358 s = (decl->init.statement != NULL ? "defined" : "declared");
8360 if (!warning.unused_variable)
8366 warningf(&decl->source_position, "'%#T' %s but not used",
8367 type, decl->symbol, s);
8372 * Parse a translation unit.
8374 static void parse_translation_unit(void)
8376 while(token.type != T_EOF) {
8377 if (token.type == ';') {
8378 /* TODO error in strict mode */
8379 warningf(HERE, "stray ';' outside of function");
8382 parse_external_declaration();
8390 * @return the translation unit or NULL if errors occurred.
8392 void start_parsing(void)
8394 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8395 label_stack = NEW_ARR_F(stack_entry_t, 0);
8396 diagnostic_count = 0;
8400 type_set_output(stderr);
8401 ast_set_output(stderr);
8403 assert(unit == NULL);
8404 unit = allocate_ast_zero(sizeof(unit[0]));
8406 assert(global_scope == NULL);
8407 global_scope = &unit->scope;
8409 assert(scope == NULL);
8410 set_scope(&unit->scope);
8412 initialize_builtin_types();
8415 translation_unit_t *finish_parsing(void)
8417 assert(scope == &unit->scope);
8419 last_declaration = NULL;
8421 assert(global_scope == &unit->scope);
8422 check_unused_globals();
8423 global_scope = NULL;
8425 DEL_ARR_F(environment_stack);
8426 DEL_ARR_F(label_stack);
8428 translation_unit_t *result = unit;
8435 lookahead_bufpos = 0;
8436 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8439 parse_translation_unit();
8443 * Initialize the parser.
8445 void init_parser(void)
8448 /* add predefined symbols for extended-decl-modifier */
8449 sym_align = symbol_table_insert("align");
8450 sym_allocate = symbol_table_insert("allocate");
8451 sym_dllimport = symbol_table_insert("dllimport");
8452 sym_dllexport = symbol_table_insert("dllexport");
8453 sym_naked = symbol_table_insert("naked");
8454 sym_noinline = symbol_table_insert("noinline");
8455 sym_noreturn = symbol_table_insert("noreturn");
8456 sym_nothrow = symbol_table_insert("nothrow");
8457 sym_novtable = symbol_table_insert("novtable");
8458 sym_property = symbol_table_insert("property");
8459 sym_get = symbol_table_insert("get");
8460 sym_put = symbol_table_insert("put");
8461 sym_selectany = symbol_table_insert("selectany");
8462 sym_thread = symbol_table_insert("thread");
8463 sym_uuid = symbol_table_insert("uuid");
8464 sym_deprecated = symbol_table_insert("deprecated");
8465 sym_restrict = symbol_table_insert("restrict");
8466 sym_noalias = symbol_table_insert("noalias");
8468 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8470 init_expression_parsers();
8471 obstack_init(&temp_obst);
8473 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8474 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8478 * Terminate the parser.
8480 void exit_parser(void)
8482 obstack_free(&temp_obst, NULL);