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] = "coommon",
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 len = strlen(s2);
1130 if(s2[len-2] == '_' && s2[len-1] == '_') {
1131 return strncmp(s1, s2+2, len-4);
1135 return strcmp(s1, s2);
1139 * Allocate a new gnu temporal attribute.
1141 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1142 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1143 attribute->kind = kind;
1144 attribute->next = NULL;
1145 attribute->invalid = false;
1146 attribute->have_arguments = false;
1152 * parse one constant expression argument.
1154 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1155 expression_t *expression;
1156 add_anchor_token(')');
1157 expression = parse_constant_expression();
1158 rem_anchor_token(')');
1163 attribute->invalid = true;
1167 * parse a list of constant expressions arguments.
1169 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1170 expression_t *expression;
1171 add_anchor_token(')');
1172 add_anchor_token(',');
1174 expression = parse_constant_expression();
1175 if(token.type != ',')
1179 rem_anchor_token(',');
1180 rem_anchor_token(')');
1185 attribute->invalid = true;
1189 * parse one string literal argument.
1191 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1194 add_anchor_token('(');
1195 if(token.type != T_STRING_LITERAL) {
1196 parse_error_expected("while parsing attribute directive",
1197 T_STRING_LITERAL, NULL);
1200 *string = parse_string_literals();
1201 rem_anchor_token('(');
1205 attribute->invalid = true;
1209 * parse one tls model.
1211 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1212 static const char *tls_models[] = {
1218 string_t string = { NULL, 0 };
1219 parse_gnu_attribute_string_arg(attribute, &string);
1220 if(string.begin != NULL) {
1221 for(size_t i = 0; i < 4; ++i) {
1222 if(strcmp(tls_models[i], string.begin) == 0) {
1223 attribute->u.value = i;
1227 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1229 attribute->invalid = true;
1233 * parse one tls model.
1235 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1236 static const char *visibilities[] = {
1242 string_t string = { NULL, 0 };
1243 parse_gnu_attribute_string_arg(attribute, &string);
1244 if(string.begin != NULL) {
1245 for(size_t i = 0; i < 4; ++i) {
1246 if(strcmp(visibilities[i], string.begin) == 0) {
1247 attribute->u.value = i;
1251 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1253 attribute->invalid = true;
1257 * parse one (code) model.
1259 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1260 static const char *visibilities[] = {
1265 string_t string = { NULL, 0 };
1266 parse_gnu_attribute_string_arg(attribute, &string);
1267 if(string.begin != NULL) {
1268 for(int i = 0; i < 3; ++i) {
1269 if(strcmp(visibilities[i], string.begin) == 0) {
1270 attribute->u.value = i;
1274 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1276 attribute->invalid = true;
1279 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1281 /* TODO: find out what is allowed here... */
1283 /* at least: byte, word, pointer, list of machine modes
1284 * __XXX___ is interpreted as XXX */
1285 add_anchor_token(')');
1286 expect(T_IDENTIFIER);
1287 rem_anchor_token(')');
1291 attribute->invalid = true;
1295 * parse one interrupt argument.
1297 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1298 static const char *interrupts[] = {
1305 string_t string = { NULL, 0 };
1306 parse_gnu_attribute_string_arg(attribute, &string);
1307 if(string.begin != NULL) {
1308 for(size_t i = 0; i < 5; ++i) {
1309 if(strcmp(interrupts[i], string.begin) == 0) {
1310 attribute->u.value = i;
1314 errorf(HERE, "'%s' is not an interrupt", string.begin);
1316 attribute->invalid = true;
1320 * parse ( identifier, const expression, const expression )
1322 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1323 static const char *format_names[] = {
1331 if(token.type != T_IDENTIFIER) {
1332 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1335 const char *name = token.v.symbol->string;
1336 for(i = 0; i < 4; ++i) {
1337 if(strcmp_underscore(format_names[i], name) == 0)
1341 if(warning.attribute)
1342 warningf(HERE, "'%s' is an unrecognized format function type", name);
1347 add_anchor_token(')');
1348 add_anchor_token(',');
1349 parse_constant_expression();
1350 rem_anchor_token(',');
1351 rem_anchor_token('(');
1354 add_anchor_token(')');
1355 parse_constant_expression();
1356 rem_anchor_token('(');
1360 attribute->u.value = true;
1363 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1365 if(!attribute->have_arguments)
1368 /* should have no arguments */
1369 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1370 eat_until_matching_token('(');
1371 /* we have already consumed '(', so we stop before ')', eat it */
1373 attribute->invalid = true;
1377 * Parse one GNU attribute.
1379 * Note that attribute names can be specified WITH or WITHOUT
1380 * double underscores, ie const or __const__.
1382 * The following attributes are parsed without arguments
1407 * no_instrument_function
1408 * warn_unused_result
1425 * externally_visible
1433 * The following attributes are parsed with arguments
1434 * aligned( const expression )
1435 * alias( string literal )
1436 * section( string literal )
1437 * format( identifier, const expression, const expression )
1438 * format_arg( const expression )
1439 * tls_model( string literal )
1440 * visibility( string literal )
1441 * regparm( const expression )
1442 * model( string leteral )
1443 * trap_exit( const expression )
1444 * sp_switch( string literal )
1446 * The following attributes might have arguments
1447 * weak_ref( string literal )
1448 * non_null( const expression // ',' )
1449 * interrupt( string literal )
1450 * sentinel( constant expression )
1452 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1454 gnu_attribute_t *head = *attributes;
1455 gnu_attribute_t *last = *attributes;
1456 decl_modifiers_t modifiers = 0;
1457 gnu_attribute_t *attribute;
1459 eat(T___attribute__);
1463 if(token.type != ')') {
1464 /* find the end of the list */
1466 while(last->next != NULL)
1470 /* non-empty attribute list */
1473 if (token.type == T_const) {
1475 } else if(token.type == T_volatile) {
1477 } else if(token.type == T_cdecl) {
1478 /* __attribute__((cdecl)), WITH ms mode */
1480 } else if (token.type == T_IDENTIFIER) {
1481 const symbol_t *sym = token.v.symbol;
1484 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1491 for(i = 0; i < GNU_AK_LAST; ++i) {
1492 if(strcmp_underscore(gnu_attribute_names[i], name) == 0)
1495 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1498 if(kind == GNU_AK_LAST) {
1499 if(warning.attribute)
1500 warningf(HERE, "'%s' attribute directive ignored", name);
1502 /* skip possible arguments */
1503 if(token.type == '(') {
1504 eat_until_matching_token(')');
1507 /* check for arguments */
1508 attribute = allocate_gnu_attribute(kind);
1509 if(token.type == '(') {
1511 if(token.type == ')') {
1512 /* empty args are allowed */
1515 attribute->have_arguments = true;
1520 case GNU_AK_VOLATILE:
1522 case GNU_AK_STDCALL:
1523 case GNU_AK_FASTCALL:
1524 case GNU_AK_DEPRECATED:
1529 case GNU_AK_NOCOMMON:
1531 case GNU_AK_NOTSHARED:
1534 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1535 case GNU_AK_WARN_UNUSED_RESULT:
1536 case GNU_AK_LONGCALL:
1537 case GNU_AK_SHORTCALL:
1538 case GNU_AK_LONG_CALL:
1539 case GNU_AK_SHORT_CALL:
1540 case GNU_AK_FUNCTION_VECTOR:
1541 case GNU_AK_INTERRUPT_HANDLER:
1542 case GNU_AK_NMI_HANDLER:
1543 case GNU_AK_NESTING:
1547 case GNU_AK_EIGTHBIT_DATA:
1548 case GNU_AK_TINY_DATA:
1549 case GNU_AK_SAVEALL:
1550 case GNU_AK_FLATTEN:
1551 case GNU_AK_SSEREGPARM:
1552 case GNU_AK_EXTERNALLY_VISIBLE:
1553 case GNU_AK_RETURN_TWICE:
1554 case GNU_AK_MAY_ALIAS:
1555 case GNU_AK_MS_STRUCT:
1556 case GNU_AK_GCC_STRUCT:
1557 check_no_argument(attribute, name);
1561 check_no_argument(attribute, name);
1562 modifiers |= DM_PURE;
1565 case GNU_AK_ALWAYS_INLINE:
1566 check_no_argument(attribute, name);
1567 modifiers |= DM_FORCEINLINE;
1570 case GNU_AK_DLLIMPORT:
1571 check_no_argument(attribute, name);
1572 modifiers |= DM_DLLIMPORT;
1575 case GNU_AK_DLLEXPORT:
1576 check_no_argument(attribute, name);
1577 modifiers |= DM_DLLEXPORT;
1581 check_no_argument(attribute, name);
1582 modifiers |= DM_PACKED;
1585 case GNU_AK_NOINLINE:
1586 check_no_argument(attribute, name);
1587 modifiers |= DM_NOINLINE;
1590 case GNU_AK_NORETURN:
1591 check_no_argument(attribute, name);
1592 modifiers |= DM_NORETURN;
1595 case GNU_AK_NOTHROW:
1596 check_no_argument(attribute, name);
1597 modifiers |= DM_NOTHROW;
1600 case GNU_AK_TRANSPARENT_UNION:
1601 check_no_argument(attribute, name);
1602 modifiers |= DM_TRANSPARENT_UNION;
1605 case GNU_AK_CONSTRUCTOR:
1606 check_no_argument(attribute, name);
1607 modifiers |= DM_CONSTRUCTOR;
1610 case GNU_AK_DESTRUCTOR:
1611 check_no_argument(attribute, name);
1612 modifiers |= DM_DESTRUCTOR;
1615 case GNU_AK_ALIGNED:
1616 case GNU_AK_FORMAT_ARG:
1617 case GNU_AK_REGPARM:
1618 case GNU_AK_TRAP_EXIT:
1619 if(!attribute->have_arguments) {
1620 /* should have arguments */
1621 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1622 attribute->invalid = true;
1624 parse_gnu_attribute_const_arg(attribute);
1627 case GNU_AK_SECTION:
1628 case GNU_AK_SP_SWITCH:
1629 if(!attribute->have_arguments) {
1630 /* should have arguments */
1631 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1632 attribute->invalid = true;
1634 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1637 if(!attribute->have_arguments) {
1638 /* should have arguments */
1639 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1640 attribute->invalid = true;
1642 parse_gnu_attribute_format_args(attribute);
1644 case GNU_AK_WEAKREF:
1645 /* may have one string argument */
1646 if(attribute->have_arguments)
1647 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1649 case GNU_AK_NONNULL:
1650 if(attribute->have_arguments)
1651 parse_gnu_attribute_const_arg_list(attribute);
1653 case GNU_AK_TLS_MODEL:
1654 if(!attribute->have_arguments) {
1655 /* should have arguments */
1656 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1658 parse_gnu_attribute_tls_model_arg(attribute);
1660 case GNU_AK_VISIBILITY:
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_visibility_arg(attribute);
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_model_arg(attribute);
1676 if(!attribute->have_arguments) {
1677 /* should have arguments */
1678 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1680 parse_gnu_attribute_mode_arg(attribute);
1683 case GNU_AK_INTERRUPT:
1684 /* may have one string argument */
1685 if(attribute->have_arguments)
1686 parse_gnu_attribute_interrupt_arg(attribute);
1688 case GNU_AK_SENTINEL:
1689 /* may have one string argument */
1690 if(attribute->have_arguments)
1691 parse_gnu_attribute_const_arg(attribute);
1694 /* already handled */
1698 if(attribute != NULL) {
1700 last->next = attribute;
1703 head = last = attribute;
1707 if(token.type != ',')
1721 * Parse GNU attributes.
1723 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1725 decl_modifiers_t modifiers = 0;
1728 switch(token.type) {
1729 case T___attribute__: {
1730 modifiers |= parse_gnu_attribute(attributes);
1736 if(token.type != T_STRING_LITERAL) {
1737 parse_error_expected("while parsing assembler attribute",
1738 T_STRING_LITERAL, NULL);
1739 eat_until_matching_token('(');
1742 parse_string_literals();
1747 goto attributes_finished;
1751 attributes_finished:
1756 static designator_t *parse_designation(void)
1758 designator_t *result = NULL;
1759 designator_t *last = NULL;
1762 designator_t *designator;
1763 switch(token.type) {
1765 designator = allocate_ast_zero(sizeof(designator[0]));
1766 designator->source_position = token.source_position;
1768 add_anchor_token(']');
1769 designator->array_index = parse_constant_expression();
1770 rem_anchor_token(']');
1774 designator = allocate_ast_zero(sizeof(designator[0]));
1775 designator->source_position = token.source_position;
1777 if(token.type != T_IDENTIFIER) {
1778 parse_error_expected("while parsing designator",
1779 T_IDENTIFIER, NULL);
1782 designator->symbol = token.v.symbol;
1790 assert(designator != NULL);
1792 last->next = designator;
1794 result = designator;
1802 static initializer_t *initializer_from_string(array_type_t *type,
1803 const string_t *const string)
1805 /* TODO: check len vs. size of array type */
1808 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1809 initializer->string.string = *string;
1814 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1815 wide_string_t *const string)
1817 /* TODO: check len vs. size of array type */
1820 initializer_t *const initializer =
1821 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1822 initializer->wide_string.string = *string;
1828 * Build an initializer from a given expression.
1830 static initializer_t *initializer_from_expression(type_t *orig_type,
1831 expression_t *expression)
1833 /* TODO check that expression is a constant expression */
1835 /* § 6.7.8.14/15 char array may be initialized by string literals */
1836 type_t *type = skip_typeref(orig_type);
1837 type_t *expr_type_orig = expression->base.type;
1838 type_t *expr_type = skip_typeref(expr_type_orig);
1839 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1840 array_type_t *const array_type = &type->array;
1841 type_t *const element_type = skip_typeref(array_type->element_type);
1843 if (element_type->kind == TYPE_ATOMIC) {
1844 atomic_type_kind_t akind = element_type->atomic.akind;
1845 switch (expression->kind) {
1846 case EXPR_STRING_LITERAL:
1847 if (akind == ATOMIC_TYPE_CHAR
1848 || akind == ATOMIC_TYPE_SCHAR
1849 || akind == ATOMIC_TYPE_UCHAR) {
1850 return initializer_from_string(array_type,
1851 &expression->string.value);
1854 case EXPR_WIDE_STRING_LITERAL: {
1855 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1856 if (get_unqualified_type(element_type) == bare_wchar_type) {
1857 return initializer_from_wide_string(array_type,
1858 &expression->wide_string.value);
1868 assign_error_t error = semantic_assign(type, expression);
1869 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1871 report_assign_error(error, type, expression, "initializer",
1872 &expression->base.source_position);
1874 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1875 result->value.value = create_implicit_cast(expression, type);
1881 * Checks if a given expression can be used as an constant initializer.
1883 static bool is_initializer_constant(const expression_t *expression)
1885 return is_constant_expression(expression)
1886 || is_address_constant(expression);
1890 * Parses an scalar initializer.
1892 * § 6.7.8.11; eat {} without warning
1894 static initializer_t *parse_scalar_initializer(type_t *type,
1895 bool must_be_constant)
1897 /* there might be extra {} hierarchies */
1899 while(token.type == '{') {
1902 warningf(HERE, "extra curly braces around scalar initializer");
1907 expression_t *expression = parse_assignment_expression();
1908 if(must_be_constant && !is_initializer_constant(expression)) {
1909 errorf(&expression->base.source_position,
1910 "Initialisation expression '%E' is not constant\n",
1914 initializer_t *initializer = initializer_from_expression(type, expression);
1916 if(initializer == NULL) {
1917 errorf(&expression->base.source_position,
1918 "expression '%E' (type '%T') doesn't match expected type '%T'",
1919 expression, expression->base.type, type);
1924 bool additional_warning_displayed = false;
1926 if(token.type == ',') {
1929 if(token.type != '}') {
1930 if(!additional_warning_displayed) {
1931 warningf(HERE, "additional elements in scalar initializer");
1932 additional_warning_displayed = true;
1943 * An entry in the type path.
1945 typedef struct type_path_entry_t type_path_entry_t;
1946 struct type_path_entry_t {
1947 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1949 size_t index; /**< For array types: the current index. */
1950 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1955 * A type path expression a position inside compound or array types.
1957 typedef struct type_path_t type_path_t;
1958 struct type_path_t {
1959 type_path_entry_t *path; /**< An flexible array containing the current path. */
1960 type_t *top_type; /**< type of the element the path points */
1961 size_t max_index; /**< largest index in outermost array */
1965 * Prints a type path for debugging.
1967 static __attribute__((unused)) void debug_print_type_path(
1968 const type_path_t *path)
1970 size_t len = ARR_LEN(path->path);
1972 for(size_t i = 0; i < len; ++i) {
1973 const type_path_entry_t *entry = & path->path[i];
1975 type_t *type = skip_typeref(entry->type);
1976 if(is_type_compound(type)) {
1977 /* in gcc mode structs can have no members */
1978 if(entry->v.compound_entry == NULL) {
1982 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1983 } else if(is_type_array(type)) {
1984 fprintf(stderr, "[%zd]", entry->v.index);
1986 fprintf(stderr, "-INVALID-");
1989 if(path->top_type != NULL) {
1990 fprintf(stderr, " (");
1991 print_type(path->top_type);
1992 fprintf(stderr, ")");
1997 * Return the top type path entry, ie. in a path
1998 * (type).a.b returns the b.
2000 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2002 size_t len = ARR_LEN(path->path);
2004 return &path->path[len-1];
2008 * Enlarge the type path by an (empty) element.
2010 static type_path_entry_t *append_to_type_path(type_path_t *path)
2012 size_t len = ARR_LEN(path->path);
2013 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2015 type_path_entry_t *result = & path->path[len];
2016 memset(result, 0, sizeof(result[0]));
2021 * Descending into a sub-type. Enter the scope of the current
2024 static void descend_into_subtype(type_path_t *path)
2026 type_t *orig_top_type = path->top_type;
2027 type_t *top_type = skip_typeref(orig_top_type);
2029 assert(is_type_compound(top_type) || is_type_array(top_type));
2031 type_path_entry_t *top = append_to_type_path(path);
2032 top->type = top_type;
2034 if(is_type_compound(top_type)) {
2035 declaration_t *declaration = top_type->compound.declaration;
2036 declaration_t *entry = declaration->scope.declarations;
2037 top->v.compound_entry = entry;
2040 path->top_type = entry->type;
2042 path->top_type = NULL;
2045 assert(is_type_array(top_type));
2048 path->top_type = top_type->array.element_type;
2053 * Pop an entry from the given type path, ie. returning from
2054 * (type).a.b to (type).a
2056 static void ascend_from_subtype(type_path_t *path)
2058 type_path_entry_t *top = get_type_path_top(path);
2060 path->top_type = top->type;
2062 size_t len = ARR_LEN(path->path);
2063 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2067 * Pop entries from the given type path until the given
2068 * path level is reached.
2070 static void ascend_to(type_path_t *path, size_t top_path_level)
2072 size_t len = ARR_LEN(path->path);
2074 while(len > top_path_level) {
2075 ascend_from_subtype(path);
2076 len = ARR_LEN(path->path);
2080 static bool walk_designator(type_path_t *path, const designator_t *designator,
2081 bool used_in_offsetof)
2083 for( ; designator != NULL; designator = designator->next) {
2084 type_path_entry_t *top = get_type_path_top(path);
2085 type_t *orig_type = top->type;
2087 type_t *type = skip_typeref(orig_type);
2089 if(designator->symbol != NULL) {
2090 symbol_t *symbol = designator->symbol;
2091 if(!is_type_compound(type)) {
2092 if(is_type_valid(type)) {
2093 errorf(&designator->source_position,
2094 "'.%Y' designator used for non-compound type '%T'",
2100 declaration_t *declaration = type->compound.declaration;
2101 declaration_t *iter = declaration->scope.declarations;
2102 for( ; iter != NULL; iter = iter->next) {
2103 if(iter->symbol == symbol) {
2108 errorf(&designator->source_position,
2109 "'%T' has no member named '%Y'", orig_type, symbol);
2112 if(used_in_offsetof) {
2113 type_t *real_type = skip_typeref(iter->type);
2114 if(real_type->kind == TYPE_BITFIELD) {
2115 errorf(&designator->source_position,
2116 "offsetof designator '%Y' may not specify bitfield",
2122 top->type = orig_type;
2123 top->v.compound_entry = iter;
2124 orig_type = iter->type;
2126 expression_t *array_index = designator->array_index;
2127 assert(designator->array_index != NULL);
2129 if(!is_type_array(type)) {
2130 if(is_type_valid(type)) {
2131 errorf(&designator->source_position,
2132 "[%E] designator used for non-array type '%T'",
2133 array_index, orig_type);
2137 if(!is_type_valid(array_index->base.type)) {
2141 long index = fold_constant(array_index);
2142 if(!used_in_offsetof) {
2144 errorf(&designator->source_position,
2145 "array index [%E] must be positive", array_index);
2148 if(type->array.size_constant == true) {
2149 long array_size = type->array.size;
2150 if(index >= array_size) {
2151 errorf(&designator->source_position,
2152 "designator [%E] (%d) exceeds array size %d",
2153 array_index, index, array_size);
2159 top->type = orig_type;
2160 top->v.index = (size_t) index;
2161 orig_type = type->array.element_type;
2163 path->top_type = orig_type;
2165 if(designator->next != NULL) {
2166 descend_into_subtype(path);
2175 static void advance_current_object(type_path_t *path, size_t top_path_level)
2177 type_path_entry_t *top = get_type_path_top(path);
2179 type_t *type = skip_typeref(top->type);
2180 if(is_type_union(type)) {
2181 /* in unions only the first element is initialized */
2182 top->v.compound_entry = NULL;
2183 } else if(is_type_struct(type)) {
2184 declaration_t *entry = top->v.compound_entry;
2186 entry = entry->next;
2187 top->v.compound_entry = entry;
2189 path->top_type = entry->type;
2193 assert(is_type_array(type));
2197 if(!type->array.size_constant || top->v.index < type->array.size) {
2202 /* we're past the last member of the current sub-aggregate, try if we
2203 * can ascend in the type hierarchy and continue with another subobject */
2204 size_t len = ARR_LEN(path->path);
2206 if(len > top_path_level) {
2207 ascend_from_subtype(path);
2208 advance_current_object(path, top_path_level);
2210 path->top_type = NULL;
2215 * skip until token is found.
2217 static void skip_until(int type) {
2218 while(token.type != type) {
2219 if(token.type == T_EOF)
2226 * skip any {...} blocks until a closing bracket is reached.
2228 static void skip_initializers(void)
2230 if(token.type == '{')
2233 while(token.type != '}') {
2234 if(token.type == T_EOF)
2236 if(token.type == '{') {
2244 static initializer_t *create_empty_initializer(void)
2246 static initializer_t empty_initializer
2247 = { .list = { { INITIALIZER_LIST }, 0 } };
2248 return &empty_initializer;
2252 * Parse a part of an initialiser for a struct or union,
2254 static initializer_t *parse_sub_initializer(type_path_t *path,
2255 type_t *outer_type, size_t top_path_level,
2256 parse_initializer_env_t *env)
2258 if(token.type == '}') {
2259 /* empty initializer */
2260 return create_empty_initializer();
2263 type_t *orig_type = path->top_type;
2264 type_t *type = NULL;
2266 if (orig_type == NULL) {
2267 /* We are initializing an empty compound. */
2269 type = skip_typeref(orig_type);
2271 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2272 * initializers in this case. */
2273 if(!is_type_valid(type)) {
2274 skip_initializers();
2275 return create_empty_initializer();
2279 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2282 designator_t *designator = NULL;
2283 if(token.type == '.' || token.type == '[') {
2284 designator = parse_designation();
2286 /* reset path to toplevel, evaluate designator from there */
2287 ascend_to(path, top_path_level);
2288 if(!walk_designator(path, designator, false)) {
2289 /* can't continue after designation error */
2293 initializer_t *designator_initializer
2294 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2295 designator_initializer->designator.designator = designator;
2296 ARR_APP1(initializer_t*, initializers, designator_initializer);
2298 orig_type = path->top_type;
2299 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2304 if(token.type == '{') {
2305 if(type != NULL && is_type_scalar(type)) {
2306 sub = parse_scalar_initializer(type, env->must_be_constant);
2310 if (env->declaration != NULL)
2311 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2312 env->declaration->symbol);
2314 errorf(HERE, "extra brace group at end of initializer");
2316 descend_into_subtype(path);
2318 add_anchor_token('}');
2319 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2321 rem_anchor_token('}');
2324 ascend_from_subtype(path);
2328 goto error_parse_next;
2332 /* must be an expression */
2333 expression_t *expression = parse_assignment_expression();
2335 if(env->must_be_constant && !is_initializer_constant(expression)) {
2336 errorf(&expression->base.source_position,
2337 "Initialisation expression '%E' is not constant\n",
2342 /* we are already outside, ... */
2346 /* handle { "string" } special case */
2347 if((expression->kind == EXPR_STRING_LITERAL
2348 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2349 && outer_type != NULL) {
2350 sub = initializer_from_expression(outer_type, expression);
2352 if(token.type == ',') {
2355 if(token.type != '}') {
2356 warningf(HERE, "excessive elements in initializer for type '%T'",
2359 /* TODO: eat , ... */
2364 /* descend into subtypes until expression matches type */
2366 orig_type = path->top_type;
2367 type = skip_typeref(orig_type);
2369 sub = initializer_from_expression(orig_type, expression);
2373 if(!is_type_valid(type)) {
2376 if(is_type_scalar(type)) {
2377 errorf(&expression->base.source_position,
2378 "expression '%E' doesn't match expected type '%T'",
2379 expression, orig_type);
2383 descend_into_subtype(path);
2387 /* update largest index of top array */
2388 const type_path_entry_t *first = &path->path[0];
2389 type_t *first_type = first->type;
2390 first_type = skip_typeref(first_type);
2391 if(is_type_array(first_type)) {
2392 size_t index = first->v.index;
2393 if(index > path->max_index)
2394 path->max_index = index;
2398 /* append to initializers list */
2399 ARR_APP1(initializer_t*, initializers, sub);
2402 if(env->declaration != NULL)
2403 warningf(HERE, "excess elements in struct initializer for '%Y'",
2404 env->declaration->symbol);
2406 warningf(HERE, "excess elements in struct initializer");
2410 if(token.type == '}') {
2414 if(token.type == '}') {
2419 /* advance to the next declaration if we are not at the end */
2420 advance_current_object(path, top_path_level);
2421 orig_type = path->top_type;
2422 if(orig_type != NULL)
2423 type = skip_typeref(orig_type);
2429 size_t len = ARR_LEN(initializers);
2430 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2431 initializer_t *result = allocate_ast_zero(size);
2432 result->kind = INITIALIZER_LIST;
2433 result->list.len = len;
2434 memcpy(&result->list.initializers, initializers,
2435 len * sizeof(initializers[0]));
2437 DEL_ARR_F(initializers);
2438 ascend_to(path, top_path_level+1);
2443 skip_initializers();
2444 DEL_ARR_F(initializers);
2445 ascend_to(path, top_path_level+1);
2450 * Parses an initializer. Parsers either a compound literal
2451 * (env->declaration == NULL) or an initializer of a declaration.
2453 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2455 type_t *type = skip_typeref(env->type);
2456 initializer_t *result = NULL;
2459 if(is_type_scalar(type)) {
2460 result = parse_scalar_initializer(type, env->must_be_constant);
2461 } else if(token.type == '{') {
2465 memset(&path, 0, sizeof(path));
2466 path.top_type = env->type;
2467 path.path = NEW_ARR_F(type_path_entry_t, 0);
2469 descend_into_subtype(&path);
2471 add_anchor_token('}');
2472 result = parse_sub_initializer(&path, env->type, 1, env);
2473 rem_anchor_token('}');
2475 max_index = path.max_index;
2476 DEL_ARR_F(path.path);
2480 /* parse_scalar_initializer() also works in this case: we simply
2481 * have an expression without {} around it */
2482 result = parse_scalar_initializer(type, env->must_be_constant);
2485 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2486 * the array type size */
2487 if(is_type_array(type) && type->array.size_expression == NULL
2488 && result != NULL) {
2490 switch (result->kind) {
2491 case INITIALIZER_LIST:
2492 size = max_index + 1;
2495 case INITIALIZER_STRING:
2496 size = result->string.string.size;
2499 case INITIALIZER_WIDE_STRING:
2500 size = result->wide_string.string.size;
2503 case INITIALIZER_DESIGNATOR:
2504 case INITIALIZER_VALUE:
2505 /* can happen for parse errors */
2510 internal_errorf(HERE, "invalid initializer type");
2513 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2514 cnst->base.type = type_size_t;
2515 cnst->conste.v.int_value = size;
2517 type_t *new_type = duplicate_type(type);
2519 new_type->array.size_expression = cnst;
2520 new_type->array.size_constant = true;
2521 new_type->array.size = size;
2522 env->type = new_type;
2530 static declaration_t *append_declaration(declaration_t *declaration);
2532 static declaration_t *parse_compound_type_specifier(bool is_struct)
2534 gnu_attribute_t *attributes = NULL;
2535 decl_modifiers_t modifiers = 0;
2542 symbol_t *symbol = NULL;
2543 declaration_t *declaration = NULL;
2545 if (token.type == T___attribute__) {
2546 modifiers |= parse_attributes(&attributes);
2549 if(token.type == T_IDENTIFIER) {
2550 symbol = token.v.symbol;
2554 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2556 declaration = get_declaration(symbol, NAMESPACE_UNION);
2558 } else if(token.type != '{') {
2560 parse_error_expected("while parsing struct type specifier",
2561 T_IDENTIFIER, '{', NULL);
2563 parse_error_expected("while parsing union type specifier",
2564 T_IDENTIFIER, '{', NULL);
2570 if(declaration == NULL) {
2571 declaration = allocate_declaration_zero();
2572 declaration->namespc =
2573 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2574 declaration->source_position = token.source_position;
2575 declaration->symbol = symbol;
2576 declaration->parent_scope = scope;
2577 if (symbol != NULL) {
2578 environment_push(declaration);
2580 append_declaration(declaration);
2583 if(token.type == '{') {
2584 if (declaration->init.complete) {
2585 assert(symbol != NULL);
2586 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2587 is_struct ? "struct" : "union", symbol,
2588 &declaration->source_position);
2589 declaration->scope.declarations = NULL;
2591 declaration->init.complete = true;
2593 parse_compound_type_entries(declaration);
2594 modifiers |= parse_attributes(&attributes);
2597 declaration->modifiers |= modifiers;
2601 static void parse_enum_entries(type_t *const enum_type)
2605 if(token.type == '}') {
2607 errorf(HERE, "empty enum not allowed");
2611 add_anchor_token('}');
2613 if(token.type != T_IDENTIFIER) {
2614 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2616 rem_anchor_token('}');
2620 declaration_t *const entry = allocate_declaration_zero();
2621 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2622 entry->type = enum_type;
2623 entry->symbol = token.v.symbol;
2624 entry->source_position = token.source_position;
2627 if(token.type == '=') {
2629 expression_t *value = parse_constant_expression();
2631 value = create_implicit_cast(value, enum_type);
2632 entry->init.enum_value = value;
2637 record_declaration(entry);
2639 if(token.type != ',')
2642 } while(token.type != '}');
2643 rem_anchor_token('}');
2651 static type_t *parse_enum_specifier(void)
2653 gnu_attribute_t *attributes = NULL;
2654 declaration_t *declaration;
2658 if(token.type == T_IDENTIFIER) {
2659 symbol = token.v.symbol;
2662 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2663 } else if(token.type != '{') {
2664 parse_error_expected("while parsing enum type specifier",
2665 T_IDENTIFIER, '{', NULL);
2672 if(declaration == NULL) {
2673 declaration = allocate_declaration_zero();
2674 declaration->namespc = NAMESPACE_ENUM;
2675 declaration->source_position = token.source_position;
2676 declaration->symbol = symbol;
2677 declaration->parent_scope = scope;
2680 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2681 type->enumt.declaration = declaration;
2683 if(token.type == '{') {
2684 if(declaration->init.complete) {
2685 errorf(HERE, "multiple definitions of enum %Y", symbol);
2687 if (symbol != NULL) {
2688 environment_push(declaration);
2690 append_declaration(declaration);
2691 declaration->init.complete = true;
2693 parse_enum_entries(type);
2694 parse_attributes(&attributes);
2701 * if a symbol is a typedef to another type, return true
2703 static bool is_typedef_symbol(symbol_t *symbol)
2705 const declaration_t *const declaration =
2706 get_declaration(symbol, NAMESPACE_NORMAL);
2708 declaration != NULL &&
2709 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2712 static type_t *parse_typeof(void)
2719 add_anchor_token(')');
2721 expression_t *expression = NULL;
2724 switch(token.type) {
2725 case T___extension__:
2726 /* this can be a prefix to a typename or an expression */
2727 /* we simply eat it now. */
2730 } while(token.type == T___extension__);
2734 if(is_typedef_symbol(token.v.symbol)) {
2735 type = parse_typename();
2737 expression = parse_expression();
2738 type = expression->base.type;
2743 type = parse_typename();
2747 expression = parse_expression();
2748 type = expression->base.type;
2752 rem_anchor_token(')');
2755 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2756 typeof_type->typeoft.expression = expression;
2757 typeof_type->typeoft.typeof_type = type;
2765 SPECIFIER_SIGNED = 1 << 0,
2766 SPECIFIER_UNSIGNED = 1 << 1,
2767 SPECIFIER_LONG = 1 << 2,
2768 SPECIFIER_INT = 1 << 3,
2769 SPECIFIER_DOUBLE = 1 << 4,
2770 SPECIFIER_CHAR = 1 << 5,
2771 SPECIFIER_SHORT = 1 << 6,
2772 SPECIFIER_LONG_LONG = 1 << 7,
2773 SPECIFIER_FLOAT = 1 << 8,
2774 SPECIFIER_BOOL = 1 << 9,
2775 SPECIFIER_VOID = 1 << 10,
2776 SPECIFIER_INT8 = 1 << 11,
2777 SPECIFIER_INT16 = 1 << 12,
2778 SPECIFIER_INT32 = 1 << 13,
2779 SPECIFIER_INT64 = 1 << 14,
2780 SPECIFIER_INT128 = 1 << 15,
2781 SPECIFIER_COMPLEX = 1 << 16,
2782 SPECIFIER_IMAGINARY = 1 << 17,
2785 static type_t *create_builtin_type(symbol_t *const symbol,
2786 type_t *const real_type)
2788 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2789 type->builtin.symbol = symbol;
2790 type->builtin.real_type = real_type;
2792 type_t *result = typehash_insert(type);
2793 if(type != result) {
2800 static type_t *get_typedef_type(symbol_t *symbol)
2802 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2803 if(declaration == NULL ||
2804 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2807 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2808 type->typedeft.declaration = declaration;
2814 * check for the allowed MS alignment values.
2816 static bool check_elignment_value(long long intvalue) {
2817 if(intvalue < 1 || intvalue > 8192) {
2818 errorf(HERE, "illegal alignment value");
2821 unsigned v = (unsigned)intvalue;
2822 for(unsigned i = 1; i <= 8192; i += i) {
2826 errorf(HERE, "alignment must be power of two");
2830 #define DET_MOD(name, tag) do { \
2831 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2832 *modifiers |= tag; \
2835 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2837 decl_modifiers_t *modifiers = &specifiers->modifiers;
2840 if(token.type == T_restrict) {
2842 DET_MOD(restrict, DM_RESTRICT);
2844 } else if(token.type != T_IDENTIFIER)
2846 symbol_t *symbol = token.v.symbol;
2847 if(symbol == sym_align) {
2850 if(token.type != T_INTEGER)
2852 if(check_elignment_value(token.v.intvalue)) {
2853 if(specifiers->alignment != 0)
2854 warningf(HERE, "align used more than once");
2855 specifiers->alignment = (unsigned char)token.v.intvalue;
2859 } else if(symbol == sym_allocate) {
2862 if(token.type != T_IDENTIFIER)
2864 (void)token.v.symbol;
2866 } else if(symbol == sym_dllimport) {
2868 DET_MOD(dllimport, DM_DLLIMPORT);
2869 } else if(symbol == sym_dllexport) {
2871 DET_MOD(dllexport, DM_DLLEXPORT);
2872 } else if(symbol == sym_thread) {
2874 DET_MOD(thread, DM_THREAD);
2875 } else if(symbol == sym_naked) {
2877 DET_MOD(naked, DM_NAKED);
2878 } else if(symbol == sym_noinline) {
2880 DET_MOD(noinline, DM_NOINLINE);
2881 } else if(symbol == sym_noreturn) {
2883 DET_MOD(noreturn, DM_NORETURN);
2884 } else if(symbol == sym_nothrow) {
2886 DET_MOD(nothrow, DM_NOTHROW);
2887 } else if(symbol == sym_novtable) {
2889 DET_MOD(novtable, DM_NOVTABLE);
2890 } else if(symbol == sym_property) {
2894 bool is_get = false;
2895 if(token.type != T_IDENTIFIER)
2897 if(token.v.symbol == sym_get) {
2899 } else if(token.v.symbol == sym_put) {
2901 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2906 if(token.type != T_IDENTIFIER)
2909 if(specifiers->get_property_sym != NULL) {
2910 errorf(HERE, "get property name already specified");
2912 specifiers->get_property_sym = token.v.symbol;
2915 if(specifiers->put_property_sym != NULL) {
2916 errorf(HERE, "put property name already specified");
2918 specifiers->put_property_sym = token.v.symbol;
2922 if(token.type == ',') {
2929 } else if(symbol == sym_selectany) {
2931 DET_MOD(selectany, DM_SELECTANY);
2932 } else if(symbol == sym_uuid) {
2935 if(token.type != T_STRING_LITERAL)
2939 } else if(symbol == sym_deprecated) {
2941 if(specifiers->deprecated != 0)
2942 warningf(HERE, "deprecated used more than once");
2943 specifiers->deprecated = 1;
2944 if(token.type == '(') {
2946 if(token.type == T_STRING_LITERAL) {
2947 specifiers->deprecated_string = token.v.string.begin;
2950 errorf(HERE, "string literal expected");
2954 } else if(symbol == sym_noalias) {
2956 DET_MOD(noalias, DM_NOALIAS);
2958 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2960 if(token.type == '(')
2964 if (token.type == ',')
2971 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2973 type_t *type = NULL;
2974 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2975 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
2976 unsigned type_specifiers = 0;
2979 specifiers->source_position = token.source_position;
2982 switch(token.type) {
2985 #define MATCH_STORAGE_CLASS(token, class) \
2987 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2988 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2990 specifiers->declared_storage_class = class; \
2994 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2995 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2996 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2997 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2998 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3003 add_anchor_token(')');
3004 parse_microsoft_extended_decl_modifier(specifiers);
3005 rem_anchor_token(')');
3010 switch (specifiers->declared_storage_class) {
3011 case STORAGE_CLASS_NONE:
3012 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3015 case STORAGE_CLASS_EXTERN:
3016 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3019 case STORAGE_CLASS_STATIC:
3020 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3024 errorf(HERE, "multiple storage classes in declaration specifiers");
3030 /* type qualifiers */
3031 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3033 qualifiers |= qualifier; \
3037 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3038 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3039 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3040 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3041 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3042 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3043 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3044 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3046 case T___extension__:
3051 /* type specifiers */
3052 #define MATCH_SPECIFIER(token, specifier, name) \
3055 if(type_specifiers & specifier) { \
3056 errorf(HERE, "multiple " name " type specifiers given"); \
3058 type_specifiers |= specifier; \
3062 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3063 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3064 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3065 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3066 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3067 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3068 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3069 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3070 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3071 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3072 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3073 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3074 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3075 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3076 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3077 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3079 case T__forceinline:
3080 /* only in microsoft mode */
3081 specifiers->modifiers |= DM_FORCEINLINE;
3085 specifiers->is_inline = true;
3090 if(type_specifiers & SPECIFIER_LONG_LONG) {
3091 errorf(HERE, "multiple type specifiers given");
3092 } else if(type_specifiers & SPECIFIER_LONG) {
3093 type_specifiers |= SPECIFIER_LONG_LONG;
3095 type_specifiers |= SPECIFIER_LONG;
3100 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3102 type->compound.declaration = parse_compound_type_specifier(true);
3106 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3107 type->compound.declaration = parse_compound_type_specifier(false);
3108 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3109 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3113 type = parse_enum_specifier();
3116 type = parse_typeof();
3118 case T___builtin_va_list:
3119 type = duplicate_type(type_valist);
3123 case T___attribute__:
3124 specifiers->modifiers
3125 |= parse_attributes(&specifiers->gnu_attributes);
3126 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3127 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3130 case T_IDENTIFIER: {
3131 /* only parse identifier if we haven't found a type yet */
3132 if(type != NULL || type_specifiers != 0)
3133 goto finish_specifiers;
3135 type_t *typedef_type = get_typedef_type(token.v.symbol);
3137 if(typedef_type == NULL)
3138 goto finish_specifiers;
3141 type = typedef_type;
3145 /* function specifier */
3147 goto finish_specifiers;
3154 atomic_type_kind_t atomic_type;
3156 /* match valid basic types */
3157 switch(type_specifiers) {
3158 case SPECIFIER_VOID:
3159 atomic_type = ATOMIC_TYPE_VOID;
3161 case SPECIFIER_CHAR:
3162 atomic_type = ATOMIC_TYPE_CHAR;
3164 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3165 atomic_type = ATOMIC_TYPE_SCHAR;
3167 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3168 atomic_type = ATOMIC_TYPE_UCHAR;
3170 case SPECIFIER_SHORT:
3171 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3172 case SPECIFIER_SHORT | SPECIFIER_INT:
3173 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3174 atomic_type = ATOMIC_TYPE_SHORT;
3176 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3177 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3178 atomic_type = ATOMIC_TYPE_USHORT;
3181 case SPECIFIER_SIGNED:
3182 case SPECIFIER_SIGNED | SPECIFIER_INT:
3183 atomic_type = ATOMIC_TYPE_INT;
3185 case SPECIFIER_UNSIGNED:
3186 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3187 atomic_type = ATOMIC_TYPE_UINT;
3189 case SPECIFIER_LONG:
3190 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3191 case SPECIFIER_LONG | SPECIFIER_INT:
3192 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3193 atomic_type = ATOMIC_TYPE_LONG;
3195 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3196 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3197 atomic_type = ATOMIC_TYPE_ULONG;
3199 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3200 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3201 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3202 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3204 atomic_type = ATOMIC_TYPE_LONGLONG;
3206 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3207 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3209 atomic_type = ATOMIC_TYPE_ULONGLONG;
3212 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3213 atomic_type = unsigned_int8_type_kind;
3216 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3217 atomic_type = unsigned_int16_type_kind;
3220 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3221 atomic_type = unsigned_int32_type_kind;
3224 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3225 atomic_type = unsigned_int64_type_kind;
3228 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3229 atomic_type = unsigned_int128_type_kind;
3232 case SPECIFIER_INT8:
3233 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3234 atomic_type = int8_type_kind;
3237 case SPECIFIER_INT16:
3238 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3239 atomic_type = int16_type_kind;
3242 case SPECIFIER_INT32:
3243 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3244 atomic_type = int32_type_kind;
3247 case SPECIFIER_INT64:
3248 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3249 atomic_type = int64_type_kind;
3252 case SPECIFIER_INT128:
3253 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3254 atomic_type = int128_type_kind;
3257 case SPECIFIER_FLOAT:
3258 atomic_type = ATOMIC_TYPE_FLOAT;
3260 case SPECIFIER_DOUBLE:
3261 atomic_type = ATOMIC_TYPE_DOUBLE;
3263 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3264 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3266 case SPECIFIER_BOOL:
3267 atomic_type = ATOMIC_TYPE_BOOL;
3269 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3270 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3271 atomic_type = ATOMIC_TYPE_FLOAT;
3273 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3274 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3275 atomic_type = ATOMIC_TYPE_DOUBLE;
3277 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3278 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3279 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3282 /* invalid specifier combination, give an error message */
3283 if(type_specifiers == 0) {
3284 if (! strict_mode) {
3285 if (warning.implicit_int) {
3286 warningf(HERE, "no type specifiers in declaration, using 'int'");
3288 atomic_type = ATOMIC_TYPE_INT;
3291 errorf(HERE, "no type specifiers given in declaration");
3293 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3294 (type_specifiers & SPECIFIER_UNSIGNED)) {
3295 errorf(HERE, "signed and unsigned specifiers gives");
3296 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3297 errorf(HERE, "only integer types can be signed or unsigned");
3299 errorf(HERE, "multiple datatypes in declaration");
3301 atomic_type = ATOMIC_TYPE_INVALID;
3304 if(type_specifiers & SPECIFIER_COMPLEX &&
3305 atomic_type != ATOMIC_TYPE_INVALID) {
3306 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3307 type->complex.akind = atomic_type;
3308 } else if(type_specifiers & SPECIFIER_IMAGINARY &&
3309 atomic_type != ATOMIC_TYPE_INVALID) {
3310 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3311 type->imaginary.akind = atomic_type;
3313 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3314 type->atomic.akind = atomic_type;
3318 if(type_specifiers != 0) {
3319 errorf(HERE, "multiple datatypes in declaration");
3323 /* FIXME: check type qualifiers here */
3325 type->base.qualifiers = qualifiers;
3326 type->base.modifiers = modifiers;
3328 type_t *result = typehash_insert(type);
3329 if(newtype && result != type) {
3333 specifiers->type = result;
3338 static type_qualifiers_t parse_type_qualifiers(void)
3340 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3343 switch(token.type) {
3344 /* type qualifiers */
3345 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3346 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3347 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3348 /* microsoft extended type modifiers */
3349 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3350 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3351 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3352 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3353 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3361 static declaration_t *parse_identifier_list(void)
3363 declaration_t *declarations = NULL;
3364 declaration_t *last_declaration = NULL;
3366 declaration_t *const declaration = allocate_declaration_zero();
3367 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3368 declaration->source_position = token.source_position;
3369 declaration->symbol = token.v.symbol;
3372 if(last_declaration != NULL) {
3373 last_declaration->next = declaration;
3375 declarations = declaration;
3377 last_declaration = declaration;
3379 if (token.type != ',') {
3383 } while(token.type == T_IDENTIFIER);
3385 return declarations;
3388 static void semantic_parameter(declaration_t *declaration)
3390 /* TODO: improve error messages */
3392 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3393 errorf(HERE, "typedef not allowed in parameter list");
3394 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3395 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3396 errorf(HERE, "parameter may only have none or register storage class");
3399 type_t *const orig_type = declaration->type;
3400 type_t * type = skip_typeref(orig_type);
3402 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3403 * into a pointer. § 6.7.5.3 (7) */
3404 if (is_type_array(type)) {
3405 type_t *const element_type = type->array.element_type;
3407 type = make_pointer_type(element_type, type->base.qualifiers);
3409 declaration->type = type;
3412 if(is_type_incomplete(type)) {
3413 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3414 orig_type, declaration->symbol);
3418 static declaration_t *parse_parameter(void)
3420 declaration_specifiers_t specifiers;
3421 memset(&specifiers, 0, sizeof(specifiers));
3423 parse_declaration_specifiers(&specifiers);
3425 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3427 semantic_parameter(declaration);
3432 static declaration_t *parse_parameters(function_type_t *type)
3434 declaration_t *declarations = NULL;
3437 add_anchor_token(')');
3438 int saved_comma_state = save_and_reset_anchor_state(',');
3440 if(token.type == T_IDENTIFIER) {
3441 symbol_t *symbol = token.v.symbol;
3442 if(!is_typedef_symbol(symbol)) {
3443 type->kr_style_parameters = true;
3444 declarations = parse_identifier_list();
3445 goto parameters_finished;
3449 if(token.type == ')') {
3450 type->unspecified_parameters = 1;
3451 goto parameters_finished;
3453 if(token.type == T_void && look_ahead(1)->type == ')') {
3455 goto parameters_finished;
3458 declaration_t *declaration;
3459 declaration_t *last_declaration = NULL;
3460 function_parameter_t *parameter;
3461 function_parameter_t *last_parameter = NULL;
3464 switch(token.type) {
3468 goto parameters_finished;
3471 case T___extension__:
3473 declaration = parse_parameter();
3475 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3476 memset(parameter, 0, sizeof(parameter[0]));
3477 parameter->type = declaration->type;
3479 if(last_parameter != NULL) {
3480 last_declaration->next = declaration;
3481 last_parameter->next = parameter;
3483 type->parameters = parameter;
3484 declarations = declaration;
3486 last_parameter = parameter;
3487 last_declaration = declaration;
3491 goto parameters_finished;
3493 if (token.type != ',') {
3494 goto parameters_finished;
3500 parameters_finished:
3501 rem_anchor_token(')');
3504 restore_anchor_state(',', saved_comma_state);
3505 return declarations;
3508 restore_anchor_state(',', saved_comma_state);
3517 } construct_type_kind_t;
3519 typedef struct construct_type_t construct_type_t;
3520 struct construct_type_t {
3521 construct_type_kind_t kind;
3522 construct_type_t *next;
3525 typedef struct parsed_pointer_t parsed_pointer_t;
3526 struct parsed_pointer_t {
3527 construct_type_t construct_type;
3528 type_qualifiers_t type_qualifiers;
3531 typedef struct construct_function_type_t construct_function_type_t;
3532 struct construct_function_type_t {
3533 construct_type_t construct_type;
3534 type_t *function_type;
3537 typedef struct parsed_array_t parsed_array_t;
3538 struct parsed_array_t {
3539 construct_type_t construct_type;
3540 type_qualifiers_t type_qualifiers;
3546 typedef struct construct_base_type_t construct_base_type_t;
3547 struct construct_base_type_t {
3548 construct_type_t construct_type;
3552 static construct_type_t *parse_pointer_declarator(void)
3556 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3557 memset(pointer, 0, sizeof(pointer[0]));
3558 pointer->construct_type.kind = CONSTRUCT_POINTER;
3559 pointer->type_qualifiers = parse_type_qualifiers();
3561 return (construct_type_t*) pointer;
3564 static construct_type_t *parse_array_declarator(void)
3567 add_anchor_token(']');
3569 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3570 memset(array, 0, sizeof(array[0]));
3571 array->construct_type.kind = CONSTRUCT_ARRAY;
3573 if(token.type == T_static) {
3574 array->is_static = true;
3578 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3579 if(type_qualifiers != 0) {
3580 if(token.type == T_static) {
3581 array->is_static = true;
3585 array->type_qualifiers = type_qualifiers;
3587 if(token.type == '*' && look_ahead(1)->type == ']') {
3588 array->is_variable = true;
3590 } else if(token.type != ']') {
3591 array->size = parse_assignment_expression();
3594 rem_anchor_token(']');
3597 return (construct_type_t*) array;
3602 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3605 if(declaration != NULL) {
3606 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3608 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3611 declaration_t *parameters = parse_parameters(&type->function);
3612 if(declaration != NULL) {
3613 declaration->scope.declarations = parameters;
3616 construct_function_type_t *construct_function_type =
3617 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3618 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3619 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3620 construct_function_type->function_type = type;
3622 return (construct_type_t*) construct_function_type;
3625 static void fix_declaration_type(declaration_t *declaration)
3627 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3628 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3630 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3631 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3633 if (declaration->type->base.modifiers == type_modifiers)
3636 type_t *copy = duplicate_type(declaration->type);
3637 copy->base.modifiers = type_modifiers;
3639 type_t *result = typehash_insert(copy);
3640 if (result != copy) {
3641 obstack_free(type_obst, copy);
3644 declaration->type = result;
3647 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3648 bool may_be_abstract)
3650 /* construct a single linked list of construct_type_t's which describe
3651 * how to construct the final declarator type */
3652 construct_type_t *first = NULL;
3653 construct_type_t *last = NULL;
3654 gnu_attribute_t *attributes = NULL;
3657 while(token.type == '*') {
3658 construct_type_t *type = parse_pointer_declarator();
3669 /* TODO: find out if this is correct */
3670 decl_modifiers_t modifiers = parse_attributes(&attributes);
3672 construct_type_t *inner_types = NULL;
3674 switch(token.type) {
3676 if(declaration == NULL) {
3677 errorf(HERE, "no identifier expected in typename");
3679 declaration->symbol = token.v.symbol;
3680 declaration->source_position = token.source_position;
3686 add_anchor_token(')');
3687 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3688 rem_anchor_token(')');
3694 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3695 /* avoid a loop in the outermost scope, because eat_statement doesn't
3697 if(token.type == '}' && current_function == NULL) {
3705 construct_type_t *p = last;
3708 construct_type_t *type;
3709 switch(token.type) {
3711 type = parse_function_declarator(declaration);
3714 type = parse_array_declarator();
3717 goto declarator_finished;
3720 /* insert in the middle of the list (behind p) */
3722 type->next = p->next;
3733 declarator_finished:
3734 modifiers = parse_attributes(&attributes);
3735 if (declaration != NULL) {
3736 declaration->modifiers |= modifiers;
3739 /* append inner_types at the end of the list, we don't to set last anymore
3740 * as it's not needed anymore */
3742 assert(first == NULL);
3743 first = inner_types;
3745 last->next = inner_types;
3753 static type_t *construct_declarator_type(construct_type_t *construct_list,
3756 construct_type_t *iter = construct_list;
3757 for( ; iter != NULL; iter = iter->next) {
3758 switch(iter->kind) {
3759 case CONSTRUCT_INVALID:
3760 internal_errorf(HERE, "invalid type construction found");
3761 case CONSTRUCT_FUNCTION: {
3762 construct_function_type_t *construct_function_type
3763 = (construct_function_type_t*) iter;
3765 type_t *function_type = construct_function_type->function_type;
3767 function_type->function.return_type = type;
3769 type_t *skipped_return_type = skip_typeref(type);
3770 if (is_type_function(skipped_return_type)) {
3771 errorf(HERE, "function returning function is not allowed");
3772 type = type_error_type;
3773 } else if (is_type_array(skipped_return_type)) {
3774 errorf(HERE, "function returning array is not allowed");
3775 type = type_error_type;
3777 type = function_type;
3782 case CONSTRUCT_POINTER: {
3783 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3784 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3785 pointer_type->pointer.points_to = type;
3786 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3788 type = pointer_type;
3792 case CONSTRUCT_ARRAY: {
3793 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3794 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3796 expression_t *size_expression = parsed_array->size;
3797 if(size_expression != NULL) {
3799 = create_implicit_cast(size_expression, type_size_t);
3802 array_type->base.qualifiers = parsed_array->type_qualifiers;
3803 array_type->array.element_type = type;
3804 array_type->array.is_static = parsed_array->is_static;
3805 array_type->array.is_variable = parsed_array->is_variable;
3806 array_type->array.size_expression = size_expression;
3808 if(size_expression != NULL) {
3809 if(is_constant_expression(size_expression)) {
3810 array_type->array.size_constant = true;
3811 array_type->array.size
3812 = fold_constant(size_expression);
3814 array_type->array.is_vla = true;
3818 type_t *skipped_type = skip_typeref(type);
3819 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3820 errorf(HERE, "array of void is not allowed");
3821 type = type_error_type;
3829 type_t *hashed_type = typehash_insert(type);
3830 if(hashed_type != type) {
3831 /* the function type was constructed earlier freeing it here will
3832 * destroy other types... */
3833 if(iter->kind != CONSTRUCT_FUNCTION) {
3843 static declaration_t *parse_declarator(
3844 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3846 declaration_t *const declaration = allocate_declaration_zero();
3847 declaration->declared_storage_class = specifiers->declared_storage_class;
3848 declaration->modifiers = specifiers->modifiers;
3849 declaration->deprecated = specifiers->deprecated;
3850 declaration->deprecated_string = specifiers->deprecated_string;
3851 declaration->get_property_sym = specifiers->get_property_sym;
3852 declaration->put_property_sym = specifiers->put_property_sym;
3853 declaration->is_inline = specifiers->is_inline;
3855 declaration->storage_class = specifiers->declared_storage_class;
3856 if(declaration->storage_class == STORAGE_CLASS_NONE
3857 && scope != global_scope) {
3858 declaration->storage_class = STORAGE_CLASS_AUTO;
3861 if(specifiers->alignment != 0) {
3862 /* TODO: add checks here */
3863 declaration->alignment = specifiers->alignment;
3866 construct_type_t *construct_type
3867 = parse_inner_declarator(declaration, may_be_abstract);
3868 type_t *const type = specifiers->type;
3869 declaration->type = construct_declarator_type(construct_type, type);
3871 fix_declaration_type(declaration);
3873 if(construct_type != NULL) {
3874 obstack_free(&temp_obst, construct_type);
3880 static type_t *parse_abstract_declarator(type_t *base_type)
3882 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3884 type_t *result = construct_declarator_type(construct_type, base_type);
3885 if(construct_type != NULL) {
3886 obstack_free(&temp_obst, construct_type);
3892 static declaration_t *append_declaration(declaration_t* const declaration)
3894 if (last_declaration != NULL) {
3895 last_declaration->next = declaration;
3897 scope->declarations = declaration;
3899 last_declaration = declaration;
3904 * Check if the declaration of main is suspicious. main should be a
3905 * function with external linkage, returning int, taking either zero
3906 * arguments, two, or three arguments of appropriate types, ie.
3908 * int main([ int argc, char **argv [, char **env ] ]).
3910 * @param decl the declaration to check
3911 * @param type the function type of the declaration
3913 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3915 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3916 warningf(&decl->source_position,
3917 "'main' is normally a non-static function");
3919 if (skip_typeref(func_type->return_type) != type_int) {
3920 warningf(&decl->source_position,
3921 "return type of 'main' should be 'int', but is '%T'",
3922 func_type->return_type);
3924 const function_parameter_t *parm = func_type->parameters;
3926 type_t *const first_type = parm->type;
3927 if (!types_compatible(skip_typeref(first_type), type_int)) {
3928 warningf(&decl->source_position,
3929 "first argument of 'main' should be 'int', but is '%T'", first_type);
3933 type_t *const second_type = parm->type;
3934 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3935 warningf(&decl->source_position,
3936 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3940 type_t *const third_type = parm->type;
3941 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3942 warningf(&decl->source_position,
3943 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3947 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3951 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3957 * Check if a symbol is the equal to "main".
3959 static bool is_sym_main(const symbol_t *const sym)
3961 return strcmp(sym->string, "main") == 0;
3964 static declaration_t *internal_record_declaration(
3965 declaration_t *const declaration,
3966 const bool is_function_definition)
3968 const symbol_t *const symbol = declaration->symbol;
3969 const namespace_t namespc = (namespace_t)declaration->namespc;
3971 assert(declaration->symbol != NULL);
3972 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3974 type_t *const orig_type = declaration->type;
3975 type_t *const type = skip_typeref(orig_type);
3976 if (is_type_function(type) &&
3977 type->function.unspecified_parameters &&
3978 warning.strict_prototypes &&
3979 previous_declaration == NULL) {
3980 warningf(&declaration->source_position,
3981 "function declaration '%#T' is not a prototype",
3982 orig_type, declaration->symbol);
3985 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3986 check_type_of_main(declaration, &type->function);
3989 assert(declaration != previous_declaration);
3990 if (previous_declaration != NULL
3991 && previous_declaration->parent_scope == scope) {
3992 /* can happen for K&R style declarations */
3993 if (previous_declaration->type == NULL) {
3994 previous_declaration->type = declaration->type;
3997 const type_t *prev_type = skip_typeref(previous_declaration->type);
3998 if (!types_compatible(type, prev_type)) {
3999 errorf(&declaration->source_position,
4000 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4001 orig_type, symbol, previous_declaration->type, symbol,
4002 &previous_declaration->source_position);
4004 unsigned old_storage_class = previous_declaration->storage_class;
4005 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4006 errorf(&declaration->source_position,
4007 "redeclaration of enum entry '%Y' (declared %P)",
4008 symbol, &previous_declaration->source_position);
4009 return previous_declaration;
4012 unsigned new_storage_class = declaration->storage_class;
4014 if (is_type_incomplete(prev_type)) {
4015 previous_declaration->type = type;
4019 /* pretend no storage class means extern for function
4020 * declarations (except if the previous declaration is neither
4021 * none nor extern) */
4022 if (is_type_function(type)) {
4023 if (prev_type->function.unspecified_parameters) {
4024 previous_declaration->type = type;
4028 switch (old_storage_class) {
4029 case STORAGE_CLASS_NONE:
4030 old_storage_class = STORAGE_CLASS_EXTERN;
4032 case STORAGE_CLASS_EXTERN:
4033 if (is_function_definition) {
4034 if (warning.missing_prototypes &&
4035 prev_type->function.unspecified_parameters &&
4036 !is_sym_main(symbol)) {
4037 warningf(&declaration->source_position,
4038 "no previous prototype for '%#T'",
4041 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4042 new_storage_class = STORAGE_CLASS_EXTERN;
4051 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4052 new_storage_class == STORAGE_CLASS_EXTERN) {
4053 warn_redundant_declaration:
4054 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4055 warningf(&declaration->source_position,
4056 "redundant declaration for '%Y' (declared %P)",
4057 symbol, &previous_declaration->source_position);
4059 } else if (current_function == NULL) {
4060 if (old_storage_class != STORAGE_CLASS_STATIC &&
4061 new_storage_class == STORAGE_CLASS_STATIC) {
4062 errorf(&declaration->source_position,
4063 "static declaration of '%Y' follows non-static declaration (declared %P)",
4064 symbol, &previous_declaration->source_position);
4065 } else if (old_storage_class != STORAGE_CLASS_EXTERN
4066 && !is_function_definition) {
4067 goto warn_redundant_declaration;
4068 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4069 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4070 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4072 } else if (old_storage_class == new_storage_class) {
4073 errorf(&declaration->source_position,
4074 "redeclaration of '%Y' (declared %P)",
4075 symbol, &previous_declaration->source_position);
4077 errorf(&declaration->source_position,
4078 "redeclaration of '%Y' with different linkage (declared %P)",
4079 symbol, &previous_declaration->source_position);
4083 if (declaration->is_inline)
4084 previous_declaration->is_inline = true;
4085 return previous_declaration;
4086 } else if (is_function_definition) {
4087 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4088 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4089 warningf(&declaration->source_position,
4090 "no previous prototype for '%#T'", orig_type, symbol);
4091 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4092 warningf(&declaration->source_position,
4093 "no previous declaration for '%#T'", orig_type,
4097 } else if (warning.missing_declarations &&
4098 scope == global_scope &&
4099 !is_type_function(type) && (
4100 declaration->storage_class == STORAGE_CLASS_NONE ||
4101 declaration->storage_class == STORAGE_CLASS_THREAD
4103 warningf(&declaration->source_position,
4104 "no previous declaration for '%#T'", orig_type, symbol);
4107 assert(declaration->parent_scope == NULL);
4108 assert(scope != NULL);
4110 declaration->parent_scope = scope;
4112 environment_push(declaration);
4113 return append_declaration(declaration);
4116 static declaration_t *record_declaration(declaration_t *declaration)
4118 return internal_record_declaration(declaration, false);
4121 static declaration_t *record_function_definition(declaration_t *declaration)
4123 return internal_record_declaration(declaration, true);
4126 static void parser_error_multiple_definition(declaration_t *declaration,
4127 const source_position_t *source_position)
4129 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4130 declaration->symbol, &declaration->source_position);
4133 static bool is_declaration_specifier(const token_t *token,
4134 bool only_specifiers_qualifiers)
4136 switch(token->type) {
4141 return is_typedef_symbol(token->v.symbol);
4143 case T___extension__:
4145 return !only_specifiers_qualifiers;
4152 static void parse_init_declarator_rest(declaration_t *declaration)
4156 type_t *orig_type = declaration->type;
4157 type_t *type = skip_typeref(orig_type);
4159 if(declaration->init.initializer != NULL) {
4160 parser_error_multiple_definition(declaration, HERE);
4163 bool must_be_constant = false;
4164 if(declaration->storage_class == STORAGE_CLASS_STATIC
4165 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4166 || declaration->parent_scope == global_scope) {
4167 must_be_constant = true;
4170 parse_initializer_env_t env;
4171 env.type = orig_type;
4172 env.must_be_constant = must_be_constant;
4173 env.declaration = declaration;
4175 initializer_t *initializer = parse_initializer(&env);
4177 if(env.type != orig_type) {
4178 orig_type = env.type;
4179 type = skip_typeref(orig_type);
4180 declaration->type = env.type;
4183 if(is_type_function(type)) {
4184 errorf(&declaration->source_position,
4185 "initializers not allowed for function types at declator '%Y' (type '%T')",
4186 declaration->symbol, orig_type);
4188 declaration->init.initializer = initializer;
4192 /* parse rest of a declaration without any declarator */
4193 static void parse_anonymous_declaration_rest(
4194 const declaration_specifiers_t *specifiers,
4195 parsed_declaration_func finished_declaration)
4199 declaration_t *const declaration = allocate_declaration_zero();
4200 declaration->type = specifiers->type;
4201 declaration->declared_storage_class = specifiers->declared_storage_class;
4202 declaration->source_position = specifiers->source_position;
4203 declaration->modifiers = specifiers->modifiers;
4205 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4206 warningf(&declaration->source_position,
4207 "useless storage class in empty declaration");
4209 declaration->storage_class = STORAGE_CLASS_NONE;
4211 type_t *type = declaration->type;
4212 switch (type->kind) {
4213 case TYPE_COMPOUND_STRUCT:
4214 case TYPE_COMPOUND_UNION: {
4215 if (type->compound.declaration->symbol == NULL) {
4216 warningf(&declaration->source_position,
4217 "unnamed struct/union that defines no instances");
4226 warningf(&declaration->source_position, "empty declaration");
4230 finished_declaration(declaration);
4233 static void parse_declaration_rest(declaration_t *ndeclaration,
4234 const declaration_specifiers_t *specifiers,
4235 parsed_declaration_func finished_declaration)
4237 add_anchor_token(';');
4238 add_anchor_token('=');
4239 add_anchor_token(',');
4241 declaration_t *declaration = finished_declaration(ndeclaration);
4243 type_t *orig_type = declaration->type;
4244 type_t *type = skip_typeref(orig_type);
4246 if (type->kind != TYPE_FUNCTION &&
4247 declaration->is_inline &&
4248 is_type_valid(type)) {
4249 warningf(&declaration->source_position,
4250 "variable '%Y' declared 'inline'\n", declaration->symbol);
4253 if(token.type == '=') {
4254 parse_init_declarator_rest(declaration);
4257 if(token.type != ',')
4261 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4266 rem_anchor_token(';');
4267 rem_anchor_token('=');
4268 rem_anchor_token(',');
4271 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4273 symbol_t *symbol = declaration->symbol;
4274 if(symbol == NULL) {
4275 errorf(HERE, "anonymous declaration not valid as function parameter");
4278 namespace_t namespc = (namespace_t) declaration->namespc;
4279 if(namespc != NAMESPACE_NORMAL) {
4280 return record_declaration(declaration);
4283 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4284 if(previous_declaration == NULL ||
4285 previous_declaration->parent_scope != scope) {
4286 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4291 if(previous_declaration->type == NULL) {
4292 previous_declaration->type = declaration->type;
4293 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4294 previous_declaration->storage_class = declaration->storage_class;
4295 previous_declaration->parent_scope = scope;
4296 return previous_declaration;
4298 return record_declaration(declaration);
4302 static void parse_declaration(parsed_declaration_func finished_declaration)
4304 declaration_specifiers_t specifiers;
4305 memset(&specifiers, 0, sizeof(specifiers));
4306 parse_declaration_specifiers(&specifiers);
4308 if(token.type == ';') {
4309 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4311 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4312 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4316 static type_t *get_default_promoted_type(type_t *orig_type)
4318 type_t *result = orig_type;
4320 type_t *type = skip_typeref(orig_type);
4321 if(is_type_integer(type)) {
4322 result = promote_integer(type);
4323 } else if(type == type_float) {
4324 result = type_double;
4330 static void parse_kr_declaration_list(declaration_t *declaration)
4332 type_t *type = skip_typeref(declaration->type);
4333 if (!is_type_function(type))
4336 if (!type->function.kr_style_parameters)
4339 /* push function parameters */
4340 int top = environment_top();
4341 scope_t *last_scope = scope;
4342 set_scope(&declaration->scope);
4344 declaration_t *parameter = declaration->scope.declarations;
4345 for ( ; parameter != NULL; parameter = parameter->next) {
4346 assert(parameter->parent_scope == NULL);
4347 parameter->parent_scope = scope;
4348 environment_push(parameter);
4351 /* parse declaration list */
4352 while (is_declaration_specifier(&token, false)) {
4353 parse_declaration(finished_kr_declaration);
4356 /* pop function parameters */
4357 assert(scope == &declaration->scope);
4358 set_scope(last_scope);
4359 environment_pop_to(top);
4361 /* update function type */
4362 type_t *new_type = duplicate_type(type);
4364 function_parameter_t *parameters = NULL;
4365 function_parameter_t *last_parameter = NULL;
4367 declaration_t *parameter_declaration = declaration->scope.declarations;
4368 for( ; parameter_declaration != NULL;
4369 parameter_declaration = parameter_declaration->next) {
4370 type_t *parameter_type = parameter_declaration->type;
4371 if(parameter_type == NULL) {
4373 errorf(HERE, "no type specified for function parameter '%Y'",
4374 parameter_declaration->symbol);
4376 if (warning.implicit_int) {
4377 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4378 parameter_declaration->symbol);
4380 parameter_type = type_int;
4381 parameter_declaration->type = parameter_type;
4385 semantic_parameter(parameter_declaration);
4386 parameter_type = parameter_declaration->type;
4389 * we need the default promoted types for the function type
4391 parameter_type = get_default_promoted_type(parameter_type);
4393 function_parameter_t *function_parameter
4394 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4395 memset(function_parameter, 0, sizeof(function_parameter[0]));
4397 function_parameter->type = parameter_type;
4398 if(last_parameter != NULL) {
4399 last_parameter->next = function_parameter;
4401 parameters = function_parameter;
4403 last_parameter = function_parameter;
4406 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4408 new_type->function.parameters = parameters;
4409 new_type->function.unspecified_parameters = true;
4411 type = typehash_insert(new_type);
4412 if(type != new_type) {
4413 obstack_free(type_obst, new_type);
4416 declaration->type = type;
4419 static bool first_err = true;
4422 * When called with first_err set, prints the name of the current function,
4425 static void print_in_function(void) {
4428 diagnosticf("%s: In function '%Y':\n",
4429 current_function->source_position.input_name,
4430 current_function->symbol);
4435 * Check if all labels are defined in the current function.
4436 * Check if all labels are used in the current function.
4438 static void check_labels(void)
4440 for (const goto_statement_t *goto_statement = goto_first;
4441 goto_statement != NULL;
4442 goto_statement = goto_statement->next) {
4443 declaration_t *label = goto_statement->label;
4446 if (label->source_position.input_name == NULL) {
4447 print_in_function();
4448 errorf(&goto_statement->base.source_position,
4449 "label '%Y' used but not defined", label->symbol);
4452 goto_first = goto_last = NULL;
4454 if (warning.unused_label) {
4455 for (const label_statement_t *label_statement = label_first;
4456 label_statement != NULL;
4457 label_statement = label_statement->next) {
4458 const declaration_t *label = label_statement->label;
4460 if (! label->used) {
4461 print_in_function();
4462 warningf(&label_statement->base.source_position,
4463 "label '%Y' defined but not used", label->symbol);
4467 label_first = label_last = NULL;
4471 * Check declarations of current_function for unused entities.
4473 static void check_declarations(void)
4475 if (warning.unused_parameter) {
4476 const scope_t *scope = ¤t_function->scope;
4478 const declaration_t *parameter = scope->declarations;
4479 for (; parameter != NULL; parameter = parameter->next) {
4480 if (! parameter->used) {
4481 print_in_function();
4482 warningf(¶meter->source_position,
4483 "unused parameter '%Y'", parameter->symbol);
4487 if (warning.unused_variable) {
4491 static void parse_external_declaration(void)
4493 /* function-definitions and declarations both start with declaration
4495 declaration_specifiers_t specifiers;
4496 memset(&specifiers, 0, sizeof(specifiers));
4498 add_anchor_token(';');
4499 parse_declaration_specifiers(&specifiers);
4500 rem_anchor_token(';');
4502 /* must be a declaration */
4503 if(token.type == ';') {
4504 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4508 add_anchor_token(',');
4509 add_anchor_token('=');
4510 rem_anchor_token(';');
4512 /* declarator is common to both function-definitions and declarations */
4513 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4515 rem_anchor_token(',');
4516 rem_anchor_token('=');
4517 rem_anchor_token(';');
4519 /* must be a declaration */
4520 if(token.type == ',' || token.type == '=' || token.type == ';') {
4521 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4525 /* must be a function definition */
4526 parse_kr_declaration_list(ndeclaration);
4528 if(token.type != '{') {
4529 parse_error_expected("while parsing function definition", '{', NULL);
4530 eat_until_matching_token(';');
4534 type_t *type = ndeclaration->type;
4536 /* note that we don't skip typerefs: the standard doesn't allow them here
4537 * (so we can't use is_type_function here) */
4538 if(type->kind != TYPE_FUNCTION) {
4539 if (is_type_valid(type)) {
4540 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4541 type, ndeclaration->symbol);
4547 /* § 6.7.5.3 (14) a function definition with () means no
4548 * parameters (and not unspecified parameters) */
4549 if(type->function.unspecified_parameters
4550 && type->function.parameters == NULL
4551 && !type->function.kr_style_parameters) {
4552 type_t *duplicate = duplicate_type(type);
4553 duplicate->function.unspecified_parameters = false;
4555 type = typehash_insert(duplicate);
4556 if(type != duplicate) {
4557 obstack_free(type_obst, duplicate);
4559 ndeclaration->type = type;
4562 declaration_t *const declaration = record_function_definition(ndeclaration);
4563 if(ndeclaration != declaration) {
4564 declaration->scope = ndeclaration->scope;
4566 type = skip_typeref(declaration->type);
4568 /* push function parameters and switch scope */
4569 int top = environment_top();
4570 scope_t *last_scope = scope;
4571 set_scope(&declaration->scope);
4573 declaration_t *parameter = declaration->scope.declarations;
4574 for( ; parameter != NULL; parameter = parameter->next) {
4575 if(parameter->parent_scope == &ndeclaration->scope) {
4576 parameter->parent_scope = scope;
4578 assert(parameter->parent_scope == NULL
4579 || parameter->parent_scope == scope);
4580 parameter->parent_scope = scope;
4581 if (parameter->symbol == NULL) {
4582 errorf(&ndeclaration->source_position, "parameter name omitted");
4585 environment_push(parameter);
4588 if(declaration->init.statement != NULL) {
4589 parser_error_multiple_definition(declaration, HERE);
4591 goto end_of_parse_external_declaration;
4593 /* parse function body */
4594 int label_stack_top = label_top();
4595 declaration_t *old_current_function = current_function;
4596 current_function = declaration;
4598 declaration->init.statement = parse_compound_statement(false);
4601 check_declarations();
4603 assert(current_function == declaration);
4604 current_function = old_current_function;
4605 label_pop_to(label_stack_top);
4608 end_of_parse_external_declaration:
4609 assert(scope == &declaration->scope);
4610 set_scope(last_scope);
4611 environment_pop_to(top);
4614 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4615 source_position_t *source_position)
4617 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4619 type->bitfield.base_type = base_type;
4620 type->bitfield.size = size;
4625 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4628 declaration_t *iter = compound_declaration->scope.declarations;
4629 for( ; iter != NULL; iter = iter->next) {
4630 if(iter->namespc != NAMESPACE_NORMAL)
4633 if(iter->symbol == NULL) {
4634 type_t *type = skip_typeref(iter->type);
4635 if(is_type_compound(type)) {
4636 declaration_t *result
4637 = find_compound_entry(type->compound.declaration, symbol);
4644 if(iter->symbol == symbol) {
4652 static void parse_compound_declarators(declaration_t *struct_declaration,
4653 const declaration_specifiers_t *specifiers)
4655 declaration_t *last_declaration = struct_declaration->scope.declarations;
4656 if(last_declaration != NULL) {
4657 while(last_declaration->next != NULL) {
4658 last_declaration = last_declaration->next;
4663 declaration_t *declaration;
4665 if(token.type == ':') {
4666 source_position_t source_position = *HERE;
4669 type_t *base_type = specifiers->type;
4670 expression_t *size = parse_constant_expression();
4672 if(!is_type_integer(skip_typeref(base_type))) {
4673 errorf(HERE, "bitfield base type '%T' is not an integer type",
4677 type_t *type = make_bitfield_type(base_type, size, &source_position);
4679 declaration = allocate_declaration_zero();
4680 declaration->namespc = NAMESPACE_NORMAL;
4681 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4682 declaration->storage_class = STORAGE_CLASS_NONE;
4683 declaration->source_position = source_position;
4684 declaration->modifiers = specifiers->modifiers;
4685 declaration->type = type;
4687 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4689 type_t *orig_type = declaration->type;
4690 type_t *type = skip_typeref(orig_type);
4692 if(token.type == ':') {
4693 source_position_t source_position = *HERE;
4695 expression_t *size = parse_constant_expression();
4697 if(!is_type_integer(type)) {
4698 errorf(HERE, "bitfield base type '%T' is not an "
4699 "integer type", orig_type);
4702 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4703 declaration->type = bitfield_type;
4705 /* TODO we ignore arrays for now... what is missing is a check
4706 * that they're at the end of the struct */
4707 if(is_type_incomplete(type) && !is_type_array(type)) {
4709 "compound member '%Y' has incomplete type '%T'",
4710 declaration->symbol, orig_type);
4711 } else if(is_type_function(type)) {
4712 errorf(HERE, "compound member '%Y' must not have function "
4713 "type '%T'", declaration->symbol, orig_type);
4718 /* make sure we don't define a symbol multiple times */
4719 symbol_t *symbol = declaration->symbol;
4720 if(symbol != NULL) {
4721 declaration_t *prev_decl
4722 = find_compound_entry(struct_declaration, symbol);
4724 if(prev_decl != NULL) {
4725 assert(prev_decl->symbol == symbol);
4726 errorf(&declaration->source_position,
4727 "multiple declarations of symbol '%Y' (declared %P)",
4728 symbol, &prev_decl->source_position);
4732 /* append declaration */
4733 if(last_declaration != NULL) {
4734 last_declaration->next = declaration;
4736 struct_declaration->scope.declarations = declaration;
4738 last_declaration = declaration;
4740 if(token.type != ',')
4750 static void parse_compound_type_entries(declaration_t *compound_declaration)
4753 add_anchor_token('}');
4755 while(token.type != '}' && token.type != T_EOF) {
4756 declaration_specifiers_t specifiers;
4757 memset(&specifiers, 0, sizeof(specifiers));
4758 parse_declaration_specifiers(&specifiers);
4760 parse_compound_declarators(compound_declaration, &specifiers);
4762 rem_anchor_token('}');
4764 if(token.type == T_EOF) {
4765 errorf(HERE, "EOF while parsing struct");
4770 static type_t *parse_typename(void)
4772 declaration_specifiers_t specifiers;
4773 memset(&specifiers, 0, sizeof(specifiers));
4774 parse_declaration_specifiers(&specifiers);
4775 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4776 /* TODO: improve error message, user does probably not know what a
4777 * storage class is...
4779 errorf(HERE, "typename may not have a storage class");
4782 type_t *result = parse_abstract_declarator(specifiers.type);
4790 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4791 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4792 expression_t *left);
4794 typedef struct expression_parser_function_t expression_parser_function_t;
4795 struct expression_parser_function_t {
4796 unsigned precedence;
4797 parse_expression_function parser;
4798 unsigned infix_precedence;
4799 parse_expression_infix_function infix_parser;
4802 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4805 * Prints an error message if an expression was expected but not read
4807 static expression_t *expected_expression_error(void)
4809 /* skip the error message if the error token was read */
4810 if (token.type != T_ERROR) {
4811 errorf(HERE, "expected expression, got token '%K'", &token);
4815 return create_invalid_expression();
4819 * Parse a string constant.
4821 static expression_t *parse_string_const(void)
4824 if (token.type == T_STRING_LITERAL) {
4825 string_t res = token.v.string;
4827 while (token.type == T_STRING_LITERAL) {
4828 res = concat_strings(&res, &token.v.string);
4831 if (token.type != T_WIDE_STRING_LITERAL) {
4832 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4833 /* note: that we use type_char_ptr here, which is already the
4834 * automatic converted type. revert_automatic_type_conversion
4835 * will construct the array type */
4836 cnst->base.type = type_char_ptr;
4837 cnst->string.value = res;
4841 wres = concat_string_wide_string(&res, &token.v.wide_string);
4843 wres = token.v.wide_string;
4848 switch (token.type) {
4849 case T_WIDE_STRING_LITERAL:
4850 wres = concat_wide_strings(&wres, &token.v.wide_string);
4853 case T_STRING_LITERAL:
4854 wres = concat_wide_string_string(&wres, &token.v.string);
4858 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4859 cnst->base.type = type_wchar_t_ptr;
4860 cnst->wide_string.value = wres;
4869 * Parse an integer constant.
4871 static expression_t *parse_int_const(void)
4873 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4874 cnst->base.source_position = *HERE;
4875 cnst->base.type = token.datatype;
4876 cnst->conste.v.int_value = token.v.intvalue;
4884 * Parse a character constant.
4886 static expression_t *parse_character_constant(void)
4888 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4890 cnst->base.source_position = *HERE;
4891 cnst->base.type = token.datatype;
4892 cnst->conste.v.character = token.v.string;
4894 if (cnst->conste.v.character.size != 1) {
4895 if (warning.multichar && (c_mode & _GNUC)) {
4897 warningf(HERE, "multi-character character constant");
4899 errorf(HERE, "more than 1 characters in character constant");
4908 * Parse a wide character constant.
4910 static expression_t *parse_wide_character_constant(void)
4912 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4914 cnst->base.source_position = *HERE;
4915 cnst->base.type = token.datatype;
4916 cnst->conste.v.wide_character = token.v.wide_string;
4918 if (cnst->conste.v.wide_character.size != 1) {
4919 if (warning.multichar && (c_mode & _GNUC)) {
4921 warningf(HERE, "multi-character character constant");
4923 errorf(HERE, "more than 1 characters in character constant");
4932 * Parse a float constant.
4934 static expression_t *parse_float_const(void)
4936 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4937 cnst->base.type = token.datatype;
4938 cnst->conste.v.float_value = token.v.floatvalue;
4945 static declaration_t *create_implicit_function(symbol_t *symbol,
4946 const source_position_t *source_position)
4948 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4949 ntype->function.return_type = type_int;
4950 ntype->function.unspecified_parameters = true;
4952 type_t *type = typehash_insert(ntype);
4957 declaration_t *const declaration = allocate_declaration_zero();
4958 declaration->storage_class = STORAGE_CLASS_EXTERN;
4959 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4960 declaration->type = type;
4961 declaration->symbol = symbol;
4962 declaration->source_position = *source_position;
4964 bool strict_prototypes_old = warning.strict_prototypes;
4965 warning.strict_prototypes = false;
4966 record_declaration(declaration);
4967 warning.strict_prototypes = strict_prototypes_old;
4973 * Creates a return_type (func)(argument_type) function type if not
4976 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
4977 type_t *argument_type2)
4979 function_parameter_t *parameter2
4980 = obstack_alloc(type_obst, sizeof(parameter2[0]));
4981 memset(parameter2, 0, sizeof(parameter2[0]));
4982 parameter2->type = argument_type2;
4984 function_parameter_t *parameter1
4985 = obstack_alloc(type_obst, sizeof(parameter1[0]));
4986 memset(parameter1, 0, sizeof(parameter1[0]));
4987 parameter1->type = argument_type1;
4988 parameter1->next = parameter2;
4990 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4991 type->function.return_type = return_type;
4992 type->function.parameters = parameter1;
4994 type_t *result = typehash_insert(type);
4995 if(result != type) {
5003 * Creates a return_type (func)(argument_type) function type if not
5006 * @param return_type the return type
5007 * @param argument_type the argument type
5009 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5011 function_parameter_t *parameter
5012 = obstack_alloc(type_obst, sizeof(parameter[0]));
5013 memset(parameter, 0, sizeof(parameter[0]));
5014 parameter->type = argument_type;
5016 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5017 type->function.return_type = return_type;
5018 type->function.parameters = parameter;
5020 type_t *result = typehash_insert(type);
5021 if(result != type) {
5028 static type_t *make_function_0_type(type_t *return_type)
5030 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5031 type->function.return_type = return_type;
5032 type->function.parameters = NULL;
5034 type_t *result = typehash_insert(type);
5035 if(result != type) {
5043 * Creates a function type for some function like builtins.
5045 * @param symbol the symbol describing the builtin
5047 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5049 switch(symbol->ID) {
5050 case T___builtin_alloca:
5051 return make_function_1_type(type_void_ptr, type_size_t);
5052 case T___builtin_huge_val:
5053 return make_function_0_type(type_double);
5054 case T___builtin_nan:
5055 return make_function_1_type(type_double, type_char_ptr);
5056 case T___builtin_nanf:
5057 return make_function_1_type(type_float, type_char_ptr);
5058 case T___builtin_nand:
5059 return make_function_1_type(type_long_double, type_char_ptr);
5060 case T___builtin_va_end:
5061 return make_function_1_type(type_void, type_valist);
5062 case T___builtin_expect:
5063 return make_function_2_type(type_long, type_long, type_long);
5065 internal_errorf(HERE, "not implemented builtin symbol found");
5070 * Performs automatic type cast as described in § 6.3.2.1.
5072 * @param orig_type the original type
5074 static type_t *automatic_type_conversion(type_t *orig_type)
5076 type_t *type = skip_typeref(orig_type);
5077 if(is_type_array(type)) {
5078 array_type_t *array_type = &type->array;
5079 type_t *element_type = array_type->element_type;
5080 unsigned qualifiers = array_type->base.qualifiers;
5082 return make_pointer_type(element_type, qualifiers);
5085 if(is_type_function(type)) {
5086 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5093 * reverts the automatic casts of array to pointer types and function
5094 * to function-pointer types as defined § 6.3.2.1
5096 type_t *revert_automatic_type_conversion(const expression_t *expression)
5098 switch (expression->kind) {
5099 case EXPR_REFERENCE: return expression->reference.declaration->type;
5100 case EXPR_SELECT: return expression->select.compound_entry->type;
5102 case EXPR_UNARY_DEREFERENCE: {
5103 const expression_t *const value = expression->unary.value;
5104 type_t *const type = skip_typeref(value->base.type);
5105 assert(is_type_pointer(type));
5106 return type->pointer.points_to;
5109 case EXPR_BUILTIN_SYMBOL:
5110 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5112 case EXPR_ARRAY_ACCESS: {
5113 const expression_t *array_ref = expression->array_access.array_ref;
5114 type_t *type_left = skip_typeref(array_ref->base.type);
5115 if (!is_type_valid(type_left))
5117 assert(is_type_pointer(type_left));
5118 return type_left->pointer.points_to;
5121 case EXPR_STRING_LITERAL: {
5122 size_t size = expression->string.value.size;
5123 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5126 case EXPR_WIDE_STRING_LITERAL: {
5127 size_t size = expression->wide_string.value.size;
5128 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5131 case EXPR_COMPOUND_LITERAL:
5132 return expression->compound_literal.type;
5137 return expression->base.type;
5140 static expression_t *parse_reference(void)
5142 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5144 reference_expression_t *ref = &expression->reference;
5145 symbol_t *const symbol = token.v.symbol;
5147 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5149 source_position_t source_position = token.source_position;
5152 if(declaration == NULL) {
5153 if (! strict_mode && token.type == '(') {
5154 /* an implicitly defined function */
5155 if (warning.implicit_function_declaration) {
5156 warningf(HERE, "implicit declaration of function '%Y'",
5160 declaration = create_implicit_function(symbol,
5163 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5164 return create_invalid_expression();
5168 type_t *type = declaration->type;
5170 /* we always do the auto-type conversions; the & and sizeof parser contains
5171 * code to revert this! */
5172 type = automatic_type_conversion(type);
5174 ref->declaration = declaration;
5175 ref->base.type = type;
5177 /* this declaration is used */
5178 declaration->used = true;
5180 /* check for deprecated functions */
5181 if(declaration->deprecated != 0) {
5182 const char *prefix = "";
5183 if (is_type_function(declaration->type))
5184 prefix = "function ";
5186 if (declaration->deprecated_string != NULL) {
5187 warningf(&source_position,
5188 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5189 declaration->deprecated_string);
5191 warningf(&source_position,
5192 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5199 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5203 /* TODO check if explicit cast is allowed and issue warnings/errors */
5206 static expression_t *parse_compound_literal(type_t *type)
5208 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5210 parse_initializer_env_t env;
5212 env.declaration = NULL;
5213 env.must_be_constant = false;
5214 initializer_t *initializer = parse_initializer(&env);
5217 expression->compound_literal.initializer = initializer;
5218 expression->compound_literal.type = type;
5219 expression->base.type = automatic_type_conversion(type);
5225 * Parse a cast expression.
5227 static expression_t *parse_cast(void)
5229 source_position_t source_position = token.source_position;
5231 type_t *type = parse_typename();
5233 /* matching add_anchor_token() is at call site */
5234 rem_anchor_token(')');
5237 if(token.type == '{') {
5238 return parse_compound_literal(type);
5241 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5242 cast->base.source_position = source_position;
5244 expression_t *value = parse_sub_expression(20);
5246 check_cast_allowed(value, type);
5248 cast->base.type = type;
5249 cast->unary.value = value;
5253 return create_invalid_expression();
5257 * Parse a statement expression.
5259 static expression_t *parse_statement_expression(void)
5261 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5263 statement_t *statement = parse_compound_statement(true);
5264 expression->statement.statement = statement;
5265 expression->base.source_position = statement->base.source_position;
5267 /* find last statement and use its type */
5268 type_t *type = type_void;
5269 const statement_t *stmt = statement->compound.statements;
5271 while (stmt->base.next != NULL)
5272 stmt = stmt->base.next;
5274 if (stmt->kind == STATEMENT_EXPRESSION) {
5275 type = stmt->expression.expression->base.type;
5278 warningf(&expression->base.source_position, "empty statement expression ({})");
5280 expression->base.type = type;
5286 return create_invalid_expression();
5290 * Parse a braced expression.
5292 static expression_t *parse_brace_expression(void)
5295 add_anchor_token(')');
5297 switch(token.type) {
5299 /* gcc extension: a statement expression */
5300 return parse_statement_expression();
5304 return parse_cast();
5306 if(is_typedef_symbol(token.v.symbol)) {
5307 return parse_cast();
5311 expression_t *result = parse_expression();
5312 rem_anchor_token(')');
5317 return create_invalid_expression();
5320 static expression_t *parse_function_keyword(void)
5325 if (current_function == NULL) {
5326 errorf(HERE, "'__func__' used outside of a function");
5329 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5330 expression->base.type = type_char_ptr;
5331 expression->funcname.kind = FUNCNAME_FUNCTION;
5336 static expression_t *parse_pretty_function_keyword(void)
5338 eat(T___PRETTY_FUNCTION__);
5340 if (current_function == NULL) {
5341 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5344 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5345 expression->base.type = type_char_ptr;
5346 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5351 static expression_t *parse_funcsig_keyword(void)
5355 if (current_function == NULL) {
5356 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5359 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5360 expression->base.type = type_char_ptr;
5361 expression->funcname.kind = FUNCNAME_FUNCSIG;
5366 static expression_t *parse_funcdname_keyword(void)
5368 eat(T___FUNCDNAME__);
5370 if (current_function == NULL) {
5371 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5374 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5375 expression->base.type = type_char_ptr;
5376 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5381 static designator_t *parse_designator(void)
5383 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5384 result->source_position = *HERE;
5386 if(token.type != T_IDENTIFIER) {
5387 parse_error_expected("while parsing member designator",
5388 T_IDENTIFIER, NULL);
5391 result->symbol = token.v.symbol;
5394 designator_t *last_designator = result;
5396 if(token.type == '.') {
5398 if(token.type != T_IDENTIFIER) {
5399 parse_error_expected("while parsing member designator",
5400 T_IDENTIFIER, NULL);
5403 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5404 designator->source_position = *HERE;
5405 designator->symbol = token.v.symbol;
5408 last_designator->next = designator;
5409 last_designator = designator;
5412 if(token.type == '[') {
5414 add_anchor_token(']');
5415 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5416 designator->source_position = *HERE;
5417 designator->array_index = parse_expression();
5418 rem_anchor_token(']');
5420 if(designator->array_index == NULL) {
5424 last_designator->next = designator;
5425 last_designator = designator;
5437 * Parse the __builtin_offsetof() expression.
5439 static expression_t *parse_offsetof(void)
5441 eat(T___builtin_offsetof);
5443 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5444 expression->base.type = type_size_t;
5447 add_anchor_token(',');
5448 type_t *type = parse_typename();
5449 rem_anchor_token(',');
5451 add_anchor_token(')');
5452 designator_t *designator = parse_designator();
5453 rem_anchor_token(')');
5456 expression->offsetofe.type = type;
5457 expression->offsetofe.designator = designator;
5460 memset(&path, 0, sizeof(path));
5461 path.top_type = type;
5462 path.path = NEW_ARR_F(type_path_entry_t, 0);
5464 descend_into_subtype(&path);
5466 if(!walk_designator(&path, designator, true)) {
5467 return create_invalid_expression();
5470 DEL_ARR_F(path.path);
5474 return create_invalid_expression();
5478 * Parses a _builtin_va_start() expression.
5480 static expression_t *parse_va_start(void)
5482 eat(T___builtin_va_start);
5484 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5487 add_anchor_token(',');
5488 expression->va_starte.ap = parse_assignment_expression();
5489 rem_anchor_token(',');
5491 expression_t *const expr = parse_assignment_expression();
5492 if (expr->kind == EXPR_REFERENCE) {
5493 declaration_t *const decl = expr->reference.declaration;
5495 return create_invalid_expression();
5496 if (decl->parent_scope == ¤t_function->scope &&
5497 decl->next == NULL) {
5498 expression->va_starte.parameter = decl;
5503 errorf(&expr->base.source_position,
5504 "second argument of 'va_start' must be last parameter of the current function");
5506 return create_invalid_expression();
5510 * Parses a _builtin_va_arg() expression.
5512 static expression_t *parse_va_arg(void)
5514 eat(T___builtin_va_arg);
5516 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5519 expression->va_arge.ap = parse_assignment_expression();
5521 expression->base.type = parse_typename();
5526 return create_invalid_expression();
5529 static expression_t *parse_builtin_symbol(void)
5531 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5533 symbol_t *symbol = token.v.symbol;
5535 expression->builtin_symbol.symbol = symbol;
5538 type_t *type = get_builtin_symbol_type(symbol);
5539 type = automatic_type_conversion(type);
5541 expression->base.type = type;
5546 * Parses a __builtin_constant() expression.
5548 static expression_t *parse_builtin_constant(void)
5550 eat(T___builtin_constant_p);
5552 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5555 add_anchor_token(')');
5556 expression->builtin_constant.value = parse_assignment_expression();
5557 rem_anchor_token(')');
5559 expression->base.type = type_int;
5563 return create_invalid_expression();
5567 * Parses a __builtin_prefetch() expression.
5569 static expression_t *parse_builtin_prefetch(void)
5571 eat(T___builtin_prefetch);
5573 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5576 add_anchor_token(')');
5577 expression->builtin_prefetch.adr = parse_assignment_expression();
5578 if (token.type == ',') {
5580 expression->builtin_prefetch.rw = parse_assignment_expression();
5582 if (token.type == ',') {
5584 expression->builtin_prefetch.locality = parse_assignment_expression();
5586 rem_anchor_token(')');
5588 expression->base.type = type_void;
5592 return create_invalid_expression();
5596 * Parses a __builtin_is_*() compare expression.
5598 static expression_t *parse_compare_builtin(void)
5600 expression_t *expression;
5602 switch(token.type) {
5603 case T___builtin_isgreater:
5604 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5606 case T___builtin_isgreaterequal:
5607 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5609 case T___builtin_isless:
5610 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5612 case T___builtin_islessequal:
5613 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5615 case T___builtin_islessgreater:
5616 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5618 case T___builtin_isunordered:
5619 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5622 internal_errorf(HERE, "invalid compare builtin found");
5625 expression->base.source_position = *HERE;
5629 expression->binary.left = parse_assignment_expression();
5631 expression->binary.right = parse_assignment_expression();
5634 type_t *const orig_type_left = expression->binary.left->base.type;
5635 type_t *const orig_type_right = expression->binary.right->base.type;
5637 type_t *const type_left = skip_typeref(orig_type_left);
5638 type_t *const type_right = skip_typeref(orig_type_right);
5639 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5640 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5641 type_error_incompatible("invalid operands in comparison",
5642 &expression->base.source_position, orig_type_left, orig_type_right);
5645 semantic_comparison(&expression->binary);
5650 return create_invalid_expression();
5655 * Parses a __builtin_expect() expression.
5657 static expression_t *parse_builtin_expect(void)
5659 eat(T___builtin_expect);
5661 expression_t *expression
5662 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5665 expression->binary.left = parse_assignment_expression();
5667 expression->binary.right = parse_constant_expression();
5670 expression->base.type = expression->binary.left->base.type;
5674 return create_invalid_expression();
5679 * Parses a MS assume() expression.
5681 static expression_t *parse_assume(void) {
5684 expression_t *expression
5685 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5688 add_anchor_token(')');
5689 expression->unary.value = parse_assignment_expression();
5690 rem_anchor_token(')');
5693 expression->base.type = type_void;
5696 return create_invalid_expression();
5700 * Parse a microsoft __noop expression.
5702 static expression_t *parse_noop_expression(void) {
5703 source_position_t source_position = *HERE;
5706 if (token.type == '(') {
5707 /* parse arguments */
5709 add_anchor_token(')');
5710 add_anchor_token(',');
5712 if(token.type != ')') {
5714 (void)parse_assignment_expression();
5715 if(token.type != ',')
5721 rem_anchor_token(',');
5722 rem_anchor_token(')');
5725 /* the result is a (int)0 */
5726 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5727 cnst->base.source_position = source_position;
5728 cnst->base.type = type_int;
5729 cnst->conste.v.int_value = 0;
5730 cnst->conste.is_ms_noop = true;
5735 return create_invalid_expression();
5739 * Parses a primary expression.
5741 static expression_t *parse_primary_expression(void)
5743 switch (token.type) {
5744 case T_INTEGER: return parse_int_const();
5745 case T_CHARACTER_CONSTANT: return parse_character_constant();
5746 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5747 case T_FLOATINGPOINT: return parse_float_const();
5748 case T_STRING_LITERAL:
5749 case T_WIDE_STRING_LITERAL: return parse_string_const();
5750 case T_IDENTIFIER: return parse_reference();
5751 case T___FUNCTION__:
5752 case T___func__: return parse_function_keyword();
5753 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5754 case T___FUNCSIG__: return parse_funcsig_keyword();
5755 case T___FUNCDNAME__: return parse_funcdname_keyword();
5756 case T___builtin_offsetof: return parse_offsetof();
5757 case T___builtin_va_start: return parse_va_start();
5758 case T___builtin_va_arg: return parse_va_arg();
5759 case T___builtin_expect:
5760 case T___builtin_alloca:
5761 case T___builtin_nan:
5762 case T___builtin_nand:
5763 case T___builtin_nanf:
5764 case T___builtin_huge_val:
5765 case T___builtin_va_end: return parse_builtin_symbol();
5766 case T___builtin_isgreater:
5767 case T___builtin_isgreaterequal:
5768 case T___builtin_isless:
5769 case T___builtin_islessequal:
5770 case T___builtin_islessgreater:
5771 case T___builtin_isunordered: return parse_compare_builtin();
5772 case T___builtin_constant_p: return parse_builtin_constant();
5773 case T___builtin_prefetch: return parse_builtin_prefetch();
5774 case T__assume: return parse_assume();
5776 case '(': return parse_brace_expression();
5777 case T___noop: return parse_noop_expression();
5780 errorf(HERE, "unexpected token %K, expected an expression", &token);
5781 return create_invalid_expression();
5785 * Check if the expression has the character type and issue a warning then.
5787 static void check_for_char_index_type(const expression_t *expression) {
5788 type_t *const type = expression->base.type;
5789 const type_t *const base_type = skip_typeref(type);
5791 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5792 warning.char_subscripts) {
5793 warningf(&expression->base.source_position,
5794 "array subscript has type '%T'", type);
5798 static expression_t *parse_array_expression(unsigned precedence,
5804 add_anchor_token(']');
5806 expression_t *inside = parse_expression();
5808 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5810 array_access_expression_t *array_access = &expression->array_access;
5812 type_t *const orig_type_left = left->base.type;
5813 type_t *const orig_type_inside = inside->base.type;
5815 type_t *const type_left = skip_typeref(orig_type_left);
5816 type_t *const type_inside = skip_typeref(orig_type_inside);
5818 type_t *return_type;
5819 if (is_type_pointer(type_left)) {
5820 return_type = type_left->pointer.points_to;
5821 array_access->array_ref = left;
5822 array_access->index = inside;
5823 check_for_char_index_type(inside);
5824 } else if (is_type_pointer(type_inside)) {
5825 return_type = type_inside->pointer.points_to;
5826 array_access->array_ref = inside;
5827 array_access->index = left;
5828 array_access->flipped = true;
5829 check_for_char_index_type(left);
5831 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5833 "array access on object with non-pointer types '%T', '%T'",
5834 orig_type_left, orig_type_inside);
5836 return_type = type_error_type;
5837 array_access->array_ref = create_invalid_expression();
5840 rem_anchor_token(']');
5841 if(token.type != ']') {
5842 parse_error_expected("Problem while parsing array access", ']', NULL);
5847 return_type = automatic_type_conversion(return_type);
5848 expression->base.type = return_type;
5853 static expression_t *parse_typeprop(expression_kind_t const kind,
5854 source_position_t const pos,
5855 unsigned const precedence)
5857 expression_t *tp_expression = allocate_expression_zero(kind);
5858 tp_expression->base.type = type_size_t;
5859 tp_expression->base.source_position = pos;
5861 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5863 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5865 add_anchor_token(')');
5866 type_t* const orig_type = parse_typename();
5867 tp_expression->typeprop.type = orig_type;
5869 type_t const* const type = skip_typeref(orig_type);
5870 char const* const wrong_type =
5871 is_type_incomplete(type) ? "incomplete" :
5872 type->kind == TYPE_FUNCTION ? "function designator" :
5873 type->kind == TYPE_BITFIELD ? "bitfield" :
5875 if (wrong_type != NULL) {
5876 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5877 what, wrong_type, type);
5880 rem_anchor_token(')');
5883 expression_t *expression = parse_sub_expression(precedence);
5885 type_t* const orig_type = revert_automatic_type_conversion(expression);
5886 expression->base.type = orig_type;
5888 type_t const* const type = skip_typeref(orig_type);
5889 char const* const wrong_type =
5890 is_type_incomplete(type) ? "incomplete" :
5891 type->kind == TYPE_FUNCTION ? "function designator" :
5892 type->kind == TYPE_BITFIELD ? "bitfield" :
5894 if (wrong_type != NULL) {
5895 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5898 tp_expression->typeprop.type = expression->base.type;
5899 tp_expression->typeprop.tp_expression = expression;
5902 return tp_expression;
5904 return create_invalid_expression();
5907 static expression_t *parse_sizeof(unsigned precedence)
5909 source_position_t pos = *HERE;
5911 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5914 static expression_t *parse_alignof(unsigned precedence)
5916 source_position_t pos = *HERE;
5918 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5921 static expression_t *parse_select_expression(unsigned precedence,
5922 expression_t *compound)
5925 assert(token.type == '.' || token.type == T_MINUSGREATER);
5927 bool is_pointer = (token.type == T_MINUSGREATER);
5930 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5931 select->select.compound = compound;
5933 if (token.type != T_IDENTIFIER) {
5934 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5937 symbol_t *symbol = token.v.symbol;
5938 select->select.symbol = symbol;
5941 type_t *const orig_type = compound->base.type;
5942 type_t *const type = skip_typeref(orig_type);
5944 type_t *type_left = type;
5946 if (!is_type_pointer(type)) {
5947 if (is_type_valid(type)) {
5948 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5950 return create_invalid_expression();
5952 type_left = type->pointer.points_to;
5954 type_left = skip_typeref(type_left);
5956 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5957 type_left->kind != TYPE_COMPOUND_UNION) {
5958 if (is_type_valid(type_left)) {
5959 errorf(HERE, "request for member '%Y' in something not a struct or "
5960 "union, but '%T'", symbol, type_left);
5962 return create_invalid_expression();
5965 declaration_t *const declaration = type_left->compound.declaration;
5967 if (!declaration->init.complete) {
5968 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5970 return create_invalid_expression();
5973 declaration_t *iter = find_compound_entry(declaration, symbol);
5975 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5976 return create_invalid_expression();
5979 /* we always do the auto-type conversions; the & and sizeof parser contains
5980 * code to revert this! */
5981 type_t *expression_type = automatic_type_conversion(iter->type);
5983 select->select.compound_entry = iter;
5984 select->base.type = expression_type;
5986 type_t *skipped = skip_typeref(iter->type);
5987 if (skipped->kind == TYPE_BITFIELD) {
5988 select->base.type = skipped->bitfield.base_type;
5994 static void check_call_argument(const function_parameter_t *parameter,
5995 call_argument_t *argument)
5997 type_t *expected_type = parameter->type;
5998 type_t *expected_type_skip = skip_typeref(expected_type);
5999 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6000 expression_t *arg_expr = argument->expression;
6002 /* handle transparent union gnu extension */
6003 if (is_type_union(expected_type_skip)
6004 && (expected_type_skip->base.modifiers
6005 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6006 declaration_t *union_decl = expected_type_skip->compound.declaration;
6008 declaration_t *declaration = union_decl->scope.declarations;
6009 type_t *best_type = NULL;
6010 for ( ; declaration != NULL; declaration = declaration->next) {
6011 type_t *decl_type = declaration->type;
6012 error = semantic_assign(decl_type, arg_expr);
6013 if (error == ASSIGN_ERROR_INCOMPATIBLE
6014 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6017 if (error == ASSIGN_SUCCESS) {
6018 best_type = decl_type;
6019 } else if (best_type == NULL) {
6020 best_type = decl_type;
6024 if (best_type != NULL) {
6025 expected_type = best_type;
6029 error = semantic_assign(expected_type, arg_expr);
6030 argument->expression = create_implicit_cast(argument->expression,
6033 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6034 report_assign_error(error, expected_type, arg_expr, "function call",
6035 &arg_expr->base.source_position);
6039 * Parse a call expression, ie. expression '( ... )'.
6041 * @param expression the function address
6043 static expression_t *parse_call_expression(unsigned precedence,
6044 expression_t *expression)
6047 expression_t *result = allocate_expression_zero(EXPR_CALL);
6048 result->base.source_position = expression->base.source_position;
6050 call_expression_t *call = &result->call;
6051 call->function = expression;
6053 type_t *const orig_type = expression->base.type;
6054 type_t *const type = skip_typeref(orig_type);
6056 function_type_t *function_type = NULL;
6057 if (is_type_pointer(type)) {
6058 type_t *const to_type = skip_typeref(type->pointer.points_to);
6060 if (is_type_function(to_type)) {
6061 function_type = &to_type->function;
6062 call->base.type = function_type->return_type;
6066 if (function_type == NULL && is_type_valid(type)) {
6067 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6070 /* parse arguments */
6072 add_anchor_token(')');
6073 add_anchor_token(',');
6075 if(token.type != ')') {
6076 call_argument_t *last_argument = NULL;
6079 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6081 argument->expression = parse_assignment_expression();
6082 if(last_argument == NULL) {
6083 call->arguments = argument;
6085 last_argument->next = argument;
6087 last_argument = argument;
6089 if(token.type != ',')
6094 rem_anchor_token(',');
6095 rem_anchor_token(')');
6098 if(function_type == NULL)
6101 function_parameter_t *parameter = function_type->parameters;
6102 call_argument_t *argument = call->arguments;
6103 if (!function_type->unspecified_parameters) {
6104 for( ; parameter != NULL && argument != NULL;
6105 parameter = parameter->next, argument = argument->next) {
6106 check_call_argument(parameter, argument);
6109 if (parameter != NULL) {
6110 errorf(HERE, "too few arguments to function '%E'", expression);
6111 } else if (argument != NULL && !function_type->variadic) {
6112 errorf(HERE, "too many arguments to function '%E'", expression);
6116 /* do default promotion */
6117 for( ; argument != NULL; argument = argument->next) {
6118 type_t *type = argument->expression->base.type;
6120 type = get_default_promoted_type(type);
6122 argument->expression
6123 = create_implicit_cast(argument->expression, type);
6126 check_format(&result->call);
6130 return create_invalid_expression();
6133 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6135 static bool same_compound_type(const type_t *type1, const type_t *type2)
6138 is_type_compound(type1) &&
6139 type1->kind == type2->kind &&
6140 type1->compound.declaration == type2->compound.declaration;
6144 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6146 * @param expression the conditional expression
6148 static expression_t *parse_conditional_expression(unsigned precedence,
6149 expression_t *expression)
6152 add_anchor_token(':');
6154 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6156 conditional_expression_t *conditional = &result->conditional;
6157 conditional->condition = expression;
6160 type_t *const condition_type_orig = expression->base.type;
6161 type_t *const condition_type = skip_typeref(condition_type_orig);
6162 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6163 type_error("expected a scalar type in conditional condition",
6164 &expression->base.source_position, condition_type_orig);
6167 expression_t *true_expression = parse_expression();
6168 rem_anchor_token(':');
6170 expression_t *false_expression = parse_sub_expression(precedence);
6172 type_t *const orig_true_type = true_expression->base.type;
6173 type_t *const orig_false_type = false_expression->base.type;
6174 type_t *const true_type = skip_typeref(orig_true_type);
6175 type_t *const false_type = skip_typeref(orig_false_type);
6178 type_t *result_type;
6179 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6180 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6181 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6182 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6183 warningf(&expression->base.source_position,
6184 "ISO C forbids conditional expression with only one void side");
6186 result_type = type_void;
6187 } else if (is_type_arithmetic(true_type)
6188 && is_type_arithmetic(false_type)) {
6189 result_type = semantic_arithmetic(true_type, false_type);
6191 true_expression = create_implicit_cast(true_expression, result_type);
6192 false_expression = create_implicit_cast(false_expression, result_type);
6194 conditional->true_expression = true_expression;
6195 conditional->false_expression = false_expression;
6196 conditional->base.type = result_type;
6197 } else if (same_compound_type(true_type, false_type)) {
6198 /* just take 1 of the 2 types */
6199 result_type = true_type;
6200 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6201 type_t *pointer_type;
6203 expression_t *other_expression;
6204 if (is_type_pointer(true_type)) {
6205 pointer_type = true_type;
6206 other_type = false_type;
6207 other_expression = false_expression;
6209 pointer_type = false_type;
6210 other_type = true_type;
6211 other_expression = true_expression;
6214 /* TODO Treat (void*)0 as null pointer constant */
6215 if (is_type_pointer(other_type)) {
6216 type_t *to1 = pointer_type->pointer.points_to;
6217 type_t *to2 = other_type->pointer.points_to;
6220 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6221 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6223 } else if (types_compatible(get_unqualified_type(to1),
6224 get_unqualified_type(to2))) {
6227 warningf(&expression->base.source_position,
6228 "pointer types '%T' and '%T' in conditional expression are incompatible",
6229 true_type, false_type);
6233 type_t *const copy = duplicate_type(to);
6234 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6236 type_t *const type = typehash_insert(copy);
6240 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6241 } else if(is_null_pointer_constant(other_expression)) {
6242 result_type = pointer_type;
6243 } else if(is_type_integer(other_type)) {
6244 warningf(&expression->base.source_position,
6245 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6246 result_type = pointer_type;
6248 type_error_incompatible("while parsing conditional",
6249 &expression->base.source_position, true_type, false_type);
6250 result_type = type_error_type;
6253 /* TODO: one pointer to void*, other some pointer */
6255 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6256 type_error_incompatible("while parsing conditional",
6257 &expression->base.source_position, true_type,
6260 result_type = type_error_type;
6263 conditional->true_expression
6264 = create_implicit_cast(true_expression, result_type);
6265 conditional->false_expression
6266 = create_implicit_cast(false_expression, result_type);
6267 conditional->base.type = result_type;
6270 return create_invalid_expression();
6274 * Parse an extension expression.
6276 static expression_t *parse_extension(unsigned precedence)
6278 eat(T___extension__);
6280 /* TODO enable extensions */
6281 expression_t *expression = parse_sub_expression(precedence);
6282 /* TODO disable extensions */
6287 * Parse a __builtin_classify_type() expression.
6289 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6291 eat(T___builtin_classify_type);
6293 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6294 result->base.type = type_int;
6297 add_anchor_token(')');
6298 expression_t *expression = parse_sub_expression(precedence);
6299 rem_anchor_token(')');
6301 result->classify_type.type_expression = expression;
6305 return create_invalid_expression();
6308 static void check_pointer_arithmetic(const source_position_t *source_position,
6309 type_t *pointer_type,
6310 type_t *orig_pointer_type)
6312 type_t *points_to = pointer_type->pointer.points_to;
6313 points_to = skip_typeref(points_to);
6315 if (is_type_incomplete(points_to) &&
6317 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6318 errorf(source_position,
6319 "arithmetic with pointer to incomplete type '%T' not allowed",
6321 } else if (is_type_function(points_to)) {
6322 errorf(source_position,
6323 "arithmetic with pointer to function type '%T' not allowed",
6328 static void semantic_incdec(unary_expression_t *expression)
6330 type_t *const orig_type = expression->value->base.type;
6331 type_t *const type = skip_typeref(orig_type);
6332 if (is_type_pointer(type)) {
6333 check_pointer_arithmetic(&expression->base.source_position,
6335 } else if (!is_type_real(type) && is_type_valid(type)) {
6336 /* TODO: improve error message */
6337 errorf(HERE, "operation needs an arithmetic or pointer type");
6339 expression->base.type = orig_type;
6342 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6344 type_t *const orig_type = expression->value->base.type;
6345 type_t *const type = skip_typeref(orig_type);
6346 if(!is_type_arithmetic(type)) {
6347 if (is_type_valid(type)) {
6348 /* TODO: improve error message */
6349 errorf(HERE, "operation needs an arithmetic type");
6354 expression->base.type = orig_type;
6357 static void semantic_unexpr_scalar(unary_expression_t *expression)
6359 type_t *const orig_type = expression->value->base.type;
6360 type_t *const type = skip_typeref(orig_type);
6361 if (!is_type_scalar(type)) {
6362 if (is_type_valid(type)) {
6363 errorf(HERE, "operand of ! must be of scalar type");
6368 expression->base.type = orig_type;
6371 static void semantic_unexpr_integer(unary_expression_t *expression)
6373 type_t *const orig_type = expression->value->base.type;
6374 type_t *const type = skip_typeref(orig_type);
6375 if (!is_type_integer(type)) {
6376 if (is_type_valid(type)) {
6377 errorf(HERE, "operand of ~ must be of integer type");
6382 expression->base.type = orig_type;
6385 static void semantic_dereference(unary_expression_t *expression)
6387 type_t *const orig_type = expression->value->base.type;
6388 type_t *const type = skip_typeref(orig_type);
6389 if(!is_type_pointer(type)) {
6390 if (is_type_valid(type)) {
6391 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6396 type_t *result_type = type->pointer.points_to;
6397 result_type = automatic_type_conversion(result_type);
6398 expression->base.type = result_type;
6401 static void set_address_taken(expression_t *expression)
6403 if(expression->kind != EXPR_REFERENCE)
6406 declaration_t *const declaration = expression->reference.declaration;
6407 /* happens for parse errors */
6408 if(declaration == NULL)
6411 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6412 errorf(&expression->base.source_position,
6413 "address of register variable '%Y' requested",
6414 declaration->symbol);
6416 declaration->address_taken = 1;
6421 * Check the semantic of the address taken expression.
6423 static void semantic_take_addr(unary_expression_t *expression)
6425 expression_t *value = expression->value;
6426 value->base.type = revert_automatic_type_conversion(value);
6428 type_t *orig_type = value->base.type;
6429 if(!is_type_valid(orig_type))
6432 set_address_taken(value);
6434 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6437 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6438 static expression_t *parse_##unexpression_type(unsigned precedence) \
6442 expression_t *unary_expression \
6443 = allocate_expression_zero(unexpression_type); \
6444 unary_expression->base.source_position = *HERE; \
6445 unary_expression->unary.value = parse_sub_expression(precedence); \
6447 sfunc(&unary_expression->unary); \
6449 return unary_expression; \
6452 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6453 semantic_unexpr_arithmetic)
6454 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6455 semantic_unexpr_arithmetic)
6456 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6457 semantic_unexpr_scalar)
6458 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6459 semantic_dereference)
6460 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6462 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6463 semantic_unexpr_integer)
6464 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6466 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6469 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6471 static expression_t *parse_##unexpression_type(unsigned precedence, \
6472 expression_t *left) \
6474 (void) precedence; \
6477 expression_t *unary_expression \
6478 = allocate_expression_zero(unexpression_type); \
6479 unary_expression->unary.value = left; \
6481 sfunc(&unary_expression->unary); \
6483 return unary_expression; \
6486 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6487 EXPR_UNARY_POSTFIX_INCREMENT,
6489 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6490 EXPR_UNARY_POSTFIX_DECREMENT,
6493 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6495 /* TODO: handle complex + imaginary types */
6497 /* § 6.3.1.8 Usual arithmetic conversions */
6498 if(type_left == type_long_double || type_right == type_long_double) {
6499 return type_long_double;
6500 } else if(type_left == type_double || type_right == type_double) {
6502 } else if(type_left == type_float || type_right == type_float) {
6506 type_right = promote_integer(type_right);
6507 type_left = promote_integer(type_left);
6509 if(type_left == type_right)
6512 bool signed_left = is_type_signed(type_left);
6513 bool signed_right = is_type_signed(type_right);
6514 int rank_left = get_rank(type_left);
6515 int rank_right = get_rank(type_right);
6516 if(rank_left < rank_right) {
6517 if(signed_left == signed_right || !signed_right) {
6523 if(signed_left == signed_right || !signed_left) {
6532 * Check the semantic restrictions for a binary expression.
6534 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6536 expression_t *const left = expression->left;
6537 expression_t *const right = expression->right;
6538 type_t *const orig_type_left = left->base.type;
6539 type_t *const orig_type_right = right->base.type;
6540 type_t *const type_left = skip_typeref(orig_type_left);
6541 type_t *const type_right = skip_typeref(orig_type_right);
6543 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6544 /* TODO: improve error message */
6545 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6546 errorf(HERE, "operation needs arithmetic types");
6551 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6552 expression->left = create_implicit_cast(left, arithmetic_type);
6553 expression->right = create_implicit_cast(right, arithmetic_type);
6554 expression->base.type = arithmetic_type;
6557 static void semantic_shift_op(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 * type_left = skip_typeref(orig_type_left);
6564 type_t * type_right = skip_typeref(orig_type_right);
6566 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6567 /* TODO: improve error message */
6568 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6569 errorf(HERE, "operation needs integer types");
6574 type_left = promote_integer(type_left);
6575 type_right = promote_integer(type_right);
6577 expression->left = create_implicit_cast(left, type_left);
6578 expression->right = create_implicit_cast(right, type_right);
6579 expression->base.type = type_left;
6582 static void semantic_add(binary_expression_t *expression)
6584 expression_t *const left = expression->left;
6585 expression_t *const right = expression->right;
6586 type_t *const orig_type_left = left->base.type;
6587 type_t *const orig_type_right = right->base.type;
6588 type_t *const type_left = skip_typeref(orig_type_left);
6589 type_t *const type_right = skip_typeref(orig_type_right);
6592 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6593 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6594 expression->left = create_implicit_cast(left, arithmetic_type);
6595 expression->right = create_implicit_cast(right, arithmetic_type);
6596 expression->base.type = arithmetic_type;
6598 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6599 check_pointer_arithmetic(&expression->base.source_position,
6600 type_left, orig_type_left);
6601 expression->base.type = type_left;
6602 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6603 check_pointer_arithmetic(&expression->base.source_position,
6604 type_right, orig_type_right);
6605 expression->base.type = type_right;
6606 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6607 errorf(&expression->base.source_position,
6608 "invalid operands to binary + ('%T', '%T')",
6609 orig_type_left, orig_type_right);
6613 static void semantic_sub(binary_expression_t *expression)
6615 expression_t *const left = expression->left;
6616 expression_t *const right = expression->right;
6617 type_t *const orig_type_left = left->base.type;
6618 type_t *const orig_type_right = right->base.type;
6619 type_t *const type_left = skip_typeref(orig_type_left);
6620 type_t *const type_right = skip_typeref(orig_type_right);
6623 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6624 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6625 expression->left = create_implicit_cast(left, arithmetic_type);
6626 expression->right = create_implicit_cast(right, arithmetic_type);
6627 expression->base.type = arithmetic_type;
6629 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6630 check_pointer_arithmetic(&expression->base.source_position,
6631 type_left, orig_type_left);
6632 expression->base.type = type_left;
6633 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6634 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6635 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6636 if (!types_compatible(unqual_left, unqual_right)) {
6637 errorf(&expression->base.source_position,
6638 "subtracting pointers to incompatible types '%T' and '%T'",
6639 orig_type_left, orig_type_right);
6640 } else if (!is_type_object(unqual_left)) {
6641 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6642 warningf(&expression->base.source_position,
6643 "subtracting pointers to void");
6645 errorf(&expression->base.source_position,
6646 "subtracting pointers to non-object types '%T'",
6650 expression->base.type = type_ptrdiff_t;
6651 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6652 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6653 orig_type_left, orig_type_right);
6658 * Check the semantics of comparison expressions.
6660 * @param expression The expression to check.
6662 static void semantic_comparison(binary_expression_t *expression)
6664 expression_t *left = expression->left;
6665 expression_t *right = expression->right;
6666 type_t *orig_type_left = left->base.type;
6667 type_t *orig_type_right = right->base.type;
6669 type_t *type_left = skip_typeref(orig_type_left);
6670 type_t *type_right = skip_typeref(orig_type_right);
6672 /* TODO non-arithmetic types */
6673 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6674 /* test for signed vs unsigned compares */
6675 if (warning.sign_compare &&
6676 (expression->base.kind != EXPR_BINARY_EQUAL &&
6677 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6678 (is_type_signed(type_left) != is_type_signed(type_right))) {
6680 /* check if 1 of the operands is a constant, in this case we just
6681 * check wether we can safely represent the resulting constant in
6682 * the type of the other operand. */
6683 expression_t *const_expr = NULL;
6684 expression_t *other_expr = NULL;
6686 if(is_constant_expression(left)) {
6689 } else if(is_constant_expression(right)) {
6694 if(const_expr != NULL) {
6695 type_t *other_type = skip_typeref(other_expr->base.type);
6696 long val = fold_constant(const_expr);
6697 /* TODO: check if val can be represented by other_type */
6701 warningf(&expression->base.source_position,
6702 "comparison between signed and unsigned");
6704 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6705 expression->left = create_implicit_cast(left, arithmetic_type);
6706 expression->right = create_implicit_cast(right, arithmetic_type);
6707 expression->base.type = arithmetic_type;
6708 if (warning.float_equal &&
6709 (expression->base.kind == EXPR_BINARY_EQUAL ||
6710 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6711 is_type_float(arithmetic_type)) {
6712 warningf(&expression->base.source_position,
6713 "comparing floating point with == or != is unsafe");
6715 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6716 /* TODO check compatibility */
6717 } else if (is_type_pointer(type_left)) {
6718 expression->right = create_implicit_cast(right, type_left);
6719 } else if (is_type_pointer(type_right)) {
6720 expression->left = create_implicit_cast(left, type_right);
6721 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6722 type_error_incompatible("invalid operands in comparison",
6723 &expression->base.source_position,
6724 type_left, type_right);
6726 expression->base.type = type_int;
6730 * Checks if a compound type has constant fields.
6732 static bool has_const_fields(const compound_type_t *type)
6734 const scope_t *scope = &type->declaration->scope;
6735 const declaration_t *declaration = scope->declarations;
6737 for (; declaration != NULL; declaration = declaration->next) {
6738 if (declaration->namespc != NAMESPACE_NORMAL)
6741 const type_t *decl_type = skip_typeref(declaration->type);
6742 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6749 static bool is_lvalue(const expression_t *expression)
6751 switch (expression->kind) {
6752 case EXPR_REFERENCE:
6753 case EXPR_ARRAY_ACCESS:
6755 case EXPR_UNARY_DEREFERENCE:
6763 static bool is_valid_assignment_lhs(expression_t const* const left)
6765 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6766 type_t *const type_left = skip_typeref(orig_type_left);
6768 if (!is_lvalue(left)) {
6769 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6774 if (is_type_array(type_left)) {
6775 errorf(HERE, "cannot assign to arrays ('%E')", left);
6778 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6779 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6783 if (is_type_incomplete(type_left)) {
6784 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6785 left, orig_type_left);
6788 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6789 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6790 left, orig_type_left);
6797 static void semantic_arithmetic_assign(binary_expression_t *expression)
6799 expression_t *left = expression->left;
6800 expression_t *right = expression->right;
6801 type_t *orig_type_left = left->base.type;
6802 type_t *orig_type_right = right->base.type;
6804 if (!is_valid_assignment_lhs(left))
6807 type_t *type_left = skip_typeref(orig_type_left);
6808 type_t *type_right = skip_typeref(orig_type_right);
6810 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6811 /* TODO: improve error message */
6812 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6813 errorf(HERE, "operation needs arithmetic types");
6818 /* combined instructions are tricky. We can't create an implicit cast on
6819 * the left side, because we need the uncasted form for the store.
6820 * The ast2firm pass has to know that left_type must be right_type
6821 * for the arithmetic operation and create a cast by itself */
6822 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6823 expression->right = create_implicit_cast(right, arithmetic_type);
6824 expression->base.type = type_left;
6827 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6829 expression_t *const left = expression->left;
6830 expression_t *const right = expression->right;
6831 type_t *const orig_type_left = left->base.type;
6832 type_t *const orig_type_right = right->base.type;
6833 type_t *const type_left = skip_typeref(orig_type_left);
6834 type_t *const type_right = skip_typeref(orig_type_right);
6836 if (!is_valid_assignment_lhs(left))
6839 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6840 /* combined instructions are tricky. We can't create an implicit cast on
6841 * the left side, because we need the uncasted form for the store.
6842 * The ast2firm pass has to know that left_type must be right_type
6843 * for the arithmetic operation and create a cast by itself */
6844 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6845 expression->right = create_implicit_cast(right, arithmetic_type);
6846 expression->base.type = type_left;
6847 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6848 check_pointer_arithmetic(&expression->base.source_position,
6849 type_left, orig_type_left);
6850 expression->base.type = type_left;
6851 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6852 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6857 * Check the semantic restrictions of a logical expression.
6859 static void semantic_logical_op(binary_expression_t *expression)
6861 expression_t *const left = expression->left;
6862 expression_t *const right = expression->right;
6863 type_t *const orig_type_left = left->base.type;
6864 type_t *const orig_type_right = right->base.type;
6865 type_t *const type_left = skip_typeref(orig_type_left);
6866 type_t *const type_right = skip_typeref(orig_type_right);
6868 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6869 /* TODO: improve error message */
6870 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6871 errorf(HERE, "operation needs scalar types");
6876 expression->base.type = type_int;
6880 * Check the semantic restrictions of a binary assign expression.
6882 static void semantic_binexpr_assign(binary_expression_t *expression)
6884 expression_t *left = expression->left;
6885 type_t *orig_type_left = left->base.type;
6887 type_t *type_left = revert_automatic_type_conversion(left);
6888 type_left = skip_typeref(orig_type_left);
6890 if (!is_valid_assignment_lhs(left))
6893 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6894 report_assign_error(error, orig_type_left, expression->right,
6895 "assignment", &left->base.source_position);
6896 expression->right = create_implicit_cast(expression->right, orig_type_left);
6897 expression->base.type = orig_type_left;
6901 * Determine if the outermost operation (or parts thereof) of the given
6902 * expression has no effect in order to generate a warning about this fact.
6903 * Therefore in some cases this only examines some of the operands of the
6904 * expression (see comments in the function and examples below).
6906 * f() + 23; // warning, because + has no effect
6907 * x || f(); // no warning, because x controls execution of f()
6908 * x ? y : f(); // warning, because y has no effect
6909 * (void)x; // no warning to be able to suppress the warning
6910 * This function can NOT be used for an "expression has definitely no effect"-
6912 static bool expression_has_effect(const expression_t *const expr)
6914 switch (expr->kind) {
6915 case EXPR_UNKNOWN: break;
6916 case EXPR_INVALID: return true; /* do NOT warn */
6917 case EXPR_REFERENCE: return false;
6918 /* suppress the warning for microsoft __noop operations */
6919 case EXPR_CONST: return expr->conste.is_ms_noop;
6920 case EXPR_CHARACTER_CONSTANT: return false;
6921 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6922 case EXPR_STRING_LITERAL: return false;
6923 case EXPR_WIDE_STRING_LITERAL: return false;
6926 const call_expression_t *const call = &expr->call;
6927 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6930 switch (call->function->builtin_symbol.symbol->ID) {
6931 case T___builtin_va_end: return true;
6932 default: return false;
6936 /* Generate the warning if either the left or right hand side of a
6937 * conditional expression has no effect */
6938 case EXPR_CONDITIONAL: {
6939 const conditional_expression_t *const cond = &expr->conditional;
6941 expression_has_effect(cond->true_expression) &&
6942 expression_has_effect(cond->false_expression);
6945 case EXPR_SELECT: return false;
6946 case EXPR_ARRAY_ACCESS: return false;
6947 case EXPR_SIZEOF: return false;
6948 case EXPR_CLASSIFY_TYPE: return false;
6949 case EXPR_ALIGNOF: return false;
6951 case EXPR_FUNCNAME: return false;
6952 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6953 case EXPR_BUILTIN_CONSTANT_P: return false;
6954 case EXPR_BUILTIN_PREFETCH: return true;
6955 case EXPR_OFFSETOF: return false;
6956 case EXPR_VA_START: return true;
6957 case EXPR_VA_ARG: return true;
6958 case EXPR_STATEMENT: return true; // TODO
6959 case EXPR_COMPOUND_LITERAL: return false;
6961 case EXPR_UNARY_NEGATE: return false;
6962 case EXPR_UNARY_PLUS: return false;
6963 case EXPR_UNARY_BITWISE_NEGATE: return false;
6964 case EXPR_UNARY_NOT: return false;
6965 case EXPR_UNARY_DEREFERENCE: return false;
6966 case EXPR_UNARY_TAKE_ADDRESS: return false;
6967 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6968 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6969 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6970 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6972 /* Treat void casts as if they have an effect in order to being able to
6973 * suppress the warning */
6974 case EXPR_UNARY_CAST: {
6975 type_t *const type = skip_typeref(expr->base.type);
6976 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6979 case EXPR_UNARY_CAST_IMPLICIT: return true;
6980 case EXPR_UNARY_ASSUME: return true;
6982 case EXPR_BINARY_ADD: return false;
6983 case EXPR_BINARY_SUB: return false;
6984 case EXPR_BINARY_MUL: return false;
6985 case EXPR_BINARY_DIV: return false;
6986 case EXPR_BINARY_MOD: return false;
6987 case EXPR_BINARY_EQUAL: return false;
6988 case EXPR_BINARY_NOTEQUAL: return false;
6989 case EXPR_BINARY_LESS: return false;
6990 case EXPR_BINARY_LESSEQUAL: return false;
6991 case EXPR_BINARY_GREATER: return false;
6992 case EXPR_BINARY_GREATEREQUAL: return false;
6993 case EXPR_BINARY_BITWISE_AND: return false;
6994 case EXPR_BINARY_BITWISE_OR: return false;
6995 case EXPR_BINARY_BITWISE_XOR: return false;
6996 case EXPR_BINARY_SHIFTLEFT: return false;
6997 case EXPR_BINARY_SHIFTRIGHT: return false;
6998 case EXPR_BINARY_ASSIGN: return true;
6999 case EXPR_BINARY_MUL_ASSIGN: return true;
7000 case EXPR_BINARY_DIV_ASSIGN: return true;
7001 case EXPR_BINARY_MOD_ASSIGN: return true;
7002 case EXPR_BINARY_ADD_ASSIGN: return true;
7003 case EXPR_BINARY_SUB_ASSIGN: return true;
7004 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7005 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7006 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7007 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7008 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7010 /* Only examine the right hand side of && and ||, because the left hand
7011 * side already has the effect of controlling the execution of the right
7013 case EXPR_BINARY_LOGICAL_AND:
7014 case EXPR_BINARY_LOGICAL_OR:
7015 /* Only examine the right hand side of a comma expression, because the left
7016 * hand side has a separate warning */
7017 case EXPR_BINARY_COMMA:
7018 return expression_has_effect(expr->binary.right);
7020 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7021 case EXPR_BINARY_ISGREATER: return false;
7022 case EXPR_BINARY_ISGREATEREQUAL: return false;
7023 case EXPR_BINARY_ISLESS: return false;
7024 case EXPR_BINARY_ISLESSEQUAL: return false;
7025 case EXPR_BINARY_ISLESSGREATER: return false;
7026 case EXPR_BINARY_ISUNORDERED: return false;
7029 internal_errorf(HERE, "unexpected expression");
7032 static void semantic_comma(binary_expression_t *expression)
7034 if (warning.unused_value) {
7035 const expression_t *const left = expression->left;
7036 if (!expression_has_effect(left)) {
7037 warningf(&left->base.source_position,
7038 "left-hand operand of comma expression has no effect");
7041 expression->base.type = expression->right->base.type;
7044 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7045 static expression_t *parse_##binexpression_type(unsigned precedence, \
7046 expression_t *left) \
7049 source_position_t pos = *HERE; \
7051 expression_t *right = parse_sub_expression(precedence + lr); \
7053 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7054 binexpr->base.source_position = pos; \
7055 binexpr->binary.left = left; \
7056 binexpr->binary.right = right; \
7057 sfunc(&binexpr->binary); \
7062 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7063 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7064 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7065 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7066 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7067 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7068 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7069 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7070 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7072 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7073 semantic_comparison, 1)
7074 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7075 semantic_comparison, 1)
7076 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7077 semantic_comparison, 1)
7078 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7079 semantic_comparison, 1)
7081 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7082 semantic_binexpr_arithmetic, 1)
7083 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7084 semantic_binexpr_arithmetic, 1)
7085 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7086 semantic_binexpr_arithmetic, 1)
7087 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7088 semantic_logical_op, 1)
7089 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7090 semantic_logical_op, 1)
7091 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7092 semantic_shift_op, 1)
7093 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7094 semantic_shift_op, 1)
7095 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7096 semantic_arithmetic_addsubb_assign, 0)
7097 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7098 semantic_arithmetic_addsubb_assign, 0)
7099 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7100 semantic_arithmetic_assign, 0)
7101 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7102 semantic_arithmetic_assign, 0)
7103 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7104 semantic_arithmetic_assign, 0)
7105 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7106 semantic_arithmetic_assign, 0)
7107 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7108 semantic_arithmetic_assign, 0)
7109 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7110 semantic_arithmetic_assign, 0)
7111 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7112 semantic_arithmetic_assign, 0)
7113 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7114 semantic_arithmetic_assign, 0)
7116 static expression_t *parse_sub_expression(unsigned precedence)
7118 if(token.type < 0) {
7119 return expected_expression_error();
7122 expression_parser_function_t *parser
7123 = &expression_parsers[token.type];
7124 source_position_t source_position = token.source_position;
7127 if(parser->parser != NULL) {
7128 left = parser->parser(parser->precedence);
7130 left = parse_primary_expression();
7132 assert(left != NULL);
7133 left->base.source_position = source_position;
7136 if(token.type < 0) {
7137 return expected_expression_error();
7140 parser = &expression_parsers[token.type];
7141 if(parser->infix_parser == NULL)
7143 if(parser->infix_precedence < precedence)
7146 left = parser->infix_parser(parser->infix_precedence, left);
7148 assert(left != NULL);
7149 assert(left->kind != EXPR_UNKNOWN);
7150 left->base.source_position = source_position;
7157 * Parse an expression.
7159 static expression_t *parse_expression(void)
7161 return parse_sub_expression(1);
7165 * Register a parser for a prefix-like operator with given precedence.
7167 * @param parser the parser function
7168 * @param token_type the token type of the prefix token
7169 * @param precedence the precedence of the operator
7171 static void register_expression_parser(parse_expression_function parser,
7172 int token_type, unsigned precedence)
7174 expression_parser_function_t *entry = &expression_parsers[token_type];
7176 if(entry->parser != NULL) {
7177 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7178 panic("trying to register multiple expression parsers for a token");
7180 entry->parser = parser;
7181 entry->precedence = precedence;
7185 * Register a parser for an infix operator with given precedence.
7187 * @param parser the parser function
7188 * @param token_type the token type of the infix operator
7189 * @param precedence the precedence of the operator
7191 static void register_infix_parser(parse_expression_infix_function parser,
7192 int token_type, unsigned precedence)
7194 expression_parser_function_t *entry = &expression_parsers[token_type];
7196 if(entry->infix_parser != NULL) {
7197 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7198 panic("trying to register multiple infix expression parsers for a "
7201 entry->infix_parser = parser;
7202 entry->infix_precedence = precedence;
7206 * Initialize the expression parsers.
7208 static void init_expression_parsers(void)
7210 memset(&expression_parsers, 0, sizeof(expression_parsers));
7212 register_infix_parser(parse_array_expression, '[', 30);
7213 register_infix_parser(parse_call_expression, '(', 30);
7214 register_infix_parser(parse_select_expression, '.', 30);
7215 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7216 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7218 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7221 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7222 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7223 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7224 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7225 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7226 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7227 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7228 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7229 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7230 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7231 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7232 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7233 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7234 T_EXCLAMATIONMARKEQUAL, 13);
7235 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7236 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7237 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7238 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7239 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7240 register_infix_parser(parse_conditional_expression, '?', 7);
7241 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7242 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7243 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7244 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7245 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7246 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7247 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7248 T_LESSLESSEQUAL, 2);
7249 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7250 T_GREATERGREATEREQUAL, 2);
7251 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7253 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7255 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7258 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7260 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7261 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7262 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7263 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7264 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7265 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7266 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7268 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7270 register_expression_parser(parse_sizeof, T_sizeof, 25);
7271 register_expression_parser(parse_alignof, T___alignof__, 25);
7272 register_expression_parser(parse_extension, T___extension__, 25);
7273 register_expression_parser(parse_builtin_classify_type,
7274 T___builtin_classify_type, 25);
7278 * Parse a asm statement arguments specification.
7280 static asm_argument_t *parse_asm_arguments(bool is_out)
7282 asm_argument_t *result = NULL;
7283 asm_argument_t *last = NULL;
7285 while (token.type == T_STRING_LITERAL || token.type == '[') {
7286 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7287 memset(argument, 0, sizeof(argument[0]));
7289 if (token.type == '[') {
7291 if (token.type != T_IDENTIFIER) {
7292 parse_error_expected("while parsing asm argument",
7293 T_IDENTIFIER, NULL);
7296 argument->symbol = token.v.symbol;
7301 argument->constraints = parse_string_literals();
7303 expression_t *expression = parse_expression();
7304 argument->expression = expression;
7305 if (is_out && !is_lvalue(expression)) {
7306 errorf(&expression->base.source_position,
7307 "asm output argument is not an lvalue");
7311 set_address_taken(expression);
7314 last->next = argument;
7320 if (token.type != ',')
7331 * Parse a asm statement clobber specification.
7333 static asm_clobber_t *parse_asm_clobbers(void)
7335 asm_clobber_t *result = NULL;
7336 asm_clobber_t *last = NULL;
7338 while(token.type == T_STRING_LITERAL) {
7339 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7340 clobber->clobber = parse_string_literals();
7343 last->next = clobber;
7349 if(token.type != ',')
7358 * Parse an asm statement.
7360 static statement_t *parse_asm_statement(void)
7364 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7365 statement->base.source_position = token.source_position;
7367 asm_statement_t *asm_statement = &statement->asms;
7369 if(token.type == T_volatile) {
7371 asm_statement->is_volatile = true;
7375 add_anchor_token(')');
7376 add_anchor_token(':');
7377 asm_statement->asm_text = parse_string_literals();
7379 if(token.type != ':') {
7380 rem_anchor_token(':');
7385 asm_statement->outputs = parse_asm_arguments(true);
7386 if(token.type != ':') {
7387 rem_anchor_token(':');
7392 asm_statement->inputs = parse_asm_arguments(false);
7393 if(token.type != ':') {
7394 rem_anchor_token(':');
7397 rem_anchor_token(':');
7400 asm_statement->clobbers = parse_asm_clobbers();
7403 rem_anchor_token(')');
7408 return create_invalid_statement();
7412 * Parse a case statement.
7414 static statement_t *parse_case_statement(void)
7418 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7420 statement->base.source_position = token.source_position;
7421 statement->case_label.expression = parse_expression();
7423 if (c_mode & _GNUC) {
7424 if (token.type == T_DOTDOTDOT) {
7426 statement->case_label.end_range = parse_expression();
7432 if (! is_constant_expression(statement->case_label.expression)) {
7433 errorf(&statement->base.source_position,
7434 "case label does not reduce to an integer constant");
7436 /* TODO: check if the case label is already known */
7437 if (current_switch != NULL) {
7438 /* link all cases into the switch statement */
7439 if (current_switch->last_case == NULL) {
7440 current_switch->first_case =
7441 current_switch->last_case = &statement->case_label;
7443 current_switch->last_case->next = &statement->case_label;
7446 errorf(&statement->base.source_position,
7447 "case label not within a switch statement");
7450 statement->case_label.statement = parse_statement();
7454 return create_invalid_statement();
7458 * Finds an existing default label of a switch statement.
7460 static case_label_statement_t *
7461 find_default_label(const switch_statement_t *statement)
7463 case_label_statement_t *label = statement->first_case;
7464 for ( ; label != NULL; label = label->next) {
7465 if (label->expression == NULL)
7472 * Parse a default statement.
7474 static statement_t *parse_default_statement(void)
7478 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7480 statement->base.source_position = token.source_position;
7483 if (current_switch != NULL) {
7484 const case_label_statement_t *def_label = find_default_label(current_switch);
7485 if (def_label != NULL) {
7486 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7487 &def_label->base.source_position);
7489 /* link all cases into the switch statement */
7490 if (current_switch->last_case == NULL) {
7491 current_switch->first_case =
7492 current_switch->last_case = &statement->case_label;
7494 current_switch->last_case->next = &statement->case_label;
7498 errorf(&statement->base.source_position,
7499 "'default' label not within a switch statement");
7501 statement->case_label.statement = parse_statement();
7505 return create_invalid_statement();
7509 * Return the declaration for a given label symbol or create a new one.
7511 static declaration_t *get_label(symbol_t *symbol)
7513 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7514 assert(current_function != NULL);
7515 /* if we found a label in the same function, then we already created the
7517 if(candidate != NULL
7518 && candidate->parent_scope == ¤t_function->scope) {
7522 /* otherwise we need to create a new one */
7523 declaration_t *const declaration = allocate_declaration_zero();
7524 declaration->namespc = NAMESPACE_LABEL;
7525 declaration->symbol = symbol;
7527 label_push(declaration);
7533 * Parse a label statement.
7535 static statement_t *parse_label_statement(void)
7537 assert(token.type == T_IDENTIFIER);
7538 symbol_t *symbol = token.v.symbol;
7541 declaration_t *label = get_label(symbol);
7543 /* if source position is already set then the label is defined twice,
7544 * otherwise it was just mentioned in a goto so far */
7545 if(label->source_position.input_name != NULL) {
7546 errorf(HERE, "duplicate label '%Y' (declared %P)",
7547 symbol, &label->source_position);
7549 label->source_position = token.source_position;
7552 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7554 statement->base.source_position = token.source_position;
7555 statement->label.label = label;
7559 if(token.type == '}') {
7560 /* TODO only warn? */
7562 warningf(HERE, "label at end of compound statement");
7563 statement->label.statement = create_empty_statement();
7565 errorf(HERE, "label at end of compound statement");
7566 statement->label.statement = create_invalid_statement();
7570 if (token.type == ';') {
7571 /* eat an empty statement here, to avoid the warning about an empty
7572 * after a label. label:; is commonly used to have a label before
7574 statement->label.statement = create_empty_statement();
7577 statement->label.statement = parse_statement();
7581 /* remember the labels's in a list for later checking */
7582 if (label_last == NULL) {
7583 label_first = &statement->label;
7585 label_last->next = &statement->label;
7587 label_last = &statement->label;
7593 * Parse an if statement.
7595 static statement_t *parse_if(void)
7599 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7600 statement->base.source_position = token.source_position;
7603 add_anchor_token(')');
7604 statement->ifs.condition = parse_expression();
7605 rem_anchor_token(')');
7608 add_anchor_token(T_else);
7609 statement->ifs.true_statement = parse_statement();
7610 rem_anchor_token(T_else);
7612 if(token.type == T_else) {
7614 statement->ifs.false_statement = parse_statement();
7619 return create_invalid_statement();
7623 * Parse a switch statement.
7625 static statement_t *parse_switch(void)
7629 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7630 statement->base.source_position = token.source_position;
7633 expression_t *const expr = parse_expression();
7634 type_t * type = skip_typeref(expr->base.type);
7635 if (is_type_integer(type)) {
7636 type = promote_integer(type);
7637 } else if (is_type_valid(type)) {
7638 errorf(&expr->base.source_position,
7639 "switch quantity is not an integer, but '%T'", type);
7640 type = type_error_type;
7642 statement->switchs.expression = create_implicit_cast(expr, type);
7645 switch_statement_t *rem = current_switch;
7646 current_switch = &statement->switchs;
7647 statement->switchs.body = parse_statement();
7648 current_switch = rem;
7650 if(warning.switch_default &&
7651 find_default_label(&statement->switchs) == NULL) {
7652 warningf(&statement->base.source_position, "switch has no default case");
7657 return create_invalid_statement();
7660 static statement_t *parse_loop_body(statement_t *const loop)
7662 statement_t *const rem = current_loop;
7663 current_loop = loop;
7665 statement_t *const body = parse_statement();
7672 * Parse a while statement.
7674 static statement_t *parse_while(void)
7678 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7679 statement->base.source_position = token.source_position;
7682 add_anchor_token(')');
7683 statement->whiles.condition = parse_expression();
7684 rem_anchor_token(')');
7687 statement->whiles.body = parse_loop_body(statement);
7691 return create_invalid_statement();
7695 * Parse a do statement.
7697 static statement_t *parse_do(void)
7701 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7703 statement->base.source_position = token.source_position;
7705 add_anchor_token(T_while);
7706 statement->do_while.body = parse_loop_body(statement);
7707 rem_anchor_token(T_while);
7711 add_anchor_token(')');
7712 statement->do_while.condition = parse_expression();
7713 rem_anchor_token(')');
7719 return create_invalid_statement();
7723 * Parse a for statement.
7725 static statement_t *parse_for(void)
7729 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7730 statement->base.source_position = token.source_position;
7732 int top = environment_top();
7733 scope_t *last_scope = scope;
7734 set_scope(&statement->fors.scope);
7737 add_anchor_token(')');
7739 if(token.type != ';') {
7740 if(is_declaration_specifier(&token, false)) {
7741 parse_declaration(record_declaration);
7743 add_anchor_token(';');
7744 expression_t *const init = parse_expression();
7745 statement->fors.initialisation = init;
7746 if (warning.unused_value && !expression_has_effect(init)) {
7747 warningf(&init->base.source_position,
7748 "initialisation of 'for'-statement has no effect");
7750 rem_anchor_token(';');
7757 if(token.type != ';') {
7758 add_anchor_token(';');
7759 statement->fors.condition = parse_expression();
7760 rem_anchor_token(';');
7763 if(token.type != ')') {
7764 expression_t *const step = parse_expression();
7765 statement->fors.step = step;
7766 if (warning.unused_value && !expression_has_effect(step)) {
7767 warningf(&step->base.source_position,
7768 "step of 'for'-statement has no effect");
7771 rem_anchor_token(')');
7773 statement->fors.body = parse_loop_body(statement);
7775 assert(scope == &statement->fors.scope);
7776 set_scope(last_scope);
7777 environment_pop_to(top);
7782 rem_anchor_token(')');
7783 assert(scope == &statement->fors.scope);
7784 set_scope(last_scope);
7785 environment_pop_to(top);
7787 return create_invalid_statement();
7791 * Parse a goto statement.
7793 static statement_t *parse_goto(void)
7797 if(token.type != T_IDENTIFIER) {
7798 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7802 symbol_t *symbol = token.v.symbol;
7805 declaration_t *label = get_label(symbol);
7807 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7808 statement->base.source_position = token.source_position;
7810 statement->gotos.label = label;
7812 /* remember the goto's in a list for later checking */
7813 if (goto_last == NULL) {
7814 goto_first = &statement->gotos;
7816 goto_last->next = &statement->gotos;
7818 goto_last = &statement->gotos;
7824 return create_invalid_statement();
7828 * Parse a continue statement.
7830 static statement_t *parse_continue(void)
7832 statement_t *statement;
7833 if (current_loop == NULL) {
7834 errorf(HERE, "continue statement not within loop");
7835 statement = create_invalid_statement();
7837 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7839 statement->base.source_position = token.source_position;
7847 return create_invalid_statement();
7851 * Parse a break statement.
7853 static statement_t *parse_break(void)
7855 statement_t *statement;
7856 if (current_switch == NULL && current_loop == NULL) {
7857 errorf(HERE, "break statement not within loop or switch");
7858 statement = create_invalid_statement();
7860 statement = allocate_statement_zero(STATEMENT_BREAK);
7862 statement->base.source_position = token.source_position;
7870 return create_invalid_statement();
7874 * Parse a __leave statement.
7876 static statement_t *parse_leave(void)
7878 statement_t *statement;
7879 if (current_try == NULL) {
7880 errorf(HERE, "__leave statement not within __try");
7881 statement = create_invalid_statement();
7883 statement = allocate_statement_zero(STATEMENT_LEAVE);
7885 statement->base.source_position = token.source_position;
7893 return create_invalid_statement();
7897 * Check if a given declaration represents a local variable.
7899 static bool is_local_var_declaration(const declaration_t *declaration) {
7900 switch ((storage_class_tag_t) declaration->storage_class) {
7901 case STORAGE_CLASS_AUTO:
7902 case STORAGE_CLASS_REGISTER: {
7903 const type_t *type = skip_typeref(declaration->type);
7904 if(is_type_function(type)) {
7916 * Check if a given declaration represents a variable.
7918 static bool is_var_declaration(const declaration_t *declaration) {
7919 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7922 const type_t *type = skip_typeref(declaration->type);
7923 return !is_type_function(type);
7927 * Check if a given expression represents a local variable.
7929 static bool is_local_variable(const expression_t *expression)
7931 if (expression->base.kind != EXPR_REFERENCE) {
7934 const declaration_t *declaration = expression->reference.declaration;
7935 return is_local_var_declaration(declaration);
7939 * Check if a given expression represents a local variable and
7940 * return its declaration then, else return NULL.
7942 declaration_t *expr_is_variable(const expression_t *expression)
7944 if (expression->base.kind != EXPR_REFERENCE) {
7947 declaration_t *declaration = expression->reference.declaration;
7948 if (is_var_declaration(declaration))
7954 * Parse a return statement.
7956 static statement_t *parse_return(void)
7958 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7959 statement->base.source_position = token.source_position;
7963 expression_t *return_value = NULL;
7964 if(token.type != ';') {
7965 return_value = parse_expression();
7969 const type_t *const func_type = current_function->type;
7970 assert(is_type_function(func_type));
7971 type_t *const return_type = skip_typeref(func_type->function.return_type);
7973 if(return_value != NULL) {
7974 type_t *return_value_type = skip_typeref(return_value->base.type);
7976 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7977 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7978 warningf(&statement->base.source_position,
7979 "'return' with a value, in function returning void");
7980 return_value = NULL;
7982 assign_error_t error = semantic_assign(return_type, return_value);
7983 report_assign_error(error, return_type, return_value, "'return'",
7984 &statement->base.source_position);
7985 return_value = create_implicit_cast(return_value, return_type);
7987 /* check for returning address of a local var */
7988 if (return_value != NULL &&
7989 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7990 const expression_t *expression = return_value->unary.value;
7991 if (is_local_variable(expression)) {
7992 warningf(&statement->base.source_position,
7993 "function returns address of local variable");
7997 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7998 warningf(&statement->base.source_position,
7999 "'return' without value, in function returning non-void");
8002 statement->returns.value = return_value;
8006 return create_invalid_statement();
8010 * Parse a declaration statement.
8012 static statement_t *parse_declaration_statement(void)
8014 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8016 statement->base.source_position = token.source_position;
8018 declaration_t *before = last_declaration;
8019 parse_declaration(record_declaration);
8021 if(before == NULL) {
8022 statement->declaration.declarations_begin = scope->declarations;
8024 statement->declaration.declarations_begin = before->next;
8026 statement->declaration.declarations_end = last_declaration;
8032 * Parse an expression statement, ie. expr ';'.
8034 static statement_t *parse_expression_statement(void)
8036 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8038 statement->base.source_position = token.source_position;
8039 expression_t *const expr = parse_expression();
8040 statement->expression.expression = expr;
8046 return create_invalid_statement();
8050 * Parse a microsoft __try { } __finally { } or
8051 * __try{ } __except() { }
8053 static statement_t *parse_ms_try_statment(void) {
8054 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8056 statement->base.source_position = token.source_position;
8059 ms_try_statement_t *rem = current_try;
8060 current_try = &statement->ms_try;
8061 statement->ms_try.try_statement = parse_compound_statement(false);
8064 if(token.type == T___except) {
8067 add_anchor_token(')');
8068 expression_t *const expr = parse_expression();
8069 type_t * type = skip_typeref(expr->base.type);
8070 if (is_type_integer(type)) {
8071 type = promote_integer(type);
8072 } else if (is_type_valid(type)) {
8073 errorf(&expr->base.source_position,
8074 "__expect expression is not an integer, but '%T'", type);
8075 type = type_error_type;
8077 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8078 rem_anchor_token(')');
8080 statement->ms_try.final_statement = parse_compound_statement(false);
8081 } else if(token.type == T__finally) {
8083 statement->ms_try.final_statement = parse_compound_statement(false);
8085 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8086 return create_invalid_statement();
8090 return create_invalid_statement();
8094 * Parse a statement.
8095 * There's also parse_statement() which additionally checks for
8096 * "statement has no effect" warnings
8098 static statement_t *intern_parse_statement(void)
8100 statement_t *statement = NULL;
8102 /* declaration or statement */
8103 add_anchor_token(';');
8104 switch(token.type) {
8106 statement = parse_asm_statement();
8110 statement = parse_case_statement();
8114 statement = parse_default_statement();
8118 statement = parse_compound_statement(false);
8122 statement = parse_if();
8126 statement = parse_switch();
8130 statement = parse_while();
8134 statement = parse_do();
8138 statement = parse_for();
8142 statement = parse_goto();
8146 statement = parse_continue();
8150 statement = parse_break();
8154 statement = parse_leave();
8158 statement = parse_return();
8162 if(warning.empty_statement) {
8163 warningf(HERE, "statement is empty");
8165 statement = create_empty_statement();
8170 if(look_ahead(1)->type == ':') {
8171 statement = parse_label_statement();
8175 if(is_typedef_symbol(token.v.symbol)) {
8176 statement = parse_declaration_statement();
8180 statement = parse_expression_statement();
8183 case T___extension__:
8184 /* this can be a prefix to a declaration or an expression statement */
8185 /* we simply eat it now and parse the rest with tail recursion */
8188 } while(token.type == T___extension__);
8189 statement = parse_statement();
8193 statement = parse_declaration_statement();
8197 statement = parse_ms_try_statment();
8201 statement = parse_expression_statement();
8204 rem_anchor_token(';');
8206 assert(statement != NULL
8207 && statement->base.source_position.input_name != NULL);
8213 * parse a statement and emits "statement has no effect" warning if needed
8214 * (This is really a wrapper around intern_parse_statement with check for 1
8215 * single warning. It is needed, because for statement expressions we have
8216 * to avoid the warning on the last statement)
8218 static statement_t *parse_statement(void)
8220 statement_t *statement = intern_parse_statement();
8222 if(statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8223 expression_t *expression = statement->expression.expression;
8224 if(!expression_has_effect(expression)) {
8225 warningf(&expression->base.source_position,
8226 "statement has no effect");
8234 * Parse a compound statement.
8236 static statement_t *parse_compound_statement(bool inside_expression_statement)
8238 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8240 statement->base.source_position = token.source_position;
8243 add_anchor_token('}');
8245 int top = environment_top();
8246 scope_t *last_scope = scope;
8247 set_scope(&statement->compound.scope);
8249 statement_t *last_statement = NULL;
8251 while(token.type != '}' && token.type != T_EOF) {
8252 statement_t *sub_statement = intern_parse_statement();
8253 if(is_invalid_statement(sub_statement)) {
8254 /* an error occurred. if we are at an anchor, return */
8260 if(last_statement != NULL) {
8261 last_statement->base.next = sub_statement;
8263 statement->compound.statements = sub_statement;
8266 while(sub_statement->base.next != NULL)
8267 sub_statement = sub_statement->base.next;
8269 last_statement = sub_statement;
8272 if(token.type == '}') {
8275 errorf(&statement->base.source_position,
8276 "end of file while looking for closing '}'");
8279 /* look over all statements again to produce no effect warnings */
8280 if(warning.unused_value) {
8281 statement_t *sub_statement = statement->compound.statements;
8282 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8283 if(sub_statement->kind != STATEMENT_EXPRESSION)
8285 /* don't emit a warning for the last expression in an expression
8286 * statement as it has always an effect */
8287 if(inside_expression_statement && sub_statement->base.next == NULL)
8290 expression_t *expression = sub_statement->expression.expression;
8291 if(!expression_has_effect(expression)) {
8292 warningf(&expression->base.source_position,
8293 "statement has no effect");
8299 rem_anchor_token('}');
8300 assert(scope == &statement->compound.scope);
8301 set_scope(last_scope);
8302 environment_pop_to(top);
8308 * Initialize builtin types.
8310 static void initialize_builtin_types(void)
8312 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8313 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8314 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8315 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8316 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8317 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8318 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8319 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8321 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8322 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8323 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8324 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8328 * Check for unused global static functions and variables
8330 static void check_unused_globals(void)
8332 if (!warning.unused_function && !warning.unused_variable)
8335 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8336 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
8339 type_t *const type = decl->type;
8341 if (is_type_function(skip_typeref(type))) {
8342 if (!warning.unused_function || decl->is_inline)
8345 s = (decl->init.statement != NULL ? "defined" : "declared");
8347 if (!warning.unused_variable)
8353 warningf(&decl->source_position, "'%#T' %s but not used",
8354 type, decl->symbol, s);
8359 * Parse a translation unit.
8361 static void parse_translation_unit(void)
8363 while(token.type != T_EOF) {
8364 if (token.type == ';') {
8365 /* TODO error in strict mode */
8366 warningf(HERE, "stray ';' outside of function");
8369 parse_external_declaration();
8377 * @return the translation unit or NULL if errors occurred.
8379 void start_parsing(void)
8381 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8382 label_stack = NEW_ARR_F(stack_entry_t, 0);
8383 diagnostic_count = 0;
8387 type_set_output(stderr);
8388 ast_set_output(stderr);
8390 assert(unit == NULL);
8391 unit = allocate_ast_zero(sizeof(unit[0]));
8393 assert(global_scope == NULL);
8394 global_scope = &unit->scope;
8396 assert(scope == NULL);
8397 set_scope(&unit->scope);
8399 initialize_builtin_types();
8402 translation_unit_t *finish_parsing(void)
8404 assert(scope == &unit->scope);
8406 last_declaration = NULL;
8408 assert(global_scope == &unit->scope);
8409 check_unused_globals();
8410 global_scope = NULL;
8412 DEL_ARR_F(environment_stack);
8413 DEL_ARR_F(label_stack);
8415 translation_unit_t *result = unit;
8422 lookahead_bufpos = 0;
8423 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8426 parse_translation_unit();
8430 * Initialize the parser.
8432 void init_parser(void)
8435 /* add predefined symbols for extended-decl-modifier */
8436 sym_align = symbol_table_insert("align");
8437 sym_allocate = symbol_table_insert("allocate");
8438 sym_dllimport = symbol_table_insert("dllimport");
8439 sym_dllexport = symbol_table_insert("dllexport");
8440 sym_naked = symbol_table_insert("naked");
8441 sym_noinline = symbol_table_insert("noinline");
8442 sym_noreturn = symbol_table_insert("noreturn");
8443 sym_nothrow = symbol_table_insert("nothrow");
8444 sym_novtable = symbol_table_insert("novtable");
8445 sym_property = symbol_table_insert("property");
8446 sym_get = symbol_table_insert("get");
8447 sym_put = symbol_table_insert("put");
8448 sym_selectany = symbol_table_insert("selectany");
8449 sym_thread = symbol_table_insert("thread");
8450 sym_uuid = symbol_table_insert("uuid");
8451 sym_deprecated = symbol_table_insert("deprecated");
8452 sym_restrict = symbol_table_insert("restrict");
8453 sym_noalias = symbol_table_insert("noalias");
8455 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8457 init_expression_parsers();
8458 obstack_init(&temp_obst);
8460 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8461 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8465 * Terminate the parser.
8467 void exit_parser(void)
8469 obstack_free(&temp_obst, NULL);