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();
1758 /* TODO record modifier */
1759 warningf(HERE, "Ignoring declaration modifier %K", &token);
1764 goto attributes_finished;
1768 attributes_finished:
1773 static designator_t *parse_designation(void)
1775 designator_t *result = NULL;
1776 designator_t *last = NULL;
1779 designator_t *designator;
1780 switch(token.type) {
1782 designator = allocate_ast_zero(sizeof(designator[0]));
1783 designator->source_position = token.source_position;
1785 add_anchor_token(']');
1786 designator->array_index = parse_constant_expression();
1787 rem_anchor_token(']');
1791 designator = allocate_ast_zero(sizeof(designator[0]));
1792 designator->source_position = token.source_position;
1794 if(token.type != T_IDENTIFIER) {
1795 parse_error_expected("while parsing designator",
1796 T_IDENTIFIER, NULL);
1799 designator->symbol = token.v.symbol;
1807 assert(designator != NULL);
1809 last->next = designator;
1811 result = designator;
1819 static initializer_t *initializer_from_string(array_type_t *type,
1820 const string_t *const string)
1822 /* TODO: check len vs. size of array type */
1825 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1826 initializer->string.string = *string;
1831 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1832 wide_string_t *const string)
1834 /* TODO: check len vs. size of array type */
1837 initializer_t *const initializer =
1838 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1839 initializer->wide_string.string = *string;
1845 * Build an initializer from a given expression.
1847 static initializer_t *initializer_from_expression(type_t *orig_type,
1848 expression_t *expression)
1850 /* TODO check that expression is a constant expression */
1852 /* § 6.7.8.14/15 char array may be initialized by string literals */
1853 type_t *type = skip_typeref(orig_type);
1854 type_t *expr_type_orig = expression->base.type;
1855 type_t *expr_type = skip_typeref(expr_type_orig);
1856 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1857 array_type_t *const array_type = &type->array;
1858 type_t *const element_type = skip_typeref(array_type->element_type);
1860 if (element_type->kind == TYPE_ATOMIC) {
1861 atomic_type_kind_t akind = element_type->atomic.akind;
1862 switch (expression->kind) {
1863 case EXPR_STRING_LITERAL:
1864 if (akind == ATOMIC_TYPE_CHAR
1865 || akind == ATOMIC_TYPE_SCHAR
1866 || akind == ATOMIC_TYPE_UCHAR) {
1867 return initializer_from_string(array_type,
1868 &expression->string.value);
1871 case EXPR_WIDE_STRING_LITERAL: {
1872 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1873 if (get_unqualified_type(element_type) == bare_wchar_type) {
1874 return initializer_from_wide_string(array_type,
1875 &expression->wide_string.value);
1885 assign_error_t error = semantic_assign(type, expression);
1886 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1888 report_assign_error(error, type, expression, "initializer",
1889 &expression->base.source_position);
1891 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1892 result->value.value = create_implicit_cast(expression, type);
1898 * Checks if a given expression can be used as an constant initializer.
1900 static bool is_initializer_constant(const expression_t *expression)
1902 return is_constant_expression(expression)
1903 || is_address_constant(expression);
1907 * Parses an scalar initializer.
1909 * § 6.7.8.11; eat {} without warning
1911 static initializer_t *parse_scalar_initializer(type_t *type,
1912 bool must_be_constant)
1914 /* there might be extra {} hierarchies */
1916 if (token.type == '{') {
1917 warningf(HERE, "extra curly braces around scalar initializer");
1921 } while (token.type == '{');
1924 expression_t *expression = parse_assignment_expression();
1925 if(must_be_constant && !is_initializer_constant(expression)) {
1926 errorf(&expression->base.source_position,
1927 "Initialisation expression '%E' is not constant\n",
1931 initializer_t *initializer = initializer_from_expression(type, expression);
1933 if(initializer == NULL) {
1934 errorf(&expression->base.source_position,
1935 "expression '%E' (type '%T') doesn't match expected type '%T'",
1936 expression, expression->base.type, type);
1941 bool additional_warning_displayed = false;
1943 if(token.type == ',') {
1946 if(token.type != '}') {
1947 if(!additional_warning_displayed) {
1948 warningf(HERE, "additional elements in scalar initializer");
1949 additional_warning_displayed = true;
1960 * An entry in the type path.
1962 typedef struct type_path_entry_t type_path_entry_t;
1963 struct type_path_entry_t {
1964 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1966 size_t index; /**< For array types: the current index. */
1967 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1972 * A type path expression a position inside compound or array types.
1974 typedef struct type_path_t type_path_t;
1975 struct type_path_t {
1976 type_path_entry_t *path; /**< An flexible array containing the current path. */
1977 type_t *top_type; /**< type of the element the path points */
1978 size_t max_index; /**< largest index in outermost array */
1982 * Prints a type path for debugging.
1984 static __attribute__((unused)) void debug_print_type_path(
1985 const type_path_t *path)
1987 size_t len = ARR_LEN(path->path);
1989 for(size_t i = 0; i < len; ++i) {
1990 const type_path_entry_t *entry = & path->path[i];
1992 type_t *type = skip_typeref(entry->type);
1993 if(is_type_compound(type)) {
1994 /* in gcc mode structs can have no members */
1995 if(entry->v.compound_entry == NULL) {
1999 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2000 } else if(is_type_array(type)) {
2001 fprintf(stderr, "[%zd]", entry->v.index);
2003 fprintf(stderr, "-INVALID-");
2006 if(path->top_type != NULL) {
2007 fprintf(stderr, " (");
2008 print_type(path->top_type);
2009 fprintf(stderr, ")");
2014 * Return the top type path entry, ie. in a path
2015 * (type).a.b returns the b.
2017 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2019 size_t len = ARR_LEN(path->path);
2021 return &path->path[len-1];
2025 * Enlarge the type path by an (empty) element.
2027 static type_path_entry_t *append_to_type_path(type_path_t *path)
2029 size_t len = ARR_LEN(path->path);
2030 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2032 type_path_entry_t *result = & path->path[len];
2033 memset(result, 0, sizeof(result[0]));
2038 * Descending into a sub-type. Enter the scope of the current
2041 static void descend_into_subtype(type_path_t *path)
2043 type_t *orig_top_type = path->top_type;
2044 type_t *top_type = skip_typeref(orig_top_type);
2046 assert(is_type_compound(top_type) || is_type_array(top_type));
2048 type_path_entry_t *top = append_to_type_path(path);
2049 top->type = top_type;
2051 if(is_type_compound(top_type)) {
2052 declaration_t *declaration = top_type->compound.declaration;
2053 declaration_t *entry = declaration->scope.declarations;
2054 top->v.compound_entry = entry;
2057 path->top_type = entry->type;
2059 path->top_type = NULL;
2062 assert(is_type_array(top_type));
2065 path->top_type = top_type->array.element_type;
2070 * Pop an entry from the given type path, ie. returning from
2071 * (type).a.b to (type).a
2073 static void ascend_from_subtype(type_path_t *path)
2075 type_path_entry_t *top = get_type_path_top(path);
2077 path->top_type = top->type;
2079 size_t len = ARR_LEN(path->path);
2080 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2084 * Pop entries from the given type path until the given
2085 * path level is reached.
2087 static void ascend_to(type_path_t *path, size_t top_path_level)
2089 size_t len = ARR_LEN(path->path);
2091 while(len > top_path_level) {
2092 ascend_from_subtype(path);
2093 len = ARR_LEN(path->path);
2097 static bool walk_designator(type_path_t *path, const designator_t *designator,
2098 bool used_in_offsetof)
2100 for( ; designator != NULL; designator = designator->next) {
2101 type_path_entry_t *top = get_type_path_top(path);
2102 type_t *orig_type = top->type;
2104 type_t *type = skip_typeref(orig_type);
2106 if(designator->symbol != NULL) {
2107 symbol_t *symbol = designator->symbol;
2108 if(!is_type_compound(type)) {
2109 if(is_type_valid(type)) {
2110 errorf(&designator->source_position,
2111 "'.%Y' designator used for non-compound type '%T'",
2117 declaration_t *declaration = type->compound.declaration;
2118 declaration_t *iter = declaration->scope.declarations;
2119 for( ; iter != NULL; iter = iter->next) {
2120 if(iter->symbol == symbol) {
2125 errorf(&designator->source_position,
2126 "'%T' has no member named '%Y'", orig_type, symbol);
2129 if(used_in_offsetof) {
2130 type_t *real_type = skip_typeref(iter->type);
2131 if(real_type->kind == TYPE_BITFIELD) {
2132 errorf(&designator->source_position,
2133 "offsetof designator '%Y' may not specify bitfield",
2139 top->type = orig_type;
2140 top->v.compound_entry = iter;
2141 orig_type = iter->type;
2143 expression_t *array_index = designator->array_index;
2144 assert(designator->array_index != NULL);
2146 if(!is_type_array(type)) {
2147 if(is_type_valid(type)) {
2148 errorf(&designator->source_position,
2149 "[%E] designator used for non-array type '%T'",
2150 array_index, orig_type);
2154 if(!is_type_valid(array_index->base.type)) {
2158 long index = fold_constant(array_index);
2159 if(!used_in_offsetof) {
2161 errorf(&designator->source_position,
2162 "array index [%E] must be positive", array_index);
2165 if(type->array.size_constant == true) {
2166 long array_size = type->array.size;
2167 if(index >= array_size) {
2168 errorf(&designator->source_position,
2169 "designator [%E] (%d) exceeds array size %d",
2170 array_index, index, array_size);
2176 top->type = orig_type;
2177 top->v.index = (size_t) index;
2178 orig_type = type->array.element_type;
2180 path->top_type = orig_type;
2182 if(designator->next != NULL) {
2183 descend_into_subtype(path);
2192 static void advance_current_object(type_path_t *path, size_t top_path_level)
2194 type_path_entry_t *top = get_type_path_top(path);
2196 type_t *type = skip_typeref(top->type);
2197 if(is_type_union(type)) {
2198 /* in unions only the first element is initialized */
2199 top->v.compound_entry = NULL;
2200 } else if(is_type_struct(type)) {
2201 declaration_t *entry = top->v.compound_entry;
2203 entry = entry->next;
2204 top->v.compound_entry = entry;
2206 path->top_type = entry->type;
2210 assert(is_type_array(type));
2214 if(!type->array.size_constant || top->v.index < type->array.size) {
2219 /* we're past the last member of the current sub-aggregate, try if we
2220 * can ascend in the type hierarchy and continue with another subobject */
2221 size_t len = ARR_LEN(path->path);
2223 if(len > top_path_level) {
2224 ascend_from_subtype(path);
2225 advance_current_object(path, top_path_level);
2227 path->top_type = NULL;
2232 * skip until token is found.
2234 static void skip_until(int type) {
2235 while(token.type != type) {
2236 if(token.type == T_EOF)
2243 * skip any {...} blocks until a closing bracket is reached.
2245 static void skip_initializers(void)
2247 if(token.type == '{')
2250 while(token.type != '}') {
2251 if(token.type == T_EOF)
2253 if(token.type == '{') {
2261 static initializer_t *create_empty_initializer(void)
2263 static initializer_t empty_initializer
2264 = { .list = { { INITIALIZER_LIST }, 0 } };
2265 return &empty_initializer;
2269 * Parse a part of an initialiser for a struct or union,
2271 static initializer_t *parse_sub_initializer(type_path_t *path,
2272 type_t *outer_type, size_t top_path_level,
2273 parse_initializer_env_t *env)
2275 if(token.type == '}') {
2276 /* empty initializer */
2277 return create_empty_initializer();
2280 type_t *orig_type = path->top_type;
2281 type_t *type = NULL;
2283 if (orig_type == NULL) {
2284 /* We are initializing an empty compound. */
2286 type = skip_typeref(orig_type);
2288 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2289 * initializers in this case. */
2290 if(!is_type_valid(type)) {
2291 skip_initializers();
2292 return create_empty_initializer();
2296 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2299 designator_t *designator = NULL;
2300 if(token.type == '.' || token.type == '[') {
2301 designator = parse_designation();
2303 /* reset path to toplevel, evaluate designator from there */
2304 ascend_to(path, top_path_level);
2305 if(!walk_designator(path, designator, false)) {
2306 /* can't continue after designation error */
2310 initializer_t *designator_initializer
2311 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2312 designator_initializer->designator.designator = designator;
2313 ARR_APP1(initializer_t*, initializers, designator_initializer);
2315 orig_type = path->top_type;
2316 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2321 if(token.type == '{') {
2322 if(type != NULL && is_type_scalar(type)) {
2323 sub = parse_scalar_initializer(type, env->must_be_constant);
2327 if (env->declaration != NULL)
2328 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2329 env->declaration->symbol);
2331 errorf(HERE, "extra brace group at end of initializer");
2333 descend_into_subtype(path);
2335 add_anchor_token('}');
2336 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2338 rem_anchor_token('}');
2341 ascend_from_subtype(path);
2345 goto error_parse_next;
2349 /* must be an expression */
2350 expression_t *expression = parse_assignment_expression();
2352 if(env->must_be_constant && !is_initializer_constant(expression)) {
2353 errorf(&expression->base.source_position,
2354 "Initialisation expression '%E' is not constant\n",
2359 /* we are already outside, ... */
2363 /* handle { "string" } special case */
2364 if((expression->kind == EXPR_STRING_LITERAL
2365 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2366 && outer_type != NULL) {
2367 sub = initializer_from_expression(outer_type, expression);
2369 if(token.type == ',') {
2372 if(token.type != '}') {
2373 warningf(HERE, "excessive elements in initializer for type '%T'",
2376 /* TODO: eat , ... */
2381 /* descend into subtypes until expression matches type */
2383 orig_type = path->top_type;
2384 type = skip_typeref(orig_type);
2386 sub = initializer_from_expression(orig_type, expression);
2390 if(!is_type_valid(type)) {
2393 if(is_type_scalar(type)) {
2394 errorf(&expression->base.source_position,
2395 "expression '%E' doesn't match expected type '%T'",
2396 expression, orig_type);
2400 descend_into_subtype(path);
2404 /* update largest index of top array */
2405 const type_path_entry_t *first = &path->path[0];
2406 type_t *first_type = first->type;
2407 first_type = skip_typeref(first_type);
2408 if(is_type_array(first_type)) {
2409 size_t index = first->v.index;
2410 if(index > path->max_index)
2411 path->max_index = index;
2415 /* append to initializers list */
2416 ARR_APP1(initializer_t*, initializers, sub);
2419 if(env->declaration != NULL)
2420 warningf(HERE, "excess elements in struct initializer for '%Y'",
2421 env->declaration->symbol);
2423 warningf(HERE, "excess elements in struct initializer");
2427 if(token.type == '}') {
2431 if(token.type == '}') {
2436 /* advance to the next declaration if we are not at the end */
2437 advance_current_object(path, top_path_level);
2438 orig_type = path->top_type;
2439 if(orig_type != NULL)
2440 type = skip_typeref(orig_type);
2446 size_t len = ARR_LEN(initializers);
2447 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2448 initializer_t *result = allocate_ast_zero(size);
2449 result->kind = INITIALIZER_LIST;
2450 result->list.len = len;
2451 memcpy(&result->list.initializers, initializers,
2452 len * sizeof(initializers[0]));
2454 DEL_ARR_F(initializers);
2455 ascend_to(path, top_path_level+1);
2460 skip_initializers();
2461 DEL_ARR_F(initializers);
2462 ascend_to(path, top_path_level+1);
2467 * Parses an initializer. Parsers either a compound literal
2468 * (env->declaration == NULL) or an initializer of a declaration.
2470 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2472 type_t *type = skip_typeref(env->type);
2473 initializer_t *result = NULL;
2476 if(is_type_scalar(type)) {
2477 result = parse_scalar_initializer(type, env->must_be_constant);
2478 } else if(token.type == '{') {
2482 memset(&path, 0, sizeof(path));
2483 path.top_type = env->type;
2484 path.path = NEW_ARR_F(type_path_entry_t, 0);
2486 descend_into_subtype(&path);
2488 add_anchor_token('}');
2489 result = parse_sub_initializer(&path, env->type, 1, env);
2490 rem_anchor_token('}');
2492 max_index = path.max_index;
2493 DEL_ARR_F(path.path);
2497 /* parse_scalar_initializer() also works in this case: we simply
2498 * have an expression without {} around it */
2499 result = parse_scalar_initializer(type, env->must_be_constant);
2502 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2503 * the array type size */
2504 if(is_type_array(type) && type->array.size_expression == NULL
2505 && result != NULL) {
2507 switch (result->kind) {
2508 case INITIALIZER_LIST:
2509 size = max_index + 1;
2512 case INITIALIZER_STRING:
2513 size = result->string.string.size;
2516 case INITIALIZER_WIDE_STRING:
2517 size = result->wide_string.string.size;
2520 case INITIALIZER_DESIGNATOR:
2521 case INITIALIZER_VALUE:
2522 /* can happen for parse errors */
2527 internal_errorf(HERE, "invalid initializer type");
2530 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2531 cnst->base.type = type_size_t;
2532 cnst->conste.v.int_value = size;
2534 type_t *new_type = duplicate_type(type);
2536 new_type->array.size_expression = cnst;
2537 new_type->array.size_constant = true;
2538 new_type->array.size = size;
2539 env->type = new_type;
2547 static declaration_t *append_declaration(declaration_t *declaration);
2549 static declaration_t *parse_compound_type_specifier(bool is_struct)
2551 gnu_attribute_t *attributes = NULL;
2552 decl_modifiers_t modifiers = 0;
2559 symbol_t *symbol = NULL;
2560 declaration_t *declaration = NULL;
2562 if (token.type == T___attribute__) {
2563 modifiers |= parse_attributes(&attributes);
2566 if(token.type == T_IDENTIFIER) {
2567 symbol = token.v.symbol;
2571 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2573 declaration = get_declaration(symbol, NAMESPACE_UNION);
2575 } else if(token.type != '{') {
2577 parse_error_expected("while parsing struct type specifier",
2578 T_IDENTIFIER, '{', NULL);
2580 parse_error_expected("while parsing union type specifier",
2581 T_IDENTIFIER, '{', NULL);
2587 if(declaration == NULL) {
2588 declaration = allocate_declaration_zero();
2589 declaration->namespc =
2590 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2591 declaration->source_position = token.source_position;
2592 declaration->symbol = symbol;
2593 declaration->parent_scope = scope;
2594 if (symbol != NULL) {
2595 environment_push(declaration);
2597 append_declaration(declaration);
2600 if(token.type == '{') {
2601 if (declaration->init.complete) {
2602 assert(symbol != NULL);
2603 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2604 is_struct ? "struct" : "union", symbol,
2605 &declaration->source_position);
2606 declaration->scope.declarations = NULL;
2608 declaration->init.complete = true;
2610 parse_compound_type_entries(declaration);
2611 modifiers |= parse_attributes(&attributes);
2614 declaration->modifiers |= modifiers;
2618 static void parse_enum_entries(type_t *const enum_type)
2622 if(token.type == '}') {
2624 errorf(HERE, "empty enum not allowed");
2628 add_anchor_token('}');
2630 if(token.type != T_IDENTIFIER) {
2631 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2633 rem_anchor_token('}');
2637 declaration_t *const entry = allocate_declaration_zero();
2638 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2639 entry->type = enum_type;
2640 entry->symbol = token.v.symbol;
2641 entry->source_position = token.source_position;
2644 if(token.type == '=') {
2646 expression_t *value = parse_constant_expression();
2648 value = create_implicit_cast(value, enum_type);
2649 entry->init.enum_value = value;
2654 record_declaration(entry);
2656 if(token.type != ',')
2659 } while(token.type != '}');
2660 rem_anchor_token('}');
2668 static type_t *parse_enum_specifier(void)
2670 gnu_attribute_t *attributes = NULL;
2671 declaration_t *declaration;
2675 if(token.type == T_IDENTIFIER) {
2676 symbol = token.v.symbol;
2679 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2680 } else if(token.type != '{') {
2681 parse_error_expected("while parsing enum type specifier",
2682 T_IDENTIFIER, '{', NULL);
2689 if(declaration == NULL) {
2690 declaration = allocate_declaration_zero();
2691 declaration->namespc = NAMESPACE_ENUM;
2692 declaration->source_position = token.source_position;
2693 declaration->symbol = symbol;
2694 declaration->parent_scope = scope;
2697 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2698 type->enumt.declaration = declaration;
2700 if(token.type == '{') {
2701 if(declaration->init.complete) {
2702 errorf(HERE, "multiple definitions of enum %Y", symbol);
2704 if (symbol != NULL) {
2705 environment_push(declaration);
2707 append_declaration(declaration);
2708 declaration->init.complete = true;
2710 parse_enum_entries(type);
2711 parse_attributes(&attributes);
2718 * if a symbol is a typedef to another type, return true
2720 static bool is_typedef_symbol(symbol_t *symbol)
2722 const declaration_t *const declaration =
2723 get_declaration(symbol, NAMESPACE_NORMAL);
2725 declaration != NULL &&
2726 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2729 static type_t *parse_typeof(void)
2736 add_anchor_token(')');
2738 expression_t *expression = NULL;
2741 switch(token.type) {
2742 case T___extension__:
2743 /* this can be a prefix to a typename or an expression */
2744 /* we simply eat it now. */
2747 } while(token.type == T___extension__);
2751 if(is_typedef_symbol(token.v.symbol)) {
2752 type = parse_typename();
2754 expression = parse_expression();
2755 type = expression->base.type;
2760 type = parse_typename();
2764 expression = parse_expression();
2765 type = expression->base.type;
2769 rem_anchor_token(')');
2772 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2773 typeof_type->typeoft.expression = expression;
2774 typeof_type->typeoft.typeof_type = type;
2782 SPECIFIER_SIGNED = 1 << 0,
2783 SPECIFIER_UNSIGNED = 1 << 1,
2784 SPECIFIER_LONG = 1 << 2,
2785 SPECIFIER_INT = 1 << 3,
2786 SPECIFIER_DOUBLE = 1 << 4,
2787 SPECIFIER_CHAR = 1 << 5,
2788 SPECIFIER_SHORT = 1 << 6,
2789 SPECIFIER_LONG_LONG = 1 << 7,
2790 SPECIFIER_FLOAT = 1 << 8,
2791 SPECIFIER_BOOL = 1 << 9,
2792 SPECIFIER_VOID = 1 << 10,
2793 SPECIFIER_INT8 = 1 << 11,
2794 SPECIFIER_INT16 = 1 << 12,
2795 SPECIFIER_INT32 = 1 << 13,
2796 SPECIFIER_INT64 = 1 << 14,
2797 SPECIFIER_INT128 = 1 << 15,
2798 SPECIFIER_COMPLEX = 1 << 16,
2799 SPECIFIER_IMAGINARY = 1 << 17,
2802 static type_t *create_builtin_type(symbol_t *const symbol,
2803 type_t *const real_type)
2805 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2806 type->builtin.symbol = symbol;
2807 type->builtin.real_type = real_type;
2809 type_t *result = typehash_insert(type);
2810 if(type != result) {
2817 static type_t *get_typedef_type(symbol_t *symbol)
2819 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2820 if(declaration == NULL ||
2821 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2824 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2825 type->typedeft.declaration = declaration;
2831 * check for the allowed MS alignment values.
2833 static bool check_elignment_value(long long intvalue) {
2834 if(intvalue < 1 || intvalue > 8192) {
2835 errorf(HERE, "illegal alignment value");
2838 unsigned v = (unsigned)intvalue;
2839 for(unsigned i = 1; i <= 8192; i += i) {
2843 errorf(HERE, "alignment must be power of two");
2847 #define DET_MOD(name, tag) do { \
2848 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2849 *modifiers |= tag; \
2852 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2854 decl_modifiers_t *modifiers = &specifiers->modifiers;
2857 if(token.type == T_restrict) {
2859 DET_MOD(restrict, DM_RESTRICT);
2861 } else if(token.type != T_IDENTIFIER)
2863 symbol_t *symbol = token.v.symbol;
2864 if(symbol == sym_align) {
2867 if(token.type != T_INTEGER)
2869 if(check_elignment_value(token.v.intvalue)) {
2870 if(specifiers->alignment != 0)
2871 warningf(HERE, "align used more than once");
2872 specifiers->alignment = (unsigned char)token.v.intvalue;
2876 } else if(symbol == sym_allocate) {
2879 if(token.type != T_IDENTIFIER)
2881 (void)token.v.symbol;
2883 } else if(symbol == sym_dllimport) {
2885 DET_MOD(dllimport, DM_DLLIMPORT);
2886 } else if(symbol == sym_dllexport) {
2888 DET_MOD(dllexport, DM_DLLEXPORT);
2889 } else if(symbol == sym_thread) {
2891 DET_MOD(thread, DM_THREAD);
2892 } else if(symbol == sym_naked) {
2894 DET_MOD(naked, DM_NAKED);
2895 } else if(symbol == sym_noinline) {
2897 DET_MOD(noinline, DM_NOINLINE);
2898 } else if(symbol == sym_noreturn) {
2900 DET_MOD(noreturn, DM_NORETURN);
2901 } else if(symbol == sym_nothrow) {
2903 DET_MOD(nothrow, DM_NOTHROW);
2904 } else if(symbol == sym_novtable) {
2906 DET_MOD(novtable, DM_NOVTABLE);
2907 } else if(symbol == sym_property) {
2911 bool is_get = false;
2912 if(token.type != T_IDENTIFIER)
2914 if(token.v.symbol == sym_get) {
2916 } else if(token.v.symbol == sym_put) {
2918 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2923 if(token.type != T_IDENTIFIER)
2926 if(specifiers->get_property_sym != NULL) {
2927 errorf(HERE, "get property name already specified");
2929 specifiers->get_property_sym = token.v.symbol;
2932 if(specifiers->put_property_sym != NULL) {
2933 errorf(HERE, "put property name already specified");
2935 specifiers->put_property_sym = token.v.symbol;
2939 if(token.type == ',') {
2946 } else if(symbol == sym_selectany) {
2948 DET_MOD(selectany, DM_SELECTANY);
2949 } else if(symbol == sym_uuid) {
2952 if(token.type != T_STRING_LITERAL)
2956 } else if(symbol == sym_deprecated) {
2958 if(specifiers->deprecated != 0)
2959 warningf(HERE, "deprecated used more than once");
2960 specifiers->deprecated = 1;
2961 if(token.type == '(') {
2963 if(token.type == T_STRING_LITERAL) {
2964 specifiers->deprecated_string = token.v.string.begin;
2967 errorf(HERE, "string literal expected");
2971 } else if(symbol == sym_noalias) {
2973 DET_MOD(noalias, DM_NOALIAS);
2975 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2977 if(token.type == '(')
2981 if (token.type == ',')
2988 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2990 type_t *type = NULL;
2991 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2992 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
2993 unsigned type_specifiers = 0;
2996 specifiers->source_position = token.source_position;
2999 switch(token.type) {
3002 #define MATCH_STORAGE_CLASS(token, class) \
3004 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3005 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3007 specifiers->declared_storage_class = class; \
3011 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3012 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3013 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3014 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3015 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3020 add_anchor_token(')');
3021 parse_microsoft_extended_decl_modifier(specifiers);
3022 rem_anchor_token(')');
3027 switch (specifiers->declared_storage_class) {
3028 case STORAGE_CLASS_NONE:
3029 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3032 case STORAGE_CLASS_EXTERN:
3033 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3036 case STORAGE_CLASS_STATIC:
3037 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3041 errorf(HERE, "multiple storage classes in declaration specifiers");
3047 /* type qualifiers */
3048 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3050 qualifiers |= qualifier; \
3054 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3055 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3056 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3057 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3058 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3059 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3060 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3061 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3063 case T___extension__:
3068 /* type specifiers */
3069 #define MATCH_SPECIFIER(token, specifier, name) \
3072 if(type_specifiers & specifier) { \
3073 errorf(HERE, "multiple " name " type specifiers given"); \
3075 type_specifiers |= specifier; \
3079 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3080 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3081 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3082 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3083 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3084 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3085 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3086 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3087 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3088 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3089 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3090 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3091 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3092 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3093 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3094 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3096 case T__forceinline:
3097 /* only in microsoft mode */
3098 specifiers->modifiers |= DM_FORCEINLINE;
3102 specifiers->is_inline = true;
3107 if(type_specifiers & SPECIFIER_LONG_LONG) {
3108 errorf(HERE, "multiple type specifiers given");
3109 } else if(type_specifiers & SPECIFIER_LONG) {
3110 type_specifiers |= SPECIFIER_LONG_LONG;
3112 type_specifiers |= SPECIFIER_LONG;
3117 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3119 type->compound.declaration = parse_compound_type_specifier(true);
3123 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3124 type->compound.declaration = parse_compound_type_specifier(false);
3125 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3126 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3130 type = parse_enum_specifier();
3133 type = parse_typeof();
3135 case T___builtin_va_list:
3136 type = duplicate_type(type_valist);
3140 case T___attribute__:
3141 specifiers->modifiers
3142 |= parse_attributes(&specifiers->gnu_attributes);
3143 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3144 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3147 case T_IDENTIFIER: {
3148 /* only parse identifier if we haven't found a type yet */
3149 if(type != NULL || type_specifiers != 0)
3150 goto finish_specifiers;
3152 type_t *typedef_type = get_typedef_type(token.v.symbol);
3154 if(typedef_type == NULL)
3155 goto finish_specifiers;
3158 type = typedef_type;
3162 /* function specifier */
3164 goto finish_specifiers;
3171 atomic_type_kind_t atomic_type;
3173 /* match valid basic types */
3174 switch(type_specifiers) {
3175 case SPECIFIER_VOID:
3176 atomic_type = ATOMIC_TYPE_VOID;
3178 case SPECIFIER_CHAR:
3179 atomic_type = ATOMIC_TYPE_CHAR;
3181 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3182 atomic_type = ATOMIC_TYPE_SCHAR;
3184 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3185 atomic_type = ATOMIC_TYPE_UCHAR;
3187 case SPECIFIER_SHORT:
3188 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3189 case SPECIFIER_SHORT | SPECIFIER_INT:
3190 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3191 atomic_type = ATOMIC_TYPE_SHORT;
3193 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3194 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3195 atomic_type = ATOMIC_TYPE_USHORT;
3198 case SPECIFIER_SIGNED:
3199 case SPECIFIER_SIGNED | SPECIFIER_INT:
3200 atomic_type = ATOMIC_TYPE_INT;
3202 case SPECIFIER_UNSIGNED:
3203 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3204 atomic_type = ATOMIC_TYPE_UINT;
3206 case SPECIFIER_LONG:
3207 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3208 case SPECIFIER_LONG | SPECIFIER_INT:
3209 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3210 atomic_type = ATOMIC_TYPE_LONG;
3212 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3213 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3214 atomic_type = ATOMIC_TYPE_ULONG;
3216 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3217 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3218 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3219 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3221 atomic_type = ATOMIC_TYPE_LONGLONG;
3223 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3224 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3226 atomic_type = ATOMIC_TYPE_ULONGLONG;
3229 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3230 atomic_type = unsigned_int8_type_kind;
3233 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3234 atomic_type = unsigned_int16_type_kind;
3237 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3238 atomic_type = unsigned_int32_type_kind;
3241 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3242 atomic_type = unsigned_int64_type_kind;
3245 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3246 atomic_type = unsigned_int128_type_kind;
3249 case SPECIFIER_INT8:
3250 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3251 atomic_type = int8_type_kind;
3254 case SPECIFIER_INT16:
3255 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3256 atomic_type = int16_type_kind;
3259 case SPECIFIER_INT32:
3260 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3261 atomic_type = int32_type_kind;
3264 case SPECIFIER_INT64:
3265 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3266 atomic_type = int64_type_kind;
3269 case SPECIFIER_INT128:
3270 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3271 atomic_type = int128_type_kind;
3274 case SPECIFIER_FLOAT:
3275 atomic_type = ATOMIC_TYPE_FLOAT;
3277 case SPECIFIER_DOUBLE:
3278 atomic_type = ATOMIC_TYPE_DOUBLE;
3280 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3281 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3283 case SPECIFIER_BOOL:
3284 atomic_type = ATOMIC_TYPE_BOOL;
3286 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3287 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3288 atomic_type = ATOMIC_TYPE_FLOAT;
3290 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3291 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3292 atomic_type = ATOMIC_TYPE_DOUBLE;
3294 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3295 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3296 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3299 /* invalid specifier combination, give an error message */
3300 if(type_specifiers == 0) {
3301 if (! strict_mode) {
3302 if (warning.implicit_int) {
3303 warningf(HERE, "no type specifiers in declaration, using 'int'");
3305 atomic_type = ATOMIC_TYPE_INT;
3308 errorf(HERE, "no type specifiers given in declaration");
3310 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3311 (type_specifiers & SPECIFIER_UNSIGNED)) {
3312 errorf(HERE, "signed and unsigned specifiers gives");
3313 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3314 errorf(HERE, "only integer types can be signed or unsigned");
3316 errorf(HERE, "multiple datatypes in declaration");
3318 atomic_type = ATOMIC_TYPE_INVALID;
3321 if(type_specifiers & SPECIFIER_COMPLEX &&
3322 atomic_type != ATOMIC_TYPE_INVALID) {
3323 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3324 type->complex.akind = atomic_type;
3325 } else if(type_specifiers & SPECIFIER_IMAGINARY &&
3326 atomic_type != ATOMIC_TYPE_INVALID) {
3327 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3328 type->imaginary.akind = atomic_type;
3330 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3331 type->atomic.akind = atomic_type;
3335 if(type_specifiers != 0) {
3336 errorf(HERE, "multiple datatypes in declaration");
3340 /* FIXME: check type qualifiers here */
3342 type->base.qualifiers = qualifiers;
3343 type->base.modifiers = modifiers;
3345 type_t *result = typehash_insert(type);
3346 if(newtype && result != type) {
3350 specifiers->type = result;
3355 static type_qualifiers_t parse_type_qualifiers(void)
3357 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3360 switch(token.type) {
3361 /* type qualifiers */
3362 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3363 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3364 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3365 /* microsoft extended type modifiers */
3366 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3367 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3368 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3369 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3370 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3378 static declaration_t *parse_identifier_list(void)
3380 declaration_t *declarations = NULL;
3381 declaration_t *last_declaration = NULL;
3383 declaration_t *const declaration = allocate_declaration_zero();
3384 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3385 declaration->source_position = token.source_position;
3386 declaration->symbol = token.v.symbol;
3389 if(last_declaration != NULL) {
3390 last_declaration->next = declaration;
3392 declarations = declaration;
3394 last_declaration = declaration;
3396 if (token.type != ',') {
3400 } while(token.type == T_IDENTIFIER);
3402 return declarations;
3405 static void semantic_parameter(declaration_t *declaration)
3407 /* TODO: improve error messages */
3409 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3410 errorf(HERE, "typedef not allowed in parameter list");
3411 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3412 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3413 errorf(HERE, "parameter may only have none or register storage class");
3416 type_t *const orig_type = declaration->type;
3417 type_t * type = skip_typeref(orig_type);
3419 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3420 * into a pointer. § 6.7.5.3 (7) */
3421 if (is_type_array(type)) {
3422 type_t *const element_type = type->array.element_type;
3424 type = make_pointer_type(element_type, type->base.qualifiers);
3426 declaration->type = type;
3429 if(is_type_incomplete(type)) {
3430 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3431 orig_type, declaration->symbol);
3435 static declaration_t *parse_parameter(void)
3437 declaration_specifiers_t specifiers;
3438 memset(&specifiers, 0, sizeof(specifiers));
3440 parse_declaration_specifiers(&specifiers);
3442 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3447 static declaration_t *parse_parameters(function_type_t *type)
3449 declaration_t *declarations = NULL;
3452 add_anchor_token(')');
3453 int saved_comma_state = save_and_reset_anchor_state(',');
3455 if(token.type == T_IDENTIFIER) {
3456 symbol_t *symbol = token.v.symbol;
3457 if(!is_typedef_symbol(symbol)) {
3458 type->kr_style_parameters = true;
3459 declarations = parse_identifier_list();
3460 goto parameters_finished;
3464 if(token.type == ')') {
3465 type->unspecified_parameters = 1;
3466 goto parameters_finished;
3469 declaration_t *declaration;
3470 declaration_t *last_declaration = NULL;
3471 function_parameter_t *parameter;
3472 function_parameter_t *last_parameter = NULL;
3475 switch(token.type) {
3479 goto parameters_finished;
3482 case T___extension__:
3484 declaration = parse_parameter();
3486 /* func(void) is not a parameter */
3487 if (last_parameter == NULL
3488 && token.type == ')'
3489 && declaration->symbol == NULL
3490 && skip_typeref(declaration->type) == type_void) {
3491 goto parameters_finished;
3493 semantic_parameter(declaration);
3495 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3496 memset(parameter, 0, sizeof(parameter[0]));
3497 parameter->type = declaration->type;
3499 if(last_parameter != NULL) {
3500 last_declaration->next = declaration;
3501 last_parameter->next = parameter;
3503 type->parameters = parameter;
3504 declarations = declaration;
3506 last_parameter = parameter;
3507 last_declaration = declaration;
3511 goto parameters_finished;
3513 if (token.type != ',') {
3514 goto parameters_finished;
3520 parameters_finished:
3521 rem_anchor_token(')');
3524 restore_anchor_state(',', saved_comma_state);
3525 return declarations;
3528 restore_anchor_state(',', saved_comma_state);
3537 } construct_type_kind_t;
3539 typedef struct construct_type_t construct_type_t;
3540 struct construct_type_t {
3541 construct_type_kind_t kind;
3542 construct_type_t *next;
3545 typedef struct parsed_pointer_t parsed_pointer_t;
3546 struct parsed_pointer_t {
3547 construct_type_t construct_type;
3548 type_qualifiers_t type_qualifiers;
3551 typedef struct construct_function_type_t construct_function_type_t;
3552 struct construct_function_type_t {
3553 construct_type_t construct_type;
3554 type_t *function_type;
3557 typedef struct parsed_array_t parsed_array_t;
3558 struct parsed_array_t {
3559 construct_type_t construct_type;
3560 type_qualifiers_t type_qualifiers;
3566 typedef struct construct_base_type_t construct_base_type_t;
3567 struct construct_base_type_t {
3568 construct_type_t construct_type;
3572 static construct_type_t *parse_pointer_declarator(void)
3576 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3577 memset(pointer, 0, sizeof(pointer[0]));
3578 pointer->construct_type.kind = CONSTRUCT_POINTER;
3579 pointer->type_qualifiers = parse_type_qualifiers();
3581 return (construct_type_t*) pointer;
3584 static construct_type_t *parse_array_declarator(void)
3587 add_anchor_token(']');
3589 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3590 memset(array, 0, sizeof(array[0]));
3591 array->construct_type.kind = CONSTRUCT_ARRAY;
3593 if(token.type == T_static) {
3594 array->is_static = true;
3598 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3599 if(type_qualifiers != 0) {
3600 if(token.type == T_static) {
3601 array->is_static = true;
3605 array->type_qualifiers = type_qualifiers;
3607 if(token.type == '*' && look_ahead(1)->type == ']') {
3608 array->is_variable = true;
3610 } else if(token.type != ']') {
3611 array->size = parse_assignment_expression();
3614 rem_anchor_token(']');
3617 return (construct_type_t*) array;
3622 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3625 if(declaration != NULL) {
3626 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3628 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3631 declaration_t *parameters = parse_parameters(&type->function);
3632 if(declaration != NULL) {
3633 declaration->scope.declarations = parameters;
3636 construct_function_type_t *construct_function_type =
3637 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3638 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3639 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3640 construct_function_type->function_type = type;
3642 return (construct_type_t*) construct_function_type;
3645 static void fix_declaration_type(declaration_t *declaration)
3647 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3648 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3650 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3651 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3653 if (declaration->type->base.modifiers == type_modifiers)
3656 type_t *copy = duplicate_type(declaration->type);
3657 copy->base.modifiers = type_modifiers;
3659 type_t *result = typehash_insert(copy);
3660 if (result != copy) {
3661 obstack_free(type_obst, copy);
3664 declaration->type = result;
3667 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3668 bool may_be_abstract)
3670 /* construct a single linked list of construct_type_t's which describe
3671 * how to construct the final declarator type */
3672 construct_type_t *first = NULL;
3673 construct_type_t *last = NULL;
3674 gnu_attribute_t *attributes = NULL;
3676 decl_modifiers_t modifiers = parse_attributes(&attributes);
3679 while(token.type == '*') {
3680 construct_type_t *type = parse_pointer_declarator();
3690 /* TODO: find out if this is correct */
3691 modifiers |= parse_attributes(&attributes);
3694 construct_type_t *inner_types = NULL;
3696 switch(token.type) {
3698 if(declaration == NULL) {
3699 errorf(HERE, "no identifier expected in typename");
3701 declaration->symbol = token.v.symbol;
3702 declaration->source_position = token.source_position;
3708 add_anchor_token(')');
3709 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3710 rem_anchor_token(')');
3716 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3717 /* avoid a loop in the outermost scope, because eat_statement doesn't
3719 if(token.type == '}' && current_function == NULL) {
3727 construct_type_t *p = last;
3730 construct_type_t *type;
3731 switch(token.type) {
3733 type = parse_function_declarator(declaration);
3736 type = parse_array_declarator();
3739 goto declarator_finished;
3742 /* insert in the middle of the list (behind p) */
3744 type->next = p->next;
3755 declarator_finished:
3756 modifiers |= parse_attributes(&attributes);
3757 if (declaration != NULL) {
3758 declaration->modifiers |= modifiers;
3761 /* append inner_types at the end of the list, we don't to set last anymore
3762 * as it's not needed anymore */
3764 assert(first == NULL);
3765 first = inner_types;
3767 last->next = inner_types;
3775 static type_t *construct_declarator_type(construct_type_t *construct_list,
3778 construct_type_t *iter = construct_list;
3779 for( ; iter != NULL; iter = iter->next) {
3780 switch(iter->kind) {
3781 case CONSTRUCT_INVALID:
3782 internal_errorf(HERE, "invalid type construction found");
3783 case CONSTRUCT_FUNCTION: {
3784 construct_function_type_t *construct_function_type
3785 = (construct_function_type_t*) iter;
3787 type_t *function_type = construct_function_type->function_type;
3789 function_type->function.return_type = type;
3791 type_t *skipped_return_type = skip_typeref(type);
3792 if (is_type_function(skipped_return_type)) {
3793 errorf(HERE, "function returning function is not allowed");
3794 type = type_error_type;
3795 } else if (is_type_array(skipped_return_type)) {
3796 errorf(HERE, "function returning array is not allowed");
3797 type = type_error_type;
3799 type = function_type;
3804 case CONSTRUCT_POINTER: {
3805 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3806 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3807 pointer_type->pointer.points_to = type;
3808 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3810 type = pointer_type;
3814 case CONSTRUCT_ARRAY: {
3815 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3816 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3818 expression_t *size_expression = parsed_array->size;
3819 if(size_expression != NULL) {
3821 = create_implicit_cast(size_expression, type_size_t);
3824 array_type->base.qualifiers = parsed_array->type_qualifiers;
3825 array_type->array.element_type = type;
3826 array_type->array.is_static = parsed_array->is_static;
3827 array_type->array.is_variable = parsed_array->is_variable;
3828 array_type->array.size_expression = size_expression;
3830 if(size_expression != NULL) {
3831 if(is_constant_expression(size_expression)) {
3832 array_type->array.size_constant = true;
3833 array_type->array.size
3834 = fold_constant(size_expression);
3836 array_type->array.is_vla = true;
3840 type_t *skipped_type = skip_typeref(type);
3841 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3842 errorf(HERE, "array of void is not allowed");
3843 type = type_error_type;
3851 type_t *hashed_type = typehash_insert(type);
3852 if(hashed_type != type) {
3853 /* the function type was constructed earlier freeing it here will
3854 * destroy other types... */
3855 if(iter->kind != CONSTRUCT_FUNCTION) {
3865 static declaration_t *parse_declarator(
3866 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3868 declaration_t *const declaration = allocate_declaration_zero();
3869 declaration->declared_storage_class = specifiers->declared_storage_class;
3870 declaration->modifiers = specifiers->modifiers;
3871 declaration->deprecated = specifiers->deprecated;
3872 declaration->deprecated_string = specifiers->deprecated_string;
3873 declaration->get_property_sym = specifiers->get_property_sym;
3874 declaration->put_property_sym = specifiers->put_property_sym;
3875 declaration->is_inline = specifiers->is_inline;
3877 declaration->storage_class = specifiers->declared_storage_class;
3878 if(declaration->storage_class == STORAGE_CLASS_NONE
3879 && scope != global_scope) {
3880 declaration->storage_class = STORAGE_CLASS_AUTO;
3883 if(specifiers->alignment != 0) {
3884 /* TODO: add checks here */
3885 declaration->alignment = specifiers->alignment;
3888 construct_type_t *construct_type
3889 = parse_inner_declarator(declaration, may_be_abstract);
3890 type_t *const type = specifiers->type;
3891 declaration->type = construct_declarator_type(construct_type, type);
3893 fix_declaration_type(declaration);
3895 if(construct_type != NULL) {
3896 obstack_free(&temp_obst, construct_type);
3902 static type_t *parse_abstract_declarator(type_t *base_type)
3904 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3906 type_t *result = construct_declarator_type(construct_type, base_type);
3907 if(construct_type != NULL) {
3908 obstack_free(&temp_obst, construct_type);
3914 static declaration_t *append_declaration(declaration_t* const declaration)
3916 if (last_declaration != NULL) {
3917 last_declaration->next = declaration;
3919 scope->declarations = declaration;
3921 last_declaration = declaration;
3926 * Check if the declaration of main is suspicious. main should be a
3927 * function with external linkage, returning int, taking either zero
3928 * arguments, two, or three arguments of appropriate types, ie.
3930 * int main([ int argc, char **argv [, char **env ] ]).
3932 * @param decl the declaration to check
3933 * @param type the function type of the declaration
3935 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3937 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3938 warningf(&decl->source_position,
3939 "'main' is normally a non-static function");
3941 if (skip_typeref(func_type->return_type) != type_int) {
3942 warningf(&decl->source_position,
3943 "return type of 'main' should be 'int', but is '%T'",
3944 func_type->return_type);
3946 const function_parameter_t *parm = func_type->parameters;
3948 type_t *const first_type = parm->type;
3949 if (!types_compatible(skip_typeref(first_type), type_int)) {
3950 warningf(&decl->source_position,
3951 "first argument of 'main' should be 'int', but is '%T'", first_type);
3955 type_t *const second_type = parm->type;
3956 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3957 warningf(&decl->source_position,
3958 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3962 type_t *const third_type = parm->type;
3963 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3964 warningf(&decl->source_position,
3965 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3969 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3973 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3979 * Check if a symbol is the equal to "main".
3981 static bool is_sym_main(const symbol_t *const sym)
3983 return strcmp(sym->string, "main") == 0;
3986 static declaration_t *internal_record_declaration(
3987 declaration_t *const declaration,
3988 const bool is_function_definition)
3990 const symbol_t *const symbol = declaration->symbol;
3991 const namespace_t namespc = (namespace_t)declaration->namespc;
3993 assert(declaration->symbol != NULL);
3994 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3996 type_t *const orig_type = declaration->type;
3997 type_t *const type = skip_typeref(orig_type);
3998 if (is_type_function(type) &&
3999 type->function.unspecified_parameters &&
4000 warning.strict_prototypes &&
4001 previous_declaration == NULL) {
4002 warningf(&declaration->source_position,
4003 "function declaration '%#T' is not a prototype",
4004 orig_type, declaration->symbol);
4007 if (is_function_definition && warning.main && is_sym_main(symbol)) {
4008 check_type_of_main(declaration, &type->function);
4011 assert(declaration != previous_declaration);
4012 if (previous_declaration != NULL
4013 && previous_declaration->parent_scope == scope) {
4014 /* can happen for K&R style declarations */
4015 if (previous_declaration->type == NULL) {
4016 previous_declaration->type = declaration->type;
4019 const type_t *prev_type = skip_typeref(previous_declaration->type);
4020 if (!types_compatible(type, prev_type)) {
4021 errorf(&declaration->source_position,
4022 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4023 orig_type, symbol, previous_declaration->type, symbol,
4024 &previous_declaration->source_position);
4026 unsigned old_storage_class = previous_declaration->storage_class;
4027 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4028 errorf(&declaration->source_position,
4029 "redeclaration of enum entry '%Y' (declared %P)",
4030 symbol, &previous_declaration->source_position);
4031 return previous_declaration;
4034 unsigned new_storage_class = declaration->storage_class;
4036 if (is_type_incomplete(prev_type)) {
4037 previous_declaration->type = type;
4041 /* pretend no storage class means extern for function
4042 * declarations (except if the previous declaration is neither
4043 * none nor extern) */
4044 if (is_type_function(type)) {
4045 if (prev_type->function.unspecified_parameters) {
4046 previous_declaration->type = type;
4050 switch (old_storage_class) {
4051 case STORAGE_CLASS_NONE:
4052 old_storage_class = STORAGE_CLASS_EXTERN;
4055 case STORAGE_CLASS_EXTERN:
4056 if (is_function_definition) {
4057 if (warning.missing_prototypes &&
4058 prev_type->function.unspecified_parameters &&
4059 !is_sym_main(symbol)) {
4060 warningf(&declaration->source_position,
4061 "no previous prototype for '%#T'",
4064 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4065 new_storage_class = STORAGE_CLASS_EXTERN;
4074 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4075 new_storage_class == STORAGE_CLASS_EXTERN) {
4076 warn_redundant_declaration:
4077 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4078 warningf(&declaration->source_position,
4079 "redundant declaration for '%Y' (declared %P)",
4080 symbol, &previous_declaration->source_position);
4082 } else if (current_function == NULL) {
4083 if (old_storage_class != STORAGE_CLASS_STATIC &&
4084 new_storage_class == STORAGE_CLASS_STATIC) {
4085 errorf(&declaration->source_position,
4086 "static declaration of '%Y' follows non-static declaration (declared %P)",
4087 symbol, &previous_declaration->source_position);
4088 } else if (old_storage_class != STORAGE_CLASS_EXTERN
4089 && !is_function_definition) {
4090 goto warn_redundant_declaration;
4091 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4092 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4093 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4095 } else if (old_storage_class == new_storage_class) {
4096 errorf(&declaration->source_position,
4097 "redeclaration of '%Y' (declared %P)",
4098 symbol, &previous_declaration->source_position);
4100 errorf(&declaration->source_position,
4101 "redeclaration of '%Y' with different linkage (declared %P)",
4102 symbol, &previous_declaration->source_position);
4106 if (declaration->is_inline)
4107 previous_declaration->is_inline = true;
4108 return previous_declaration;
4109 } else if (is_function_definition) {
4110 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4111 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4112 warningf(&declaration->source_position,
4113 "no previous prototype for '%#T'", orig_type, symbol);
4114 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4115 warningf(&declaration->source_position,
4116 "no previous declaration for '%#T'", orig_type,
4120 } else if (warning.missing_declarations &&
4121 scope == global_scope &&
4122 !is_type_function(type) && (
4123 declaration->storage_class == STORAGE_CLASS_NONE ||
4124 declaration->storage_class == STORAGE_CLASS_THREAD
4126 warningf(&declaration->source_position,
4127 "no previous declaration for '%#T'", orig_type, symbol);
4130 assert(declaration->parent_scope == NULL);
4131 assert(scope != NULL);
4133 declaration->parent_scope = scope;
4135 environment_push(declaration);
4136 return append_declaration(declaration);
4139 static declaration_t *record_declaration(declaration_t *declaration)
4141 return internal_record_declaration(declaration, false);
4144 static declaration_t *record_function_definition(declaration_t *declaration)
4146 return internal_record_declaration(declaration, true);
4149 static void parser_error_multiple_definition(declaration_t *declaration,
4150 const source_position_t *source_position)
4152 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4153 declaration->symbol, &declaration->source_position);
4156 static bool is_declaration_specifier(const token_t *token,
4157 bool only_specifiers_qualifiers)
4159 switch(token->type) {
4164 return is_typedef_symbol(token->v.symbol);
4166 case T___extension__:
4168 return !only_specifiers_qualifiers;
4175 static void parse_init_declarator_rest(declaration_t *declaration)
4179 type_t *orig_type = declaration->type;
4180 type_t *type = skip_typeref(orig_type);
4182 if(declaration->init.initializer != NULL) {
4183 parser_error_multiple_definition(declaration, HERE);
4186 bool must_be_constant = false;
4187 if(declaration->storage_class == STORAGE_CLASS_STATIC
4188 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4189 || declaration->parent_scope == global_scope) {
4190 must_be_constant = true;
4193 parse_initializer_env_t env;
4194 env.type = orig_type;
4195 env.must_be_constant = must_be_constant;
4196 env.declaration = declaration;
4198 initializer_t *initializer = parse_initializer(&env);
4200 if(env.type != orig_type) {
4201 orig_type = env.type;
4202 type = skip_typeref(orig_type);
4203 declaration->type = env.type;
4206 if(is_type_function(type)) {
4207 errorf(&declaration->source_position,
4208 "initializers not allowed for function types at declator '%Y' (type '%T')",
4209 declaration->symbol, orig_type);
4211 declaration->init.initializer = initializer;
4215 /* parse rest of a declaration without any declarator */
4216 static void parse_anonymous_declaration_rest(
4217 const declaration_specifiers_t *specifiers,
4218 parsed_declaration_func finished_declaration)
4222 declaration_t *const declaration = allocate_declaration_zero();
4223 declaration->type = specifiers->type;
4224 declaration->declared_storage_class = specifiers->declared_storage_class;
4225 declaration->source_position = specifiers->source_position;
4226 declaration->modifiers = specifiers->modifiers;
4228 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4229 warningf(&declaration->source_position,
4230 "useless storage class in empty declaration");
4232 declaration->storage_class = STORAGE_CLASS_NONE;
4234 type_t *type = declaration->type;
4235 switch (type->kind) {
4236 case TYPE_COMPOUND_STRUCT:
4237 case TYPE_COMPOUND_UNION: {
4238 if (type->compound.declaration->symbol == NULL) {
4239 warningf(&declaration->source_position,
4240 "unnamed struct/union that defines no instances");
4249 warningf(&declaration->source_position, "empty declaration");
4253 finished_declaration(declaration);
4256 static void parse_declaration_rest(declaration_t *ndeclaration,
4257 const declaration_specifiers_t *specifiers,
4258 parsed_declaration_func finished_declaration)
4260 add_anchor_token(';');
4261 add_anchor_token('=');
4262 add_anchor_token(',');
4264 declaration_t *declaration = finished_declaration(ndeclaration);
4266 type_t *orig_type = declaration->type;
4267 type_t *type = skip_typeref(orig_type);
4269 if (type->kind != TYPE_FUNCTION &&
4270 declaration->is_inline &&
4271 is_type_valid(type)) {
4272 warningf(&declaration->source_position,
4273 "variable '%Y' declared 'inline'\n", declaration->symbol);
4276 if(token.type == '=') {
4277 parse_init_declarator_rest(declaration);
4280 if(token.type != ',')
4284 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4289 rem_anchor_token(';');
4290 rem_anchor_token('=');
4291 rem_anchor_token(',');
4294 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4296 symbol_t *symbol = declaration->symbol;
4297 if(symbol == NULL) {
4298 errorf(HERE, "anonymous declaration not valid as function parameter");
4301 namespace_t namespc = (namespace_t) declaration->namespc;
4302 if(namespc != NAMESPACE_NORMAL) {
4303 return record_declaration(declaration);
4306 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4307 if(previous_declaration == NULL ||
4308 previous_declaration->parent_scope != scope) {
4309 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4314 if(previous_declaration->type == NULL) {
4315 previous_declaration->type = declaration->type;
4316 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4317 previous_declaration->storage_class = declaration->storage_class;
4318 previous_declaration->parent_scope = scope;
4319 return previous_declaration;
4321 return record_declaration(declaration);
4325 static void parse_declaration(parsed_declaration_func finished_declaration)
4327 declaration_specifiers_t specifiers;
4328 memset(&specifiers, 0, sizeof(specifiers));
4329 parse_declaration_specifiers(&specifiers);
4331 if(token.type == ';') {
4332 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4334 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4335 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4339 static type_t *get_default_promoted_type(type_t *orig_type)
4341 type_t *result = orig_type;
4343 type_t *type = skip_typeref(orig_type);
4344 if(is_type_integer(type)) {
4345 result = promote_integer(type);
4346 } else if(type == type_float) {
4347 result = type_double;
4353 static void parse_kr_declaration_list(declaration_t *declaration)
4355 type_t *type = skip_typeref(declaration->type);
4356 if (!is_type_function(type))
4359 if (!type->function.kr_style_parameters)
4362 /* push function parameters */
4363 int top = environment_top();
4364 scope_t *last_scope = scope;
4365 set_scope(&declaration->scope);
4367 declaration_t *parameter = declaration->scope.declarations;
4368 for ( ; parameter != NULL; parameter = parameter->next) {
4369 assert(parameter->parent_scope == NULL);
4370 parameter->parent_scope = scope;
4371 environment_push(parameter);
4374 /* parse declaration list */
4375 while (is_declaration_specifier(&token, false)) {
4376 parse_declaration(finished_kr_declaration);
4379 /* pop function parameters */
4380 assert(scope == &declaration->scope);
4381 set_scope(last_scope);
4382 environment_pop_to(top);
4384 /* update function type */
4385 type_t *new_type = duplicate_type(type);
4387 function_parameter_t *parameters = NULL;
4388 function_parameter_t *last_parameter = NULL;
4390 declaration_t *parameter_declaration = declaration->scope.declarations;
4391 for( ; parameter_declaration != NULL;
4392 parameter_declaration = parameter_declaration->next) {
4393 type_t *parameter_type = parameter_declaration->type;
4394 if(parameter_type == NULL) {
4396 errorf(HERE, "no type specified for function parameter '%Y'",
4397 parameter_declaration->symbol);
4399 if (warning.implicit_int) {
4400 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4401 parameter_declaration->symbol);
4403 parameter_type = type_int;
4404 parameter_declaration->type = parameter_type;
4408 semantic_parameter(parameter_declaration);
4409 parameter_type = parameter_declaration->type;
4412 * we need the default promoted types for the function type
4414 parameter_type = get_default_promoted_type(parameter_type);
4416 function_parameter_t *function_parameter
4417 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4418 memset(function_parameter, 0, sizeof(function_parameter[0]));
4420 function_parameter->type = parameter_type;
4421 if(last_parameter != NULL) {
4422 last_parameter->next = function_parameter;
4424 parameters = function_parameter;
4426 last_parameter = function_parameter;
4429 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4431 new_type->function.parameters = parameters;
4432 new_type->function.unspecified_parameters = true;
4434 type = typehash_insert(new_type);
4435 if(type != new_type) {
4436 obstack_free(type_obst, new_type);
4439 declaration->type = type;
4442 static bool first_err = true;
4445 * When called with first_err set, prints the name of the current function,
4448 static void print_in_function(void) {
4451 diagnosticf("%s: In function '%Y':\n",
4452 current_function->source_position.input_name,
4453 current_function->symbol);
4458 * Check if all labels are defined in the current function.
4459 * Check if all labels are used in the current function.
4461 static void check_labels(void)
4463 for (const goto_statement_t *goto_statement = goto_first;
4464 goto_statement != NULL;
4465 goto_statement = goto_statement->next) {
4466 declaration_t *label = goto_statement->label;
4469 if (label->source_position.input_name == NULL) {
4470 print_in_function();
4471 errorf(&goto_statement->base.source_position,
4472 "label '%Y' used but not defined", label->symbol);
4475 goto_first = goto_last = NULL;
4477 if (warning.unused_label) {
4478 for (const label_statement_t *label_statement = label_first;
4479 label_statement != NULL;
4480 label_statement = label_statement->next) {
4481 const declaration_t *label = label_statement->label;
4483 if (! label->used) {
4484 print_in_function();
4485 warningf(&label_statement->base.source_position,
4486 "label '%Y' defined but not used", label->symbol);
4490 label_first = label_last = NULL;
4494 * Check declarations of current_function for unused entities.
4496 static void check_declarations(void)
4498 if (warning.unused_parameter) {
4499 const scope_t *scope = ¤t_function->scope;
4501 const declaration_t *parameter = scope->declarations;
4502 for (; parameter != NULL; parameter = parameter->next) {
4503 if (! parameter->used) {
4504 print_in_function();
4505 warningf(¶meter->source_position,
4506 "unused parameter '%Y'", parameter->symbol);
4510 if (warning.unused_variable) {
4514 static void parse_external_declaration(void)
4516 /* function-definitions and declarations both start with declaration
4518 declaration_specifiers_t specifiers;
4519 memset(&specifiers, 0, sizeof(specifiers));
4521 add_anchor_token(';');
4522 parse_declaration_specifiers(&specifiers);
4523 rem_anchor_token(';');
4525 /* must be a declaration */
4526 if(token.type == ';') {
4527 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4531 add_anchor_token(',');
4532 add_anchor_token('=');
4533 rem_anchor_token(';');
4535 /* declarator is common to both function-definitions and declarations */
4536 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4538 rem_anchor_token(',');
4539 rem_anchor_token('=');
4540 rem_anchor_token(';');
4542 /* must be a declaration */
4543 if(token.type == ',' || token.type == '=' || token.type == ';') {
4544 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4548 /* must be a function definition */
4549 parse_kr_declaration_list(ndeclaration);
4551 if(token.type != '{') {
4552 parse_error_expected("while parsing function definition", '{', NULL);
4553 eat_until_matching_token(';');
4557 type_t *type = ndeclaration->type;
4559 /* note that we don't skip typerefs: the standard doesn't allow them here
4560 * (so we can't use is_type_function here) */
4561 if(type->kind != TYPE_FUNCTION) {
4562 if (is_type_valid(type)) {
4563 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4564 type, ndeclaration->symbol);
4570 /* § 6.7.5.3 (14) a function definition with () means no
4571 * parameters (and not unspecified parameters) */
4572 if(type->function.unspecified_parameters
4573 && type->function.parameters == NULL
4574 && !type->function.kr_style_parameters) {
4575 type_t *duplicate = duplicate_type(type);
4576 duplicate->function.unspecified_parameters = false;
4578 type = typehash_insert(duplicate);
4579 if(type != duplicate) {
4580 obstack_free(type_obst, duplicate);
4582 ndeclaration->type = type;
4585 declaration_t *const declaration = record_function_definition(ndeclaration);
4586 if(ndeclaration != declaration) {
4587 declaration->scope = ndeclaration->scope;
4589 type = skip_typeref(declaration->type);
4591 /* push function parameters and switch scope */
4592 int top = environment_top();
4593 scope_t *last_scope = scope;
4594 set_scope(&declaration->scope);
4596 declaration_t *parameter = declaration->scope.declarations;
4597 for( ; parameter != NULL; parameter = parameter->next) {
4598 if(parameter->parent_scope == &ndeclaration->scope) {
4599 parameter->parent_scope = scope;
4601 assert(parameter->parent_scope == NULL
4602 || parameter->parent_scope == scope);
4603 parameter->parent_scope = scope;
4604 if (parameter->symbol == NULL) {
4605 errorf(&ndeclaration->source_position, "parameter name omitted");
4608 environment_push(parameter);
4611 if(declaration->init.statement != NULL) {
4612 parser_error_multiple_definition(declaration, HERE);
4614 goto end_of_parse_external_declaration;
4616 /* parse function body */
4617 int label_stack_top = label_top();
4618 declaration_t *old_current_function = current_function;
4619 current_function = declaration;
4621 declaration->init.statement = parse_compound_statement(false);
4624 check_declarations();
4626 assert(current_function == declaration);
4627 current_function = old_current_function;
4628 label_pop_to(label_stack_top);
4631 end_of_parse_external_declaration:
4632 assert(scope == &declaration->scope);
4633 set_scope(last_scope);
4634 environment_pop_to(top);
4637 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4638 source_position_t *source_position)
4640 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4642 type->bitfield.base_type = base_type;
4643 type->bitfield.size = size;
4648 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4651 declaration_t *iter = compound_declaration->scope.declarations;
4652 for( ; iter != NULL; iter = iter->next) {
4653 if(iter->namespc != NAMESPACE_NORMAL)
4656 if(iter->symbol == NULL) {
4657 type_t *type = skip_typeref(iter->type);
4658 if(is_type_compound(type)) {
4659 declaration_t *result
4660 = find_compound_entry(type->compound.declaration, symbol);
4667 if(iter->symbol == symbol) {
4675 static void parse_compound_declarators(declaration_t *struct_declaration,
4676 const declaration_specifiers_t *specifiers)
4678 declaration_t *last_declaration = struct_declaration->scope.declarations;
4679 if(last_declaration != NULL) {
4680 while(last_declaration->next != NULL) {
4681 last_declaration = last_declaration->next;
4686 declaration_t *declaration;
4688 if(token.type == ':') {
4689 source_position_t source_position = *HERE;
4692 type_t *base_type = specifiers->type;
4693 expression_t *size = parse_constant_expression();
4695 if(!is_type_integer(skip_typeref(base_type))) {
4696 errorf(HERE, "bitfield base type '%T' is not an integer type",
4700 type_t *type = make_bitfield_type(base_type, size, &source_position);
4702 declaration = allocate_declaration_zero();
4703 declaration->namespc = NAMESPACE_NORMAL;
4704 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4705 declaration->storage_class = STORAGE_CLASS_NONE;
4706 declaration->source_position = source_position;
4707 declaration->modifiers = specifiers->modifiers;
4708 declaration->type = type;
4710 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4712 type_t *orig_type = declaration->type;
4713 type_t *type = skip_typeref(orig_type);
4715 if(token.type == ':') {
4716 source_position_t source_position = *HERE;
4718 expression_t *size = parse_constant_expression();
4720 if(!is_type_integer(type)) {
4721 errorf(HERE, "bitfield base type '%T' is not an "
4722 "integer type", orig_type);
4725 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4726 declaration->type = bitfield_type;
4728 /* TODO we ignore arrays for now... what is missing is a check
4729 * that they're at the end of the struct */
4730 if(is_type_incomplete(type) && !is_type_array(type)) {
4732 "compound member '%Y' has incomplete type '%T'",
4733 declaration->symbol, orig_type);
4734 } else if(is_type_function(type)) {
4735 errorf(HERE, "compound member '%Y' must not have function "
4736 "type '%T'", declaration->symbol, orig_type);
4741 /* make sure we don't define a symbol multiple times */
4742 symbol_t *symbol = declaration->symbol;
4743 if(symbol != NULL) {
4744 declaration_t *prev_decl
4745 = find_compound_entry(struct_declaration, symbol);
4747 if(prev_decl != NULL) {
4748 assert(prev_decl->symbol == symbol);
4749 errorf(&declaration->source_position,
4750 "multiple declarations of symbol '%Y' (declared %P)",
4751 symbol, &prev_decl->source_position);
4755 /* append declaration */
4756 if(last_declaration != NULL) {
4757 last_declaration->next = declaration;
4759 struct_declaration->scope.declarations = declaration;
4761 last_declaration = declaration;
4763 if(token.type != ',')
4773 static void parse_compound_type_entries(declaration_t *compound_declaration)
4776 add_anchor_token('}');
4778 while(token.type != '}' && token.type != T_EOF) {
4779 declaration_specifiers_t specifiers;
4780 memset(&specifiers, 0, sizeof(specifiers));
4781 parse_declaration_specifiers(&specifiers);
4783 parse_compound_declarators(compound_declaration, &specifiers);
4785 rem_anchor_token('}');
4787 if(token.type == T_EOF) {
4788 errorf(HERE, "EOF while parsing struct");
4793 static type_t *parse_typename(void)
4795 declaration_specifiers_t specifiers;
4796 memset(&specifiers, 0, sizeof(specifiers));
4797 parse_declaration_specifiers(&specifiers);
4798 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4799 /* TODO: improve error message, user does probably not know what a
4800 * storage class is...
4802 errorf(HERE, "typename may not have a storage class");
4805 type_t *result = parse_abstract_declarator(specifiers.type);
4813 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4814 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4815 expression_t *left);
4817 typedef struct expression_parser_function_t expression_parser_function_t;
4818 struct expression_parser_function_t {
4819 unsigned precedence;
4820 parse_expression_function parser;
4821 unsigned infix_precedence;
4822 parse_expression_infix_function infix_parser;
4825 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4828 * Prints an error message if an expression was expected but not read
4830 static expression_t *expected_expression_error(void)
4832 /* skip the error message if the error token was read */
4833 if (token.type != T_ERROR) {
4834 errorf(HERE, "expected expression, got token '%K'", &token);
4838 return create_invalid_expression();
4842 * Parse a string constant.
4844 static expression_t *parse_string_const(void)
4847 if (token.type == T_STRING_LITERAL) {
4848 string_t res = token.v.string;
4850 while (token.type == T_STRING_LITERAL) {
4851 res = concat_strings(&res, &token.v.string);
4854 if (token.type != T_WIDE_STRING_LITERAL) {
4855 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4856 /* note: that we use type_char_ptr here, which is already the
4857 * automatic converted type. revert_automatic_type_conversion
4858 * will construct the array type */
4859 cnst->base.type = type_char_ptr;
4860 cnst->string.value = res;
4864 wres = concat_string_wide_string(&res, &token.v.wide_string);
4866 wres = token.v.wide_string;
4871 switch (token.type) {
4872 case T_WIDE_STRING_LITERAL:
4873 wres = concat_wide_strings(&wres, &token.v.wide_string);
4876 case T_STRING_LITERAL:
4877 wres = concat_wide_string_string(&wres, &token.v.string);
4881 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4882 cnst->base.type = type_wchar_t_ptr;
4883 cnst->wide_string.value = wres;
4892 * Parse an integer constant.
4894 static expression_t *parse_int_const(void)
4896 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4897 cnst->base.source_position = *HERE;
4898 cnst->base.type = token.datatype;
4899 cnst->conste.v.int_value = token.v.intvalue;
4907 * Parse a character constant.
4909 static expression_t *parse_character_constant(void)
4911 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4913 cnst->base.source_position = *HERE;
4914 cnst->base.type = token.datatype;
4915 cnst->conste.v.character = token.v.string;
4917 if (cnst->conste.v.character.size != 1) {
4918 if (warning.multichar && (c_mode & _GNUC)) {
4920 warningf(HERE, "multi-character character constant");
4922 errorf(HERE, "more than 1 characters in character constant");
4931 * Parse a wide character constant.
4933 static expression_t *parse_wide_character_constant(void)
4935 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4937 cnst->base.source_position = *HERE;
4938 cnst->base.type = token.datatype;
4939 cnst->conste.v.wide_character = token.v.wide_string;
4941 if (cnst->conste.v.wide_character.size != 1) {
4942 if (warning.multichar && (c_mode & _GNUC)) {
4944 warningf(HERE, "multi-character character constant");
4946 errorf(HERE, "more than 1 characters in character constant");
4955 * Parse a float constant.
4957 static expression_t *parse_float_const(void)
4959 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4960 cnst->base.type = token.datatype;
4961 cnst->conste.v.float_value = token.v.floatvalue;
4968 static declaration_t *create_implicit_function(symbol_t *symbol,
4969 const source_position_t *source_position)
4971 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4972 ntype->function.return_type = type_int;
4973 ntype->function.unspecified_parameters = true;
4975 type_t *type = typehash_insert(ntype);
4980 declaration_t *const declaration = allocate_declaration_zero();
4981 declaration->storage_class = STORAGE_CLASS_EXTERN;
4982 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4983 declaration->type = type;
4984 declaration->symbol = symbol;
4985 declaration->source_position = *source_position;
4987 bool strict_prototypes_old = warning.strict_prototypes;
4988 warning.strict_prototypes = false;
4989 record_declaration(declaration);
4990 warning.strict_prototypes = strict_prototypes_old;
4996 * Creates a return_type (func)(argument_type) function type if not
4999 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5000 type_t *argument_type2)
5002 function_parameter_t *parameter2
5003 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5004 memset(parameter2, 0, sizeof(parameter2[0]));
5005 parameter2->type = argument_type2;
5007 function_parameter_t *parameter1
5008 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5009 memset(parameter1, 0, sizeof(parameter1[0]));
5010 parameter1->type = argument_type1;
5011 parameter1->next = parameter2;
5013 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5014 type->function.return_type = return_type;
5015 type->function.parameters = parameter1;
5017 type_t *result = typehash_insert(type);
5018 if(result != type) {
5026 * Creates a return_type (func)(argument_type) function type if not
5029 * @param return_type the return type
5030 * @param argument_type the argument type
5032 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5034 function_parameter_t *parameter
5035 = obstack_alloc(type_obst, sizeof(parameter[0]));
5036 memset(parameter, 0, sizeof(parameter[0]));
5037 parameter->type = argument_type;
5039 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5040 type->function.return_type = return_type;
5041 type->function.parameters = parameter;
5043 type_t *result = typehash_insert(type);
5044 if(result != type) {
5051 static type_t *make_function_0_type(type_t *return_type)
5053 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5054 type->function.return_type = return_type;
5055 type->function.parameters = NULL;
5057 type_t *result = typehash_insert(type);
5058 if(result != type) {
5066 * Creates a function type for some function like builtins.
5068 * @param symbol the symbol describing the builtin
5070 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5072 switch(symbol->ID) {
5073 case T___builtin_alloca:
5074 return make_function_1_type(type_void_ptr, type_size_t);
5075 case T___builtin_huge_val:
5076 return make_function_0_type(type_double);
5077 case T___builtin_nan:
5078 return make_function_1_type(type_double, type_char_ptr);
5079 case T___builtin_nanf:
5080 return make_function_1_type(type_float, type_char_ptr);
5081 case T___builtin_nand:
5082 return make_function_1_type(type_long_double, type_char_ptr);
5083 case T___builtin_va_end:
5084 return make_function_1_type(type_void, type_valist);
5085 case T___builtin_expect:
5086 return make_function_2_type(type_long, type_long, type_long);
5088 internal_errorf(HERE, "not implemented builtin symbol found");
5093 * Performs automatic type cast as described in § 6.3.2.1.
5095 * @param orig_type the original type
5097 static type_t *automatic_type_conversion(type_t *orig_type)
5099 type_t *type = skip_typeref(orig_type);
5100 if(is_type_array(type)) {
5101 array_type_t *array_type = &type->array;
5102 type_t *element_type = array_type->element_type;
5103 unsigned qualifiers = array_type->base.qualifiers;
5105 return make_pointer_type(element_type, qualifiers);
5108 if(is_type_function(type)) {
5109 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5116 * reverts the automatic casts of array to pointer types and function
5117 * to function-pointer types as defined § 6.3.2.1
5119 type_t *revert_automatic_type_conversion(const expression_t *expression)
5121 switch (expression->kind) {
5122 case EXPR_REFERENCE: return expression->reference.declaration->type;
5123 case EXPR_SELECT: return expression->select.compound_entry->type;
5125 case EXPR_UNARY_DEREFERENCE: {
5126 const expression_t *const value = expression->unary.value;
5127 type_t *const type = skip_typeref(value->base.type);
5128 assert(is_type_pointer(type));
5129 return type->pointer.points_to;
5132 case EXPR_BUILTIN_SYMBOL:
5133 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5135 case EXPR_ARRAY_ACCESS: {
5136 const expression_t *array_ref = expression->array_access.array_ref;
5137 type_t *type_left = skip_typeref(array_ref->base.type);
5138 if (!is_type_valid(type_left))
5140 assert(is_type_pointer(type_left));
5141 return type_left->pointer.points_to;
5144 case EXPR_STRING_LITERAL: {
5145 size_t size = expression->string.value.size;
5146 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5149 case EXPR_WIDE_STRING_LITERAL: {
5150 size_t size = expression->wide_string.value.size;
5151 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5154 case EXPR_COMPOUND_LITERAL:
5155 return expression->compound_literal.type;
5160 return expression->base.type;
5163 static expression_t *parse_reference(void)
5165 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5167 reference_expression_t *ref = &expression->reference;
5168 symbol_t *const symbol = token.v.symbol;
5170 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5172 source_position_t source_position = token.source_position;
5175 if(declaration == NULL) {
5176 if (! strict_mode && token.type == '(') {
5177 /* an implicitly defined function */
5178 if (warning.implicit_function_declaration) {
5179 warningf(HERE, "implicit declaration of function '%Y'",
5183 declaration = create_implicit_function(symbol,
5186 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5187 return create_invalid_expression();
5191 type_t *type = declaration->type;
5193 /* we always do the auto-type conversions; the & and sizeof parser contains
5194 * code to revert this! */
5195 type = automatic_type_conversion(type);
5197 ref->declaration = declaration;
5198 ref->base.type = type;
5200 /* this declaration is used */
5201 declaration->used = true;
5203 /* check for deprecated functions */
5204 if(declaration->deprecated != 0) {
5205 const char *prefix = "";
5206 if (is_type_function(declaration->type))
5207 prefix = "function ";
5209 if (declaration->deprecated_string != NULL) {
5210 warningf(&source_position,
5211 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5212 declaration->deprecated_string);
5214 warningf(&source_position,
5215 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5222 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5226 /* TODO check if explicit cast is allowed and issue warnings/errors */
5229 static expression_t *parse_compound_literal(type_t *type)
5231 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5233 parse_initializer_env_t env;
5235 env.declaration = NULL;
5236 env.must_be_constant = false;
5237 initializer_t *initializer = parse_initializer(&env);
5240 expression->compound_literal.initializer = initializer;
5241 expression->compound_literal.type = type;
5242 expression->base.type = automatic_type_conversion(type);
5248 * Parse a cast expression.
5250 static expression_t *parse_cast(void)
5252 source_position_t source_position = token.source_position;
5254 type_t *type = parse_typename();
5256 /* matching add_anchor_token() is at call site */
5257 rem_anchor_token(')');
5260 if(token.type == '{') {
5261 return parse_compound_literal(type);
5264 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5265 cast->base.source_position = source_position;
5267 expression_t *value = parse_sub_expression(20);
5269 check_cast_allowed(value, type);
5271 cast->base.type = type;
5272 cast->unary.value = value;
5276 return create_invalid_expression();
5280 * Parse a statement expression.
5282 static expression_t *parse_statement_expression(void)
5284 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5286 statement_t *statement = parse_compound_statement(true);
5287 expression->statement.statement = statement;
5288 expression->base.source_position = statement->base.source_position;
5290 /* find last statement and use its type */
5291 type_t *type = type_void;
5292 const statement_t *stmt = statement->compound.statements;
5294 while (stmt->base.next != NULL)
5295 stmt = stmt->base.next;
5297 if (stmt->kind == STATEMENT_EXPRESSION) {
5298 type = stmt->expression.expression->base.type;
5301 warningf(&expression->base.source_position, "empty statement expression ({})");
5303 expression->base.type = type;
5309 return create_invalid_expression();
5313 * Parse a braced expression.
5315 static expression_t *parse_brace_expression(void)
5318 add_anchor_token(')');
5320 switch(token.type) {
5322 /* gcc extension: a statement expression */
5323 return parse_statement_expression();
5327 return parse_cast();
5329 if(is_typedef_symbol(token.v.symbol)) {
5330 return parse_cast();
5334 expression_t *result = parse_expression();
5335 rem_anchor_token(')');
5340 return create_invalid_expression();
5343 static expression_t *parse_function_keyword(void)
5348 if (current_function == NULL) {
5349 errorf(HERE, "'__func__' used outside of a function");
5352 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5353 expression->base.type = type_char_ptr;
5354 expression->funcname.kind = FUNCNAME_FUNCTION;
5359 static expression_t *parse_pretty_function_keyword(void)
5361 eat(T___PRETTY_FUNCTION__);
5363 if (current_function == NULL) {
5364 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5367 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5368 expression->base.type = type_char_ptr;
5369 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5374 static expression_t *parse_funcsig_keyword(void)
5378 if (current_function == NULL) {
5379 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5382 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5383 expression->base.type = type_char_ptr;
5384 expression->funcname.kind = FUNCNAME_FUNCSIG;
5389 static expression_t *parse_funcdname_keyword(void)
5391 eat(T___FUNCDNAME__);
5393 if (current_function == NULL) {
5394 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5397 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5398 expression->base.type = type_char_ptr;
5399 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5404 static designator_t *parse_designator(void)
5406 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5407 result->source_position = *HERE;
5409 if(token.type != T_IDENTIFIER) {
5410 parse_error_expected("while parsing member designator",
5411 T_IDENTIFIER, NULL);
5414 result->symbol = token.v.symbol;
5417 designator_t *last_designator = result;
5419 if(token.type == '.') {
5421 if(token.type != T_IDENTIFIER) {
5422 parse_error_expected("while parsing member designator",
5423 T_IDENTIFIER, NULL);
5426 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5427 designator->source_position = *HERE;
5428 designator->symbol = token.v.symbol;
5431 last_designator->next = designator;
5432 last_designator = designator;
5435 if(token.type == '[') {
5437 add_anchor_token(']');
5438 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5439 designator->source_position = *HERE;
5440 designator->array_index = parse_expression();
5441 rem_anchor_token(']');
5443 if(designator->array_index == NULL) {
5447 last_designator->next = designator;
5448 last_designator = designator;
5460 * Parse the __builtin_offsetof() expression.
5462 static expression_t *parse_offsetof(void)
5464 eat(T___builtin_offsetof);
5466 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5467 expression->base.type = type_size_t;
5470 add_anchor_token(',');
5471 type_t *type = parse_typename();
5472 rem_anchor_token(',');
5474 add_anchor_token(')');
5475 designator_t *designator = parse_designator();
5476 rem_anchor_token(')');
5479 expression->offsetofe.type = type;
5480 expression->offsetofe.designator = designator;
5483 memset(&path, 0, sizeof(path));
5484 path.top_type = type;
5485 path.path = NEW_ARR_F(type_path_entry_t, 0);
5487 descend_into_subtype(&path);
5489 if(!walk_designator(&path, designator, true)) {
5490 return create_invalid_expression();
5493 DEL_ARR_F(path.path);
5497 return create_invalid_expression();
5501 * Parses a _builtin_va_start() expression.
5503 static expression_t *parse_va_start(void)
5505 eat(T___builtin_va_start);
5507 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5510 add_anchor_token(',');
5511 expression->va_starte.ap = parse_assignment_expression();
5512 rem_anchor_token(',');
5514 expression_t *const expr = parse_assignment_expression();
5515 if (expr->kind == EXPR_REFERENCE) {
5516 declaration_t *const decl = expr->reference.declaration;
5518 return create_invalid_expression();
5519 if (decl->parent_scope == ¤t_function->scope &&
5520 decl->next == NULL) {
5521 expression->va_starte.parameter = decl;
5526 errorf(&expr->base.source_position,
5527 "second argument of 'va_start' must be last parameter of the current function");
5529 return create_invalid_expression();
5533 * Parses a _builtin_va_arg() expression.
5535 static expression_t *parse_va_arg(void)
5537 eat(T___builtin_va_arg);
5539 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5542 expression->va_arge.ap = parse_assignment_expression();
5544 expression->base.type = parse_typename();
5549 return create_invalid_expression();
5552 static expression_t *parse_builtin_symbol(void)
5554 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5556 symbol_t *symbol = token.v.symbol;
5558 expression->builtin_symbol.symbol = symbol;
5561 type_t *type = get_builtin_symbol_type(symbol);
5562 type = automatic_type_conversion(type);
5564 expression->base.type = type;
5569 * Parses a __builtin_constant() expression.
5571 static expression_t *parse_builtin_constant(void)
5573 eat(T___builtin_constant_p);
5575 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5578 add_anchor_token(')');
5579 expression->builtin_constant.value = parse_assignment_expression();
5580 rem_anchor_token(')');
5582 expression->base.type = type_int;
5586 return create_invalid_expression();
5590 * Parses a __builtin_prefetch() expression.
5592 static expression_t *parse_builtin_prefetch(void)
5594 eat(T___builtin_prefetch);
5596 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5599 add_anchor_token(')');
5600 expression->builtin_prefetch.adr = parse_assignment_expression();
5601 if (token.type == ',') {
5603 expression->builtin_prefetch.rw = parse_assignment_expression();
5605 if (token.type == ',') {
5607 expression->builtin_prefetch.locality = parse_assignment_expression();
5609 rem_anchor_token(')');
5611 expression->base.type = type_void;
5615 return create_invalid_expression();
5619 * Parses a __builtin_is_*() compare expression.
5621 static expression_t *parse_compare_builtin(void)
5623 expression_t *expression;
5625 switch(token.type) {
5626 case T___builtin_isgreater:
5627 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5629 case T___builtin_isgreaterequal:
5630 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5632 case T___builtin_isless:
5633 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5635 case T___builtin_islessequal:
5636 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5638 case T___builtin_islessgreater:
5639 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5641 case T___builtin_isunordered:
5642 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5645 internal_errorf(HERE, "invalid compare builtin found");
5648 expression->base.source_position = *HERE;
5652 expression->binary.left = parse_assignment_expression();
5654 expression->binary.right = parse_assignment_expression();
5657 type_t *const orig_type_left = expression->binary.left->base.type;
5658 type_t *const orig_type_right = expression->binary.right->base.type;
5660 type_t *const type_left = skip_typeref(orig_type_left);
5661 type_t *const type_right = skip_typeref(orig_type_right);
5662 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5663 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5664 type_error_incompatible("invalid operands in comparison",
5665 &expression->base.source_position, orig_type_left, orig_type_right);
5668 semantic_comparison(&expression->binary);
5673 return create_invalid_expression();
5678 * Parses a __builtin_expect() expression.
5680 static expression_t *parse_builtin_expect(void)
5682 eat(T___builtin_expect);
5684 expression_t *expression
5685 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5688 expression->binary.left = parse_assignment_expression();
5690 expression->binary.right = parse_constant_expression();
5693 expression->base.type = expression->binary.left->base.type;
5697 return create_invalid_expression();
5702 * Parses a MS assume() expression.
5704 static expression_t *parse_assume(void) {
5707 expression_t *expression
5708 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5711 add_anchor_token(')');
5712 expression->unary.value = parse_assignment_expression();
5713 rem_anchor_token(')');
5716 expression->base.type = type_void;
5719 return create_invalid_expression();
5723 * Parse a microsoft __noop expression.
5725 static expression_t *parse_noop_expression(void) {
5726 source_position_t source_position = *HERE;
5729 if (token.type == '(') {
5730 /* parse arguments */
5732 add_anchor_token(')');
5733 add_anchor_token(',');
5735 if(token.type != ')') {
5737 (void)parse_assignment_expression();
5738 if(token.type != ',')
5744 rem_anchor_token(',');
5745 rem_anchor_token(')');
5748 /* the result is a (int)0 */
5749 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5750 cnst->base.source_position = source_position;
5751 cnst->base.type = type_int;
5752 cnst->conste.v.int_value = 0;
5753 cnst->conste.is_ms_noop = true;
5758 return create_invalid_expression();
5762 * Parses a primary expression.
5764 static expression_t *parse_primary_expression(void)
5766 switch (token.type) {
5767 case T_INTEGER: return parse_int_const();
5768 case T_CHARACTER_CONSTANT: return parse_character_constant();
5769 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5770 case T_FLOATINGPOINT: return parse_float_const();
5771 case T_STRING_LITERAL:
5772 case T_WIDE_STRING_LITERAL: return parse_string_const();
5773 case T_IDENTIFIER: return parse_reference();
5774 case T___FUNCTION__:
5775 case T___func__: return parse_function_keyword();
5776 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5777 case T___FUNCSIG__: return parse_funcsig_keyword();
5778 case T___FUNCDNAME__: return parse_funcdname_keyword();
5779 case T___builtin_offsetof: return parse_offsetof();
5780 case T___builtin_va_start: return parse_va_start();
5781 case T___builtin_va_arg: return parse_va_arg();
5782 case T___builtin_expect:
5783 case T___builtin_alloca:
5784 case T___builtin_nan:
5785 case T___builtin_nand:
5786 case T___builtin_nanf:
5787 case T___builtin_huge_val:
5788 case T___builtin_va_end: return parse_builtin_symbol();
5789 case T___builtin_isgreater:
5790 case T___builtin_isgreaterequal:
5791 case T___builtin_isless:
5792 case T___builtin_islessequal:
5793 case T___builtin_islessgreater:
5794 case T___builtin_isunordered: return parse_compare_builtin();
5795 case T___builtin_constant_p: return parse_builtin_constant();
5796 case T___builtin_prefetch: return parse_builtin_prefetch();
5797 case T__assume: return parse_assume();
5799 case '(': return parse_brace_expression();
5800 case T___noop: return parse_noop_expression();
5803 errorf(HERE, "unexpected token %K, expected an expression", &token);
5804 return create_invalid_expression();
5808 * Check if the expression has the character type and issue a warning then.
5810 static void check_for_char_index_type(const expression_t *expression) {
5811 type_t *const type = expression->base.type;
5812 const type_t *const base_type = skip_typeref(type);
5814 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5815 warning.char_subscripts) {
5816 warningf(&expression->base.source_position,
5817 "array subscript has type '%T'", type);
5821 static expression_t *parse_array_expression(unsigned precedence,
5827 add_anchor_token(']');
5829 expression_t *inside = parse_expression();
5831 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5833 array_access_expression_t *array_access = &expression->array_access;
5835 type_t *const orig_type_left = left->base.type;
5836 type_t *const orig_type_inside = inside->base.type;
5838 type_t *const type_left = skip_typeref(orig_type_left);
5839 type_t *const type_inside = skip_typeref(orig_type_inside);
5841 type_t *return_type;
5842 if (is_type_pointer(type_left)) {
5843 return_type = type_left->pointer.points_to;
5844 array_access->array_ref = left;
5845 array_access->index = inside;
5846 check_for_char_index_type(inside);
5847 } else if (is_type_pointer(type_inside)) {
5848 return_type = type_inside->pointer.points_to;
5849 array_access->array_ref = inside;
5850 array_access->index = left;
5851 array_access->flipped = true;
5852 check_for_char_index_type(left);
5854 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5856 "array access on object with non-pointer types '%T', '%T'",
5857 orig_type_left, orig_type_inside);
5859 return_type = type_error_type;
5860 array_access->array_ref = create_invalid_expression();
5863 rem_anchor_token(']');
5864 if(token.type != ']') {
5865 parse_error_expected("Problem while parsing array access", ']', NULL);
5870 return_type = automatic_type_conversion(return_type);
5871 expression->base.type = return_type;
5876 static expression_t *parse_typeprop(expression_kind_t const kind,
5877 source_position_t const pos,
5878 unsigned const precedence)
5880 expression_t *tp_expression = allocate_expression_zero(kind);
5881 tp_expression->base.type = type_size_t;
5882 tp_expression->base.source_position = pos;
5884 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5886 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5888 add_anchor_token(')');
5889 type_t* const orig_type = parse_typename();
5890 tp_expression->typeprop.type = orig_type;
5892 type_t const* const type = skip_typeref(orig_type);
5893 char const* const wrong_type =
5894 is_type_incomplete(type) ? "incomplete" :
5895 type->kind == TYPE_FUNCTION ? "function designator" :
5896 type->kind == TYPE_BITFIELD ? "bitfield" :
5898 if (wrong_type != NULL) {
5899 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5900 what, wrong_type, type);
5903 rem_anchor_token(')');
5906 expression_t *expression = parse_sub_expression(precedence);
5908 type_t* const orig_type = revert_automatic_type_conversion(expression);
5909 expression->base.type = orig_type;
5911 type_t const* const type = skip_typeref(orig_type);
5912 char const* const wrong_type =
5913 is_type_incomplete(type) ? "incomplete" :
5914 type->kind == TYPE_FUNCTION ? "function designator" :
5915 type->kind == TYPE_BITFIELD ? "bitfield" :
5917 if (wrong_type != NULL) {
5918 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5921 tp_expression->typeprop.type = expression->base.type;
5922 tp_expression->typeprop.tp_expression = expression;
5925 return tp_expression;
5927 return create_invalid_expression();
5930 static expression_t *parse_sizeof(unsigned precedence)
5932 source_position_t pos = *HERE;
5934 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5937 static expression_t *parse_alignof(unsigned precedence)
5939 source_position_t pos = *HERE;
5941 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5944 static expression_t *parse_select_expression(unsigned precedence,
5945 expression_t *compound)
5948 assert(token.type == '.' || token.type == T_MINUSGREATER);
5950 bool is_pointer = (token.type == T_MINUSGREATER);
5953 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5954 select->select.compound = compound;
5956 if (token.type != T_IDENTIFIER) {
5957 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5960 symbol_t *symbol = token.v.symbol;
5961 select->select.symbol = symbol;
5964 type_t *const orig_type = compound->base.type;
5965 type_t *const type = skip_typeref(orig_type);
5967 type_t *type_left = type;
5969 if (!is_type_pointer(type)) {
5970 if (is_type_valid(type)) {
5971 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5973 return create_invalid_expression();
5975 type_left = type->pointer.points_to;
5977 type_left = skip_typeref(type_left);
5979 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5980 type_left->kind != TYPE_COMPOUND_UNION) {
5981 if (is_type_valid(type_left)) {
5982 errorf(HERE, "request for member '%Y' in something not a struct or "
5983 "union, but '%T'", symbol, type_left);
5985 return create_invalid_expression();
5988 declaration_t *const declaration = type_left->compound.declaration;
5990 if (!declaration->init.complete) {
5991 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5993 return create_invalid_expression();
5996 declaration_t *iter = find_compound_entry(declaration, symbol);
5998 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5999 return create_invalid_expression();
6002 /* we always do the auto-type conversions; the & and sizeof parser contains
6003 * code to revert this! */
6004 type_t *expression_type = automatic_type_conversion(iter->type);
6006 select->select.compound_entry = iter;
6007 select->base.type = expression_type;
6009 type_t *skipped = skip_typeref(iter->type);
6010 if (skipped->kind == TYPE_BITFIELD) {
6011 select->base.type = skipped->bitfield.base_type;
6017 static void check_call_argument(const function_parameter_t *parameter,
6018 call_argument_t *argument)
6020 type_t *expected_type = parameter->type;
6021 type_t *expected_type_skip = skip_typeref(expected_type);
6022 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6023 expression_t *arg_expr = argument->expression;
6025 /* handle transparent union gnu extension */
6026 if (is_type_union(expected_type_skip)
6027 && (expected_type_skip->base.modifiers
6028 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6029 declaration_t *union_decl = expected_type_skip->compound.declaration;
6031 declaration_t *declaration = union_decl->scope.declarations;
6032 type_t *best_type = NULL;
6033 for ( ; declaration != NULL; declaration = declaration->next) {
6034 type_t *decl_type = declaration->type;
6035 error = semantic_assign(decl_type, arg_expr);
6036 if (error == ASSIGN_ERROR_INCOMPATIBLE
6037 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6040 if (error == ASSIGN_SUCCESS) {
6041 best_type = decl_type;
6042 } else if (best_type == NULL) {
6043 best_type = decl_type;
6047 if (best_type != NULL) {
6048 expected_type = best_type;
6052 error = semantic_assign(expected_type, arg_expr);
6053 argument->expression = create_implicit_cast(argument->expression,
6056 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6057 report_assign_error(error, expected_type, arg_expr, "function call",
6058 &arg_expr->base.source_position);
6062 * Parse a call expression, ie. expression '( ... )'.
6064 * @param expression the function address
6066 static expression_t *parse_call_expression(unsigned precedence,
6067 expression_t *expression)
6070 expression_t *result = allocate_expression_zero(EXPR_CALL);
6071 result->base.source_position = expression->base.source_position;
6073 call_expression_t *call = &result->call;
6074 call->function = expression;
6076 type_t *const orig_type = expression->base.type;
6077 type_t *const type = skip_typeref(orig_type);
6079 function_type_t *function_type = NULL;
6080 if (is_type_pointer(type)) {
6081 type_t *const to_type = skip_typeref(type->pointer.points_to);
6083 if (is_type_function(to_type)) {
6084 function_type = &to_type->function;
6085 call->base.type = function_type->return_type;
6089 if (function_type == NULL && is_type_valid(type)) {
6090 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6093 /* parse arguments */
6095 add_anchor_token(')');
6096 add_anchor_token(',');
6098 if(token.type != ')') {
6099 call_argument_t *last_argument = NULL;
6102 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6104 argument->expression = parse_assignment_expression();
6105 if(last_argument == NULL) {
6106 call->arguments = argument;
6108 last_argument->next = argument;
6110 last_argument = argument;
6112 if(token.type != ',')
6117 rem_anchor_token(',');
6118 rem_anchor_token(')');
6121 if(function_type == NULL)
6124 function_parameter_t *parameter = function_type->parameters;
6125 call_argument_t *argument = call->arguments;
6126 if (!function_type->unspecified_parameters) {
6127 for( ; parameter != NULL && argument != NULL;
6128 parameter = parameter->next, argument = argument->next) {
6129 check_call_argument(parameter, argument);
6132 if (parameter != NULL) {
6133 errorf(HERE, "too few arguments to function '%E'", expression);
6134 } else if (argument != NULL && !function_type->variadic) {
6135 errorf(HERE, "too many arguments to function '%E'", expression);
6139 /* do default promotion */
6140 for( ; argument != NULL; argument = argument->next) {
6141 type_t *type = argument->expression->base.type;
6143 type = get_default_promoted_type(type);
6145 argument->expression
6146 = create_implicit_cast(argument->expression, type);
6149 check_format(&result->call);
6153 return create_invalid_expression();
6156 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6158 static bool same_compound_type(const type_t *type1, const type_t *type2)
6161 is_type_compound(type1) &&
6162 type1->kind == type2->kind &&
6163 type1->compound.declaration == type2->compound.declaration;
6167 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6169 * @param expression the conditional expression
6171 static expression_t *parse_conditional_expression(unsigned precedence,
6172 expression_t *expression)
6175 add_anchor_token(':');
6177 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6179 conditional_expression_t *conditional = &result->conditional;
6180 conditional->condition = expression;
6183 type_t *const condition_type_orig = expression->base.type;
6184 type_t *const condition_type = skip_typeref(condition_type_orig);
6185 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6186 type_error("expected a scalar type in conditional condition",
6187 &expression->base.source_position, condition_type_orig);
6190 expression_t *true_expression = parse_expression();
6191 rem_anchor_token(':');
6193 expression_t *false_expression = parse_sub_expression(precedence);
6195 type_t *const orig_true_type = true_expression->base.type;
6196 type_t *const orig_false_type = false_expression->base.type;
6197 type_t *const true_type = skip_typeref(orig_true_type);
6198 type_t *const false_type = skip_typeref(orig_false_type);
6201 type_t *result_type;
6202 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6203 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6204 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6205 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6206 warningf(&expression->base.source_position,
6207 "ISO C forbids conditional expression with only one void side");
6209 result_type = type_void;
6210 } else if (is_type_arithmetic(true_type)
6211 && is_type_arithmetic(false_type)) {
6212 result_type = semantic_arithmetic(true_type, false_type);
6214 true_expression = create_implicit_cast(true_expression, result_type);
6215 false_expression = create_implicit_cast(false_expression, result_type);
6217 conditional->true_expression = true_expression;
6218 conditional->false_expression = false_expression;
6219 conditional->base.type = result_type;
6220 } else if (same_compound_type(true_type, false_type)) {
6221 /* just take 1 of the 2 types */
6222 result_type = true_type;
6223 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6224 type_t *pointer_type;
6226 expression_t *other_expression;
6227 if (is_type_pointer(true_type) &&
6228 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6229 pointer_type = true_type;
6230 other_type = false_type;
6231 other_expression = false_expression;
6233 pointer_type = false_type;
6234 other_type = true_type;
6235 other_expression = true_expression;
6238 if (is_null_pointer_constant(other_expression)) {
6239 result_type = pointer_type;
6240 } else if (is_type_pointer(other_type)) {
6241 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6242 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6245 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6246 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6248 } else if (types_compatible(get_unqualified_type(to1),
6249 get_unqualified_type(to2))) {
6252 warningf(&expression->base.source_position,
6253 "pointer types '%T' and '%T' in conditional expression are incompatible",
6254 true_type, false_type);
6258 type_t *const copy = duplicate_type(to);
6259 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6261 type_t *const type = typehash_insert(copy);
6265 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6266 } else if(is_type_integer(other_type)) {
6267 warningf(&expression->base.source_position,
6268 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6269 result_type = pointer_type;
6271 type_error_incompatible("while parsing conditional",
6272 &expression->base.source_position, true_type, false_type);
6273 result_type = type_error_type;
6276 /* TODO: one pointer to void*, other some pointer */
6278 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6279 type_error_incompatible("while parsing conditional",
6280 &expression->base.source_position, true_type,
6283 result_type = type_error_type;
6286 conditional->true_expression
6287 = create_implicit_cast(true_expression, result_type);
6288 conditional->false_expression
6289 = create_implicit_cast(false_expression, result_type);
6290 conditional->base.type = result_type;
6293 return create_invalid_expression();
6297 * Parse an extension expression.
6299 static expression_t *parse_extension(unsigned precedence)
6301 eat(T___extension__);
6303 /* TODO enable extensions */
6304 expression_t *expression = parse_sub_expression(precedence);
6305 /* TODO disable extensions */
6310 * Parse a __builtin_classify_type() expression.
6312 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6314 eat(T___builtin_classify_type);
6316 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6317 result->base.type = type_int;
6320 add_anchor_token(')');
6321 expression_t *expression = parse_sub_expression(precedence);
6322 rem_anchor_token(')');
6324 result->classify_type.type_expression = expression;
6328 return create_invalid_expression();
6331 static void check_pointer_arithmetic(const source_position_t *source_position,
6332 type_t *pointer_type,
6333 type_t *orig_pointer_type)
6335 type_t *points_to = pointer_type->pointer.points_to;
6336 points_to = skip_typeref(points_to);
6338 if (is_type_incomplete(points_to) &&
6340 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6341 errorf(source_position,
6342 "arithmetic with pointer to incomplete type '%T' not allowed",
6344 } else if (is_type_function(points_to)) {
6345 errorf(source_position,
6346 "arithmetic with pointer to function type '%T' not allowed",
6351 static void semantic_incdec(unary_expression_t *expression)
6353 type_t *const orig_type = expression->value->base.type;
6354 type_t *const type = skip_typeref(orig_type);
6355 if (is_type_pointer(type)) {
6356 check_pointer_arithmetic(&expression->base.source_position,
6358 } else if (!is_type_real(type) && is_type_valid(type)) {
6359 /* TODO: improve error message */
6360 errorf(HERE, "operation needs an arithmetic or pointer type");
6362 expression->base.type = orig_type;
6365 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6367 type_t *const orig_type = expression->value->base.type;
6368 type_t *const type = skip_typeref(orig_type);
6369 if(!is_type_arithmetic(type)) {
6370 if (is_type_valid(type)) {
6371 /* TODO: improve error message */
6372 errorf(HERE, "operation needs an arithmetic type");
6377 expression->base.type = orig_type;
6380 static void semantic_unexpr_scalar(unary_expression_t *expression)
6382 type_t *const orig_type = expression->value->base.type;
6383 type_t *const type = skip_typeref(orig_type);
6384 if (!is_type_scalar(type)) {
6385 if (is_type_valid(type)) {
6386 errorf(HERE, "operand of ! must be of scalar type");
6391 expression->base.type = orig_type;
6394 static void semantic_unexpr_integer(unary_expression_t *expression)
6396 type_t *const orig_type = expression->value->base.type;
6397 type_t *const type = skip_typeref(orig_type);
6398 if (!is_type_integer(type)) {
6399 if (is_type_valid(type)) {
6400 errorf(HERE, "operand of ~ must be of integer type");
6405 expression->base.type = orig_type;
6408 static void semantic_dereference(unary_expression_t *expression)
6410 type_t *const orig_type = expression->value->base.type;
6411 type_t *const type = skip_typeref(orig_type);
6412 if(!is_type_pointer(type)) {
6413 if (is_type_valid(type)) {
6414 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6419 type_t *result_type = type->pointer.points_to;
6420 result_type = automatic_type_conversion(result_type);
6421 expression->base.type = result_type;
6424 static void set_address_taken(expression_t *expression, bool may_be_register)
6426 if(expression->kind != EXPR_REFERENCE)
6429 declaration_t *const declaration = expression->reference.declaration;
6430 /* happens for parse errors */
6431 if(declaration == NULL)
6434 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6435 errorf(&expression->base.source_position,
6436 "address of register variable '%Y' requested",
6437 declaration->symbol);
6439 declaration->address_taken = 1;
6444 * Check the semantic of the address taken expression.
6446 static void semantic_take_addr(unary_expression_t *expression)
6448 expression_t *value = expression->value;
6449 value->base.type = revert_automatic_type_conversion(value);
6451 type_t *orig_type = value->base.type;
6452 if(!is_type_valid(orig_type))
6455 set_address_taken(value, false);
6457 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6460 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6461 static expression_t *parse_##unexpression_type(unsigned precedence) \
6465 expression_t *unary_expression \
6466 = allocate_expression_zero(unexpression_type); \
6467 unary_expression->base.source_position = *HERE; \
6468 unary_expression->unary.value = parse_sub_expression(precedence); \
6470 sfunc(&unary_expression->unary); \
6472 return unary_expression; \
6475 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6476 semantic_unexpr_arithmetic)
6477 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6478 semantic_unexpr_arithmetic)
6479 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6480 semantic_unexpr_scalar)
6481 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6482 semantic_dereference)
6483 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6485 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6486 semantic_unexpr_integer)
6487 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6489 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6492 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6494 static expression_t *parse_##unexpression_type(unsigned precedence, \
6495 expression_t *left) \
6497 (void) precedence; \
6500 expression_t *unary_expression \
6501 = allocate_expression_zero(unexpression_type); \
6502 unary_expression->unary.value = left; \
6504 sfunc(&unary_expression->unary); \
6506 return unary_expression; \
6509 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6510 EXPR_UNARY_POSTFIX_INCREMENT,
6512 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6513 EXPR_UNARY_POSTFIX_DECREMENT,
6516 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6518 /* TODO: handle complex + imaginary types */
6520 /* § 6.3.1.8 Usual arithmetic conversions */
6521 if(type_left == type_long_double || type_right == type_long_double) {
6522 return type_long_double;
6523 } else if(type_left == type_double || type_right == type_double) {
6525 } else if(type_left == type_float || type_right == type_float) {
6529 type_right = promote_integer(type_right);
6530 type_left = promote_integer(type_left);
6532 if(type_left == type_right)
6535 bool signed_left = is_type_signed(type_left);
6536 bool signed_right = is_type_signed(type_right);
6537 int rank_left = get_rank(type_left);
6538 int rank_right = get_rank(type_right);
6539 if(rank_left < rank_right) {
6540 if(signed_left == signed_right || !signed_right) {
6546 if(signed_left == signed_right || !signed_left) {
6555 * Check the semantic restrictions for a binary expression.
6557 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6559 expression_t *const left = expression->left;
6560 expression_t *const right = expression->right;
6561 type_t *const orig_type_left = left->base.type;
6562 type_t *const orig_type_right = right->base.type;
6563 type_t *const type_left = skip_typeref(orig_type_left);
6564 type_t *const type_right = skip_typeref(orig_type_right);
6566 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6567 /* TODO: improve error message */
6568 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6569 errorf(HERE, "operation needs arithmetic types");
6574 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6575 expression->left = create_implicit_cast(left, arithmetic_type);
6576 expression->right = create_implicit_cast(right, arithmetic_type);
6577 expression->base.type = arithmetic_type;
6580 static void semantic_shift_op(binary_expression_t *expression)
6582 expression_t *const left = expression->left;
6583 expression_t *const right = expression->right;
6584 type_t *const orig_type_left = left->base.type;
6585 type_t *const orig_type_right = right->base.type;
6586 type_t * type_left = skip_typeref(orig_type_left);
6587 type_t * type_right = skip_typeref(orig_type_right);
6589 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6590 /* TODO: improve error message */
6591 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6592 errorf(HERE, "operation needs integer types");
6597 type_left = promote_integer(type_left);
6598 type_right = promote_integer(type_right);
6600 expression->left = create_implicit_cast(left, type_left);
6601 expression->right = create_implicit_cast(right, type_right);
6602 expression->base.type = type_left;
6605 static void semantic_add(binary_expression_t *expression)
6607 expression_t *const left = expression->left;
6608 expression_t *const right = expression->right;
6609 type_t *const orig_type_left = left->base.type;
6610 type_t *const orig_type_right = right->base.type;
6611 type_t *const type_left = skip_typeref(orig_type_left);
6612 type_t *const type_right = skip_typeref(orig_type_right);
6615 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6616 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6617 expression->left = create_implicit_cast(left, arithmetic_type);
6618 expression->right = create_implicit_cast(right, arithmetic_type);
6619 expression->base.type = arithmetic_type;
6621 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6622 check_pointer_arithmetic(&expression->base.source_position,
6623 type_left, orig_type_left);
6624 expression->base.type = type_left;
6625 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6626 check_pointer_arithmetic(&expression->base.source_position,
6627 type_right, orig_type_right);
6628 expression->base.type = type_right;
6629 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6630 errorf(&expression->base.source_position,
6631 "invalid operands to binary + ('%T', '%T')",
6632 orig_type_left, orig_type_right);
6636 static void semantic_sub(binary_expression_t *expression)
6638 expression_t *const left = expression->left;
6639 expression_t *const right = expression->right;
6640 type_t *const orig_type_left = left->base.type;
6641 type_t *const orig_type_right = right->base.type;
6642 type_t *const type_left = skip_typeref(orig_type_left);
6643 type_t *const type_right = skip_typeref(orig_type_right);
6646 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6647 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6648 expression->left = create_implicit_cast(left, arithmetic_type);
6649 expression->right = create_implicit_cast(right, arithmetic_type);
6650 expression->base.type = arithmetic_type;
6652 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6653 check_pointer_arithmetic(&expression->base.source_position,
6654 type_left, orig_type_left);
6655 expression->base.type = type_left;
6656 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6657 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6658 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6659 if (!types_compatible(unqual_left, unqual_right)) {
6660 errorf(&expression->base.source_position,
6661 "subtracting pointers to incompatible types '%T' and '%T'",
6662 orig_type_left, orig_type_right);
6663 } else if (!is_type_object(unqual_left)) {
6664 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6665 warningf(&expression->base.source_position,
6666 "subtracting pointers to void");
6668 errorf(&expression->base.source_position,
6669 "subtracting pointers to non-object types '%T'",
6673 expression->base.type = type_ptrdiff_t;
6674 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6675 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6676 orig_type_left, orig_type_right);
6681 * Check the semantics of comparison expressions.
6683 * @param expression The expression to check.
6685 static void semantic_comparison(binary_expression_t *expression)
6687 expression_t *left = expression->left;
6688 expression_t *right = expression->right;
6689 type_t *orig_type_left = left->base.type;
6690 type_t *orig_type_right = right->base.type;
6692 type_t *type_left = skip_typeref(orig_type_left);
6693 type_t *type_right = skip_typeref(orig_type_right);
6695 /* TODO non-arithmetic types */
6696 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6697 /* test for signed vs unsigned compares */
6698 if (warning.sign_compare &&
6699 (expression->base.kind != EXPR_BINARY_EQUAL &&
6700 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6701 (is_type_signed(type_left) != is_type_signed(type_right))) {
6703 /* check if 1 of the operands is a constant, in this case we just
6704 * check wether we can safely represent the resulting constant in
6705 * the type of the other operand. */
6706 expression_t *const_expr = NULL;
6707 expression_t *other_expr = NULL;
6709 if(is_constant_expression(left)) {
6712 } else if(is_constant_expression(right)) {
6717 if(const_expr != NULL) {
6718 type_t *other_type = skip_typeref(other_expr->base.type);
6719 long val = fold_constant(const_expr);
6720 /* TODO: check if val can be represented by other_type */
6724 warningf(&expression->base.source_position,
6725 "comparison between signed and unsigned");
6727 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6728 expression->left = create_implicit_cast(left, arithmetic_type);
6729 expression->right = create_implicit_cast(right, arithmetic_type);
6730 expression->base.type = arithmetic_type;
6731 if (warning.float_equal &&
6732 (expression->base.kind == EXPR_BINARY_EQUAL ||
6733 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6734 is_type_float(arithmetic_type)) {
6735 warningf(&expression->base.source_position,
6736 "comparing floating point with == or != is unsafe");
6738 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6739 /* TODO check compatibility */
6740 } else if (is_type_pointer(type_left)) {
6741 expression->right = create_implicit_cast(right, type_left);
6742 } else if (is_type_pointer(type_right)) {
6743 expression->left = create_implicit_cast(left, type_right);
6744 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6745 type_error_incompatible("invalid operands in comparison",
6746 &expression->base.source_position,
6747 type_left, type_right);
6749 expression->base.type = type_int;
6753 * Checks if a compound type has constant fields.
6755 static bool has_const_fields(const compound_type_t *type)
6757 const scope_t *scope = &type->declaration->scope;
6758 const declaration_t *declaration = scope->declarations;
6760 for (; declaration != NULL; declaration = declaration->next) {
6761 if (declaration->namespc != NAMESPACE_NORMAL)
6764 const type_t *decl_type = skip_typeref(declaration->type);
6765 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6772 static bool is_lvalue(const expression_t *expression)
6774 switch (expression->kind) {
6775 case EXPR_REFERENCE:
6776 case EXPR_ARRAY_ACCESS:
6778 case EXPR_UNARY_DEREFERENCE:
6786 static bool is_valid_assignment_lhs(expression_t const* const left)
6788 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6789 type_t *const type_left = skip_typeref(orig_type_left);
6791 if (!is_lvalue(left)) {
6792 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6797 if (is_type_array(type_left)) {
6798 errorf(HERE, "cannot assign to arrays ('%E')", left);
6801 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6802 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6806 if (is_type_incomplete(type_left)) {
6807 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6808 left, orig_type_left);
6811 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6812 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6813 left, orig_type_left);
6820 static void semantic_arithmetic_assign(binary_expression_t *expression)
6822 expression_t *left = expression->left;
6823 expression_t *right = expression->right;
6824 type_t *orig_type_left = left->base.type;
6825 type_t *orig_type_right = right->base.type;
6827 if (!is_valid_assignment_lhs(left))
6830 type_t *type_left = skip_typeref(orig_type_left);
6831 type_t *type_right = skip_typeref(orig_type_right);
6833 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6834 /* TODO: improve error message */
6835 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6836 errorf(HERE, "operation needs arithmetic types");
6841 /* combined instructions are tricky. We can't create an implicit cast on
6842 * the left side, because we need the uncasted form for the store.
6843 * The ast2firm pass has to know that left_type must be right_type
6844 * for the arithmetic operation and create a cast by itself */
6845 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6846 expression->right = create_implicit_cast(right, arithmetic_type);
6847 expression->base.type = type_left;
6850 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6852 expression_t *const left = expression->left;
6853 expression_t *const right = expression->right;
6854 type_t *const orig_type_left = left->base.type;
6855 type_t *const orig_type_right = right->base.type;
6856 type_t *const type_left = skip_typeref(orig_type_left);
6857 type_t *const type_right = skip_typeref(orig_type_right);
6859 if (!is_valid_assignment_lhs(left))
6862 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6863 /* combined instructions are tricky. We can't create an implicit cast on
6864 * the left side, because we need the uncasted form for the store.
6865 * The ast2firm pass has to know that left_type must be right_type
6866 * for the arithmetic operation and create a cast by itself */
6867 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6868 expression->right = create_implicit_cast(right, arithmetic_type);
6869 expression->base.type = type_left;
6870 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6871 check_pointer_arithmetic(&expression->base.source_position,
6872 type_left, orig_type_left);
6873 expression->base.type = type_left;
6874 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6875 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6880 * Check the semantic restrictions of a logical expression.
6882 static void semantic_logical_op(binary_expression_t *expression)
6884 expression_t *const left = expression->left;
6885 expression_t *const right = expression->right;
6886 type_t *const orig_type_left = left->base.type;
6887 type_t *const orig_type_right = right->base.type;
6888 type_t *const type_left = skip_typeref(orig_type_left);
6889 type_t *const type_right = skip_typeref(orig_type_right);
6891 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6892 /* TODO: improve error message */
6893 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6894 errorf(HERE, "operation needs scalar types");
6899 expression->base.type = type_int;
6903 * Check the semantic restrictions of a binary assign expression.
6905 static void semantic_binexpr_assign(binary_expression_t *expression)
6907 expression_t *left = expression->left;
6908 type_t *orig_type_left = left->base.type;
6910 type_t *type_left = revert_automatic_type_conversion(left);
6911 type_left = skip_typeref(orig_type_left);
6913 if (!is_valid_assignment_lhs(left))
6916 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6917 report_assign_error(error, orig_type_left, expression->right,
6918 "assignment", &left->base.source_position);
6919 expression->right = create_implicit_cast(expression->right, orig_type_left);
6920 expression->base.type = orig_type_left;
6924 * Determine if the outermost operation (or parts thereof) of the given
6925 * expression has no effect in order to generate a warning about this fact.
6926 * Therefore in some cases this only examines some of the operands of the
6927 * expression (see comments in the function and examples below).
6929 * f() + 23; // warning, because + has no effect
6930 * x || f(); // no warning, because x controls execution of f()
6931 * x ? y : f(); // warning, because y has no effect
6932 * (void)x; // no warning to be able to suppress the warning
6933 * This function can NOT be used for an "expression has definitely no effect"-
6935 static bool expression_has_effect(const expression_t *const expr)
6937 switch (expr->kind) {
6938 case EXPR_UNKNOWN: break;
6939 case EXPR_INVALID: return true; /* do NOT warn */
6940 case EXPR_REFERENCE: return false;
6941 /* suppress the warning for microsoft __noop operations */
6942 case EXPR_CONST: return expr->conste.is_ms_noop;
6943 case EXPR_CHARACTER_CONSTANT: return false;
6944 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6945 case EXPR_STRING_LITERAL: return false;
6946 case EXPR_WIDE_STRING_LITERAL: return false;
6949 const call_expression_t *const call = &expr->call;
6950 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6953 switch (call->function->builtin_symbol.symbol->ID) {
6954 case T___builtin_va_end: return true;
6955 default: return false;
6959 /* Generate the warning if either the left or right hand side of a
6960 * conditional expression has no effect */
6961 case EXPR_CONDITIONAL: {
6962 const conditional_expression_t *const cond = &expr->conditional;
6964 expression_has_effect(cond->true_expression) &&
6965 expression_has_effect(cond->false_expression);
6968 case EXPR_SELECT: return false;
6969 case EXPR_ARRAY_ACCESS: return false;
6970 case EXPR_SIZEOF: return false;
6971 case EXPR_CLASSIFY_TYPE: return false;
6972 case EXPR_ALIGNOF: return false;
6974 case EXPR_FUNCNAME: return false;
6975 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6976 case EXPR_BUILTIN_CONSTANT_P: return false;
6977 case EXPR_BUILTIN_PREFETCH: return true;
6978 case EXPR_OFFSETOF: return false;
6979 case EXPR_VA_START: return true;
6980 case EXPR_VA_ARG: return true;
6981 case EXPR_STATEMENT: return true; // TODO
6982 case EXPR_COMPOUND_LITERAL: return false;
6984 case EXPR_UNARY_NEGATE: return false;
6985 case EXPR_UNARY_PLUS: return false;
6986 case EXPR_UNARY_BITWISE_NEGATE: return false;
6987 case EXPR_UNARY_NOT: return false;
6988 case EXPR_UNARY_DEREFERENCE: return false;
6989 case EXPR_UNARY_TAKE_ADDRESS: return false;
6990 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6991 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6992 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6993 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6995 /* Treat void casts as if they have an effect in order to being able to
6996 * suppress the warning */
6997 case EXPR_UNARY_CAST: {
6998 type_t *const type = skip_typeref(expr->base.type);
6999 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7002 case EXPR_UNARY_CAST_IMPLICIT: return true;
7003 case EXPR_UNARY_ASSUME: return true;
7005 case EXPR_BINARY_ADD: return false;
7006 case EXPR_BINARY_SUB: return false;
7007 case EXPR_BINARY_MUL: return false;
7008 case EXPR_BINARY_DIV: return false;
7009 case EXPR_BINARY_MOD: return false;
7010 case EXPR_BINARY_EQUAL: return false;
7011 case EXPR_BINARY_NOTEQUAL: return false;
7012 case EXPR_BINARY_LESS: return false;
7013 case EXPR_BINARY_LESSEQUAL: return false;
7014 case EXPR_BINARY_GREATER: return false;
7015 case EXPR_BINARY_GREATEREQUAL: return false;
7016 case EXPR_BINARY_BITWISE_AND: return false;
7017 case EXPR_BINARY_BITWISE_OR: return false;
7018 case EXPR_BINARY_BITWISE_XOR: return false;
7019 case EXPR_BINARY_SHIFTLEFT: return false;
7020 case EXPR_BINARY_SHIFTRIGHT: return false;
7021 case EXPR_BINARY_ASSIGN: return true;
7022 case EXPR_BINARY_MUL_ASSIGN: return true;
7023 case EXPR_BINARY_DIV_ASSIGN: return true;
7024 case EXPR_BINARY_MOD_ASSIGN: return true;
7025 case EXPR_BINARY_ADD_ASSIGN: return true;
7026 case EXPR_BINARY_SUB_ASSIGN: return true;
7027 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7028 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7029 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7030 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7031 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7033 /* Only examine the right hand side of && and ||, because the left hand
7034 * side already has the effect of controlling the execution of the right
7036 case EXPR_BINARY_LOGICAL_AND:
7037 case EXPR_BINARY_LOGICAL_OR:
7038 /* Only examine the right hand side of a comma expression, because the left
7039 * hand side has a separate warning */
7040 case EXPR_BINARY_COMMA:
7041 return expression_has_effect(expr->binary.right);
7043 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7044 case EXPR_BINARY_ISGREATER: return false;
7045 case EXPR_BINARY_ISGREATEREQUAL: return false;
7046 case EXPR_BINARY_ISLESS: return false;
7047 case EXPR_BINARY_ISLESSEQUAL: return false;
7048 case EXPR_BINARY_ISLESSGREATER: return false;
7049 case EXPR_BINARY_ISUNORDERED: return false;
7052 internal_errorf(HERE, "unexpected expression");
7055 static void semantic_comma(binary_expression_t *expression)
7057 if (warning.unused_value) {
7058 const expression_t *const left = expression->left;
7059 if (!expression_has_effect(left)) {
7060 warningf(&left->base.source_position,
7061 "left-hand operand of comma expression has no effect");
7064 expression->base.type = expression->right->base.type;
7067 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7068 static expression_t *parse_##binexpression_type(unsigned precedence, \
7069 expression_t *left) \
7072 source_position_t pos = *HERE; \
7074 expression_t *right = parse_sub_expression(precedence + lr); \
7076 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7077 binexpr->base.source_position = pos; \
7078 binexpr->binary.left = left; \
7079 binexpr->binary.right = right; \
7080 sfunc(&binexpr->binary); \
7085 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7086 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7087 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7088 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7089 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7090 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7091 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7092 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7093 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7095 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7096 semantic_comparison, 1)
7097 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7098 semantic_comparison, 1)
7099 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7100 semantic_comparison, 1)
7101 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7102 semantic_comparison, 1)
7104 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7105 semantic_binexpr_arithmetic, 1)
7106 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7107 semantic_binexpr_arithmetic, 1)
7108 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7109 semantic_binexpr_arithmetic, 1)
7110 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7111 semantic_logical_op, 1)
7112 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7113 semantic_logical_op, 1)
7114 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7115 semantic_shift_op, 1)
7116 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7117 semantic_shift_op, 1)
7118 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7119 semantic_arithmetic_addsubb_assign, 0)
7120 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7121 semantic_arithmetic_addsubb_assign, 0)
7122 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7123 semantic_arithmetic_assign, 0)
7124 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7125 semantic_arithmetic_assign, 0)
7126 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7127 semantic_arithmetic_assign, 0)
7128 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7129 semantic_arithmetic_assign, 0)
7130 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7131 semantic_arithmetic_assign, 0)
7132 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7133 semantic_arithmetic_assign, 0)
7134 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7135 semantic_arithmetic_assign, 0)
7136 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7137 semantic_arithmetic_assign, 0)
7139 static expression_t *parse_sub_expression(unsigned precedence)
7141 if(token.type < 0) {
7142 return expected_expression_error();
7145 expression_parser_function_t *parser
7146 = &expression_parsers[token.type];
7147 source_position_t source_position = token.source_position;
7150 if(parser->parser != NULL) {
7151 left = parser->parser(parser->precedence);
7153 left = parse_primary_expression();
7155 assert(left != NULL);
7156 left->base.source_position = source_position;
7159 if(token.type < 0) {
7160 return expected_expression_error();
7163 parser = &expression_parsers[token.type];
7164 if(parser->infix_parser == NULL)
7166 if(parser->infix_precedence < precedence)
7169 left = parser->infix_parser(parser->infix_precedence, left);
7171 assert(left != NULL);
7172 assert(left->kind != EXPR_UNKNOWN);
7173 left->base.source_position = source_position;
7180 * Parse an expression.
7182 static expression_t *parse_expression(void)
7184 return parse_sub_expression(1);
7188 * Register a parser for a prefix-like operator with given precedence.
7190 * @param parser the parser function
7191 * @param token_type the token type of the prefix token
7192 * @param precedence the precedence of the operator
7194 static void register_expression_parser(parse_expression_function parser,
7195 int token_type, unsigned precedence)
7197 expression_parser_function_t *entry = &expression_parsers[token_type];
7199 if(entry->parser != NULL) {
7200 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7201 panic("trying to register multiple expression parsers for a token");
7203 entry->parser = parser;
7204 entry->precedence = precedence;
7208 * Register a parser for an infix operator with given precedence.
7210 * @param parser the parser function
7211 * @param token_type the token type of the infix operator
7212 * @param precedence the precedence of the operator
7214 static void register_infix_parser(parse_expression_infix_function parser,
7215 int token_type, unsigned precedence)
7217 expression_parser_function_t *entry = &expression_parsers[token_type];
7219 if(entry->infix_parser != NULL) {
7220 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7221 panic("trying to register multiple infix expression parsers for a "
7224 entry->infix_parser = parser;
7225 entry->infix_precedence = precedence;
7229 * Initialize the expression parsers.
7231 static void init_expression_parsers(void)
7233 memset(&expression_parsers, 0, sizeof(expression_parsers));
7235 register_infix_parser(parse_array_expression, '[', 30);
7236 register_infix_parser(parse_call_expression, '(', 30);
7237 register_infix_parser(parse_select_expression, '.', 30);
7238 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7239 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7241 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7244 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7245 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7246 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7247 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7248 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7249 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7250 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7251 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7252 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7253 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7254 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7255 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7256 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7257 T_EXCLAMATIONMARKEQUAL, 13);
7258 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7259 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7260 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7261 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7262 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7263 register_infix_parser(parse_conditional_expression, '?', 7);
7264 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7265 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7266 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7267 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7268 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7269 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7270 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7271 T_LESSLESSEQUAL, 2);
7272 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7273 T_GREATERGREATEREQUAL, 2);
7274 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7276 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7278 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7281 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7283 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7284 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7285 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7286 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7287 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7288 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7289 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7291 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7293 register_expression_parser(parse_sizeof, T_sizeof, 25);
7294 register_expression_parser(parse_alignof, T___alignof__, 25);
7295 register_expression_parser(parse_extension, T___extension__, 25);
7296 register_expression_parser(parse_builtin_classify_type,
7297 T___builtin_classify_type, 25);
7301 * Parse a asm statement arguments specification.
7303 static asm_argument_t *parse_asm_arguments(bool is_out)
7305 asm_argument_t *result = NULL;
7306 asm_argument_t *last = NULL;
7308 while (token.type == T_STRING_LITERAL || token.type == '[') {
7309 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7310 memset(argument, 0, sizeof(argument[0]));
7312 if (token.type == '[') {
7314 if (token.type != T_IDENTIFIER) {
7315 parse_error_expected("while parsing asm argument",
7316 T_IDENTIFIER, NULL);
7319 argument->symbol = token.v.symbol;
7324 argument->constraints = parse_string_literals();
7326 expression_t *expression = parse_expression();
7327 argument->expression = expression;
7328 if (is_out && !is_lvalue(expression)) {
7329 errorf(&expression->base.source_position,
7330 "asm output argument is not an lvalue");
7334 set_address_taken(expression, true);
7337 last->next = argument;
7343 if (token.type != ',')
7354 * Parse a asm statement clobber specification.
7356 static asm_clobber_t *parse_asm_clobbers(void)
7358 asm_clobber_t *result = NULL;
7359 asm_clobber_t *last = NULL;
7361 while(token.type == T_STRING_LITERAL) {
7362 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7363 clobber->clobber = parse_string_literals();
7366 last->next = clobber;
7372 if(token.type != ',')
7381 * Parse an asm statement.
7383 static statement_t *parse_asm_statement(void)
7387 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7388 statement->base.source_position = token.source_position;
7390 asm_statement_t *asm_statement = &statement->asms;
7392 if(token.type == T_volatile) {
7394 asm_statement->is_volatile = true;
7398 add_anchor_token(')');
7399 add_anchor_token(':');
7400 asm_statement->asm_text = parse_string_literals();
7402 if(token.type != ':') {
7403 rem_anchor_token(':');
7408 asm_statement->outputs = parse_asm_arguments(true);
7409 if(token.type != ':') {
7410 rem_anchor_token(':');
7415 asm_statement->inputs = parse_asm_arguments(false);
7416 if(token.type != ':') {
7417 rem_anchor_token(':');
7420 rem_anchor_token(':');
7423 asm_statement->clobbers = parse_asm_clobbers();
7426 rem_anchor_token(')');
7431 return create_invalid_statement();
7435 * Parse a case statement.
7437 static statement_t *parse_case_statement(void)
7441 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7443 statement->base.source_position = token.source_position;
7444 statement->case_label.expression = parse_expression();
7446 if (c_mode & _GNUC) {
7447 if (token.type == T_DOTDOTDOT) {
7449 statement->case_label.end_range = parse_expression();
7455 if (! is_constant_expression(statement->case_label.expression)) {
7456 errorf(&statement->base.source_position,
7457 "case label does not reduce to an integer constant");
7459 /* TODO: check if the case label is already known */
7460 if (current_switch != NULL) {
7461 /* link all cases into the switch statement */
7462 if (current_switch->last_case == NULL) {
7463 current_switch->first_case =
7464 current_switch->last_case = &statement->case_label;
7466 current_switch->last_case->next = &statement->case_label;
7469 errorf(&statement->base.source_position,
7470 "case label not within a switch statement");
7473 statement->case_label.statement = parse_statement();
7477 return create_invalid_statement();
7481 * Finds an existing default label of a switch statement.
7483 static case_label_statement_t *
7484 find_default_label(const switch_statement_t *statement)
7486 case_label_statement_t *label = statement->first_case;
7487 for ( ; label != NULL; label = label->next) {
7488 if (label->expression == NULL)
7495 * Parse a default statement.
7497 static statement_t *parse_default_statement(void)
7501 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7503 statement->base.source_position = token.source_position;
7506 if (current_switch != NULL) {
7507 const case_label_statement_t *def_label = find_default_label(current_switch);
7508 if (def_label != NULL) {
7509 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7510 &def_label->base.source_position);
7512 /* link all cases into the switch statement */
7513 if (current_switch->last_case == NULL) {
7514 current_switch->first_case =
7515 current_switch->last_case = &statement->case_label;
7517 current_switch->last_case->next = &statement->case_label;
7521 errorf(&statement->base.source_position,
7522 "'default' label not within a switch statement");
7524 statement->case_label.statement = parse_statement();
7528 return create_invalid_statement();
7532 * Return the declaration for a given label symbol or create a new one.
7534 static declaration_t *get_label(symbol_t *symbol)
7536 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7537 assert(current_function != NULL);
7538 /* if we found a label in the same function, then we already created the
7540 if(candidate != NULL
7541 && candidate->parent_scope == ¤t_function->scope) {
7545 /* otherwise we need to create a new one */
7546 declaration_t *const declaration = allocate_declaration_zero();
7547 declaration->namespc = NAMESPACE_LABEL;
7548 declaration->symbol = symbol;
7550 label_push(declaration);
7556 * Parse a label statement.
7558 static statement_t *parse_label_statement(void)
7560 assert(token.type == T_IDENTIFIER);
7561 symbol_t *symbol = token.v.symbol;
7564 declaration_t *label = get_label(symbol);
7566 /* if source position is already set then the label is defined twice,
7567 * otherwise it was just mentioned in a goto so far */
7568 if(label->source_position.input_name != NULL) {
7569 errorf(HERE, "duplicate label '%Y' (declared %P)",
7570 symbol, &label->source_position);
7572 label->source_position = token.source_position;
7575 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7577 statement->base.source_position = token.source_position;
7578 statement->label.label = label;
7582 if(token.type == '}') {
7583 /* TODO only warn? */
7585 warningf(HERE, "label at end of compound statement");
7586 statement->label.statement = create_empty_statement();
7588 errorf(HERE, "label at end of compound statement");
7589 statement->label.statement = create_invalid_statement();
7593 if (token.type == ';') {
7594 /* eat an empty statement here, to avoid the warning about an empty
7595 * after a label. label:; is commonly used to have a label before
7597 statement->label.statement = create_empty_statement();
7600 statement->label.statement = parse_statement();
7604 /* remember the labels's in a list for later checking */
7605 if (label_last == NULL) {
7606 label_first = &statement->label;
7608 label_last->next = &statement->label;
7610 label_last = &statement->label;
7616 * Parse an if statement.
7618 static statement_t *parse_if(void)
7622 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7623 statement->base.source_position = token.source_position;
7626 add_anchor_token(')');
7627 statement->ifs.condition = parse_expression();
7628 rem_anchor_token(')');
7631 add_anchor_token(T_else);
7632 statement->ifs.true_statement = parse_statement();
7633 rem_anchor_token(T_else);
7635 if(token.type == T_else) {
7637 statement->ifs.false_statement = parse_statement();
7642 return create_invalid_statement();
7646 * Parse a switch statement.
7648 static statement_t *parse_switch(void)
7652 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7653 statement->base.source_position = token.source_position;
7656 expression_t *const expr = parse_expression();
7657 type_t * type = skip_typeref(expr->base.type);
7658 if (is_type_integer(type)) {
7659 type = promote_integer(type);
7660 } else if (is_type_valid(type)) {
7661 errorf(&expr->base.source_position,
7662 "switch quantity is not an integer, but '%T'", type);
7663 type = type_error_type;
7665 statement->switchs.expression = create_implicit_cast(expr, type);
7668 switch_statement_t *rem = current_switch;
7669 current_switch = &statement->switchs;
7670 statement->switchs.body = parse_statement();
7671 current_switch = rem;
7673 if(warning.switch_default &&
7674 find_default_label(&statement->switchs) == NULL) {
7675 warningf(&statement->base.source_position, "switch has no default case");
7680 return create_invalid_statement();
7683 static statement_t *parse_loop_body(statement_t *const loop)
7685 statement_t *const rem = current_loop;
7686 current_loop = loop;
7688 statement_t *const body = parse_statement();
7695 * Parse a while statement.
7697 static statement_t *parse_while(void)
7701 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7702 statement->base.source_position = token.source_position;
7705 add_anchor_token(')');
7706 statement->whiles.condition = parse_expression();
7707 rem_anchor_token(')');
7710 statement->whiles.body = parse_loop_body(statement);
7714 return create_invalid_statement();
7718 * Parse a do statement.
7720 static statement_t *parse_do(void)
7724 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7726 statement->base.source_position = token.source_position;
7728 add_anchor_token(T_while);
7729 statement->do_while.body = parse_loop_body(statement);
7730 rem_anchor_token(T_while);
7734 add_anchor_token(')');
7735 statement->do_while.condition = parse_expression();
7736 rem_anchor_token(')');
7742 return create_invalid_statement();
7746 * Parse a for statement.
7748 static statement_t *parse_for(void)
7752 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7753 statement->base.source_position = token.source_position;
7755 int top = environment_top();
7756 scope_t *last_scope = scope;
7757 set_scope(&statement->fors.scope);
7760 add_anchor_token(')');
7762 if(token.type != ';') {
7763 if(is_declaration_specifier(&token, false)) {
7764 parse_declaration(record_declaration);
7766 add_anchor_token(';');
7767 expression_t *const init = parse_expression();
7768 statement->fors.initialisation = init;
7769 if (warning.unused_value && !expression_has_effect(init)) {
7770 warningf(&init->base.source_position,
7771 "initialisation of 'for'-statement has no effect");
7773 rem_anchor_token(';');
7780 if(token.type != ';') {
7781 add_anchor_token(';');
7782 statement->fors.condition = parse_expression();
7783 rem_anchor_token(';');
7786 if(token.type != ')') {
7787 expression_t *const step = parse_expression();
7788 statement->fors.step = step;
7789 if (warning.unused_value && !expression_has_effect(step)) {
7790 warningf(&step->base.source_position,
7791 "step of 'for'-statement has no effect");
7794 rem_anchor_token(')');
7796 statement->fors.body = parse_loop_body(statement);
7798 assert(scope == &statement->fors.scope);
7799 set_scope(last_scope);
7800 environment_pop_to(top);
7805 rem_anchor_token(')');
7806 assert(scope == &statement->fors.scope);
7807 set_scope(last_scope);
7808 environment_pop_to(top);
7810 return create_invalid_statement();
7814 * Parse a goto statement.
7816 static statement_t *parse_goto(void)
7820 if(token.type != T_IDENTIFIER) {
7821 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7825 symbol_t *symbol = token.v.symbol;
7828 declaration_t *label = get_label(symbol);
7830 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7831 statement->base.source_position = token.source_position;
7833 statement->gotos.label = label;
7835 /* remember the goto's in a list for later checking */
7836 if (goto_last == NULL) {
7837 goto_first = &statement->gotos;
7839 goto_last->next = &statement->gotos;
7841 goto_last = &statement->gotos;
7847 return create_invalid_statement();
7851 * Parse a continue statement.
7853 static statement_t *parse_continue(void)
7855 statement_t *statement;
7856 if (current_loop == NULL) {
7857 errorf(HERE, "continue statement not within loop");
7858 statement = create_invalid_statement();
7860 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7862 statement->base.source_position = token.source_position;
7870 return create_invalid_statement();
7874 * Parse a break statement.
7876 static statement_t *parse_break(void)
7878 statement_t *statement;
7879 if (current_switch == NULL && current_loop == NULL) {
7880 errorf(HERE, "break statement not within loop or switch");
7881 statement = create_invalid_statement();
7883 statement = allocate_statement_zero(STATEMENT_BREAK);
7885 statement->base.source_position = token.source_position;
7893 return create_invalid_statement();
7897 * Parse a __leave statement.
7899 static statement_t *parse_leave(void)
7901 statement_t *statement;
7902 if (current_try == NULL) {
7903 errorf(HERE, "__leave statement not within __try");
7904 statement = create_invalid_statement();
7906 statement = allocate_statement_zero(STATEMENT_LEAVE);
7908 statement->base.source_position = token.source_position;
7916 return create_invalid_statement();
7920 * Check if a given declaration represents a local variable.
7922 static bool is_local_var_declaration(const declaration_t *declaration) {
7923 switch ((storage_class_tag_t) declaration->storage_class) {
7924 case STORAGE_CLASS_AUTO:
7925 case STORAGE_CLASS_REGISTER: {
7926 const type_t *type = skip_typeref(declaration->type);
7927 if(is_type_function(type)) {
7939 * Check if a given declaration represents a variable.
7941 static bool is_var_declaration(const declaration_t *declaration) {
7942 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7945 const type_t *type = skip_typeref(declaration->type);
7946 return !is_type_function(type);
7950 * Check if a given expression represents a local variable.
7952 static bool is_local_variable(const expression_t *expression)
7954 if (expression->base.kind != EXPR_REFERENCE) {
7957 const declaration_t *declaration = expression->reference.declaration;
7958 return is_local_var_declaration(declaration);
7962 * Check if a given expression represents a local variable and
7963 * return its declaration then, else return NULL.
7965 declaration_t *expr_is_variable(const expression_t *expression)
7967 if (expression->base.kind != EXPR_REFERENCE) {
7970 declaration_t *declaration = expression->reference.declaration;
7971 if (is_var_declaration(declaration))
7977 * Parse a return statement.
7979 static statement_t *parse_return(void)
7981 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7982 statement->base.source_position = token.source_position;
7986 expression_t *return_value = NULL;
7987 if(token.type != ';') {
7988 return_value = parse_expression();
7992 const type_t *const func_type = current_function->type;
7993 assert(is_type_function(func_type));
7994 type_t *const return_type = skip_typeref(func_type->function.return_type);
7996 if(return_value != NULL) {
7997 type_t *return_value_type = skip_typeref(return_value->base.type);
7999 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8000 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8001 warningf(&statement->base.source_position,
8002 "'return' with a value, in function returning void");
8003 return_value = NULL;
8005 assign_error_t error = semantic_assign(return_type, return_value);
8006 report_assign_error(error, return_type, return_value, "'return'",
8007 &statement->base.source_position);
8008 return_value = create_implicit_cast(return_value, return_type);
8010 /* check for returning address of a local var */
8011 if (return_value != NULL &&
8012 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8013 const expression_t *expression = return_value->unary.value;
8014 if (is_local_variable(expression)) {
8015 warningf(&statement->base.source_position,
8016 "function returns address of local variable");
8020 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8021 warningf(&statement->base.source_position,
8022 "'return' without value, in function returning non-void");
8025 statement->returns.value = return_value;
8029 return create_invalid_statement();
8033 * Parse a declaration statement.
8035 static statement_t *parse_declaration_statement(void)
8037 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8039 statement->base.source_position = token.source_position;
8041 declaration_t *before = last_declaration;
8042 parse_declaration(record_declaration);
8044 if(before == NULL) {
8045 statement->declaration.declarations_begin = scope->declarations;
8047 statement->declaration.declarations_begin = before->next;
8049 statement->declaration.declarations_end = last_declaration;
8055 * Parse an expression statement, ie. expr ';'.
8057 static statement_t *parse_expression_statement(void)
8059 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8061 statement->base.source_position = token.source_position;
8062 expression_t *const expr = parse_expression();
8063 statement->expression.expression = expr;
8069 return create_invalid_statement();
8073 * Parse a microsoft __try { } __finally { } or
8074 * __try{ } __except() { }
8076 static statement_t *parse_ms_try_statment(void) {
8077 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8079 statement->base.source_position = token.source_position;
8082 ms_try_statement_t *rem = current_try;
8083 current_try = &statement->ms_try;
8084 statement->ms_try.try_statement = parse_compound_statement(false);
8087 if(token.type == T___except) {
8090 add_anchor_token(')');
8091 expression_t *const expr = parse_expression();
8092 type_t * type = skip_typeref(expr->base.type);
8093 if (is_type_integer(type)) {
8094 type = promote_integer(type);
8095 } else if (is_type_valid(type)) {
8096 errorf(&expr->base.source_position,
8097 "__expect expression is not an integer, but '%T'", type);
8098 type = type_error_type;
8100 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8101 rem_anchor_token(')');
8103 statement->ms_try.final_statement = parse_compound_statement(false);
8104 } else if(token.type == T__finally) {
8106 statement->ms_try.final_statement = parse_compound_statement(false);
8108 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8109 return create_invalid_statement();
8113 return create_invalid_statement();
8117 * Parse a statement.
8118 * There's also parse_statement() which additionally checks for
8119 * "statement has no effect" warnings
8121 static statement_t *intern_parse_statement(void)
8123 statement_t *statement = NULL;
8125 /* declaration or statement */
8126 add_anchor_token(';');
8127 switch(token.type) {
8129 statement = parse_asm_statement();
8133 statement = parse_case_statement();
8137 statement = parse_default_statement();
8141 statement = parse_compound_statement(false);
8145 statement = parse_if();
8149 statement = parse_switch();
8153 statement = parse_while();
8157 statement = parse_do();
8161 statement = parse_for();
8165 statement = parse_goto();
8169 statement = parse_continue();
8173 statement = parse_break();
8177 statement = parse_leave();
8181 statement = parse_return();
8185 if(warning.empty_statement) {
8186 warningf(HERE, "statement is empty");
8188 statement = create_empty_statement();
8193 if(look_ahead(1)->type == ':') {
8194 statement = parse_label_statement();
8198 if(is_typedef_symbol(token.v.symbol)) {
8199 statement = parse_declaration_statement();
8203 statement = parse_expression_statement();
8206 case T___extension__:
8207 /* this can be a prefix to a declaration or an expression statement */
8208 /* we simply eat it now and parse the rest with tail recursion */
8211 } while(token.type == T___extension__);
8212 statement = parse_statement();
8216 statement = parse_declaration_statement();
8220 statement = parse_ms_try_statment();
8224 statement = parse_expression_statement();
8227 rem_anchor_token(';');
8229 assert(statement != NULL
8230 && statement->base.source_position.input_name != NULL);
8236 * parse a statement and emits "statement has no effect" warning if needed
8237 * (This is really a wrapper around intern_parse_statement with check for 1
8238 * single warning. It is needed, because for statement expressions we have
8239 * to avoid the warning on the last statement)
8241 static statement_t *parse_statement(void)
8243 statement_t *statement = intern_parse_statement();
8245 if(statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8246 expression_t *expression = statement->expression.expression;
8247 if(!expression_has_effect(expression)) {
8248 warningf(&expression->base.source_position,
8249 "statement has no effect");
8257 * Parse a compound statement.
8259 static statement_t *parse_compound_statement(bool inside_expression_statement)
8261 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8263 statement->base.source_position = token.source_position;
8266 add_anchor_token('}');
8268 int top = environment_top();
8269 scope_t *last_scope = scope;
8270 set_scope(&statement->compound.scope);
8272 statement_t *last_statement = NULL;
8274 while(token.type != '}' && token.type != T_EOF) {
8275 statement_t *sub_statement = intern_parse_statement();
8276 if(is_invalid_statement(sub_statement)) {
8277 /* an error occurred. if we are at an anchor, return */
8283 if(last_statement != NULL) {
8284 last_statement->base.next = sub_statement;
8286 statement->compound.statements = sub_statement;
8289 while(sub_statement->base.next != NULL)
8290 sub_statement = sub_statement->base.next;
8292 last_statement = sub_statement;
8295 if(token.type == '}') {
8298 errorf(&statement->base.source_position,
8299 "end of file while looking for closing '}'");
8302 /* look over all statements again to produce no effect warnings */
8303 if(warning.unused_value) {
8304 statement_t *sub_statement = statement->compound.statements;
8305 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8306 if(sub_statement->kind != STATEMENT_EXPRESSION)
8308 /* don't emit a warning for the last expression in an expression
8309 * statement as it has always an effect */
8310 if(inside_expression_statement && sub_statement->base.next == NULL)
8313 expression_t *expression = sub_statement->expression.expression;
8314 if(!expression_has_effect(expression)) {
8315 warningf(&expression->base.source_position,
8316 "statement has no effect");
8322 rem_anchor_token('}');
8323 assert(scope == &statement->compound.scope);
8324 set_scope(last_scope);
8325 environment_pop_to(top);
8331 * Initialize builtin types.
8333 static void initialize_builtin_types(void)
8335 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8336 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8337 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8338 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8339 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8340 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8341 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8342 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8344 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8345 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8346 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8347 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8351 * Check for unused global static functions and variables
8353 static void check_unused_globals(void)
8355 if (!warning.unused_function && !warning.unused_variable)
8358 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8359 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
8362 type_t *const type = decl->type;
8364 if (is_type_function(skip_typeref(type))) {
8365 if (!warning.unused_function || decl->is_inline)
8368 s = (decl->init.statement != NULL ? "defined" : "declared");
8370 if (!warning.unused_variable)
8376 warningf(&decl->source_position, "'%#T' %s but not used",
8377 type, decl->symbol, s);
8382 * Parse a translation unit.
8384 static void parse_translation_unit(void)
8386 while(token.type != T_EOF) {
8387 if (token.type == ';') {
8388 /* TODO error in strict mode */
8389 warningf(HERE, "stray ';' outside of function");
8392 parse_external_declaration();
8400 * @return the translation unit or NULL if errors occurred.
8402 void start_parsing(void)
8404 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8405 label_stack = NEW_ARR_F(stack_entry_t, 0);
8406 diagnostic_count = 0;
8410 type_set_output(stderr);
8411 ast_set_output(stderr);
8413 assert(unit == NULL);
8414 unit = allocate_ast_zero(sizeof(unit[0]));
8416 assert(global_scope == NULL);
8417 global_scope = &unit->scope;
8419 assert(scope == NULL);
8420 set_scope(&unit->scope);
8422 initialize_builtin_types();
8425 translation_unit_t *finish_parsing(void)
8427 assert(scope == &unit->scope);
8429 last_declaration = NULL;
8431 assert(global_scope == &unit->scope);
8432 check_unused_globals();
8433 global_scope = NULL;
8435 DEL_ARR_F(environment_stack);
8436 DEL_ARR_F(label_stack);
8438 translation_unit_t *result = unit;
8445 lookahead_bufpos = 0;
8446 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8449 parse_translation_unit();
8453 * Initialize the parser.
8455 void init_parser(void)
8458 /* add predefined symbols for extended-decl-modifier */
8459 sym_align = symbol_table_insert("align");
8460 sym_allocate = symbol_table_insert("allocate");
8461 sym_dllimport = symbol_table_insert("dllimport");
8462 sym_dllexport = symbol_table_insert("dllexport");
8463 sym_naked = symbol_table_insert("naked");
8464 sym_noinline = symbol_table_insert("noinline");
8465 sym_noreturn = symbol_table_insert("noreturn");
8466 sym_nothrow = symbol_table_insert("nothrow");
8467 sym_novtable = symbol_table_insert("novtable");
8468 sym_property = symbol_table_insert("property");
8469 sym_get = symbol_table_insert("get");
8470 sym_put = symbol_table_insert("put");
8471 sym_selectany = symbol_table_insert("selectany");
8472 sym_thread = symbol_table_insert("thread");
8473 sym_uuid = symbol_table_insert("uuid");
8474 sym_deprecated = symbol_table_insert("deprecated");
8475 sym_restrict = symbol_table_insert("restrict");
8476 sym_noalias = symbol_table_insert("noalias");
8478 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8480 init_expression_parsers();
8481 obstack_init(&temp_obst);
8483 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8484 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8488 * Terminate the parser.
8490 void exit_parser(void)
8492 obstack_free(&temp_obst, NULL);