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;
532 else if (type == '{')
534 else if (type == '[')
537 while(token.type != end_token ||
538 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
542 case '(': ++parenthesis_count; break;
543 case '{': ++brace_count; break;
544 case '[': ++bracket_count; break;
546 if (parenthesis_count > 0)
554 if (bracket_count > 0)
565 * Eat input tokens until an anchor is found.
567 static void eat_until_anchor(void) {
568 if (token.type == T_EOF)
570 while(token_anchor_set[token.type] == 0) {
571 if (token.type == '(' || token.type == '{' || token.type == '[')
572 eat_until_matching_token(token.type);
573 if (token.type == T_EOF)
579 static void eat_block(void) {
580 eat_until_matching_token('{');
581 if (token.type == '}')
586 * eat all token until a ';' is reached or a stop token is found.
588 static void eat_statement(void) {
589 eat_until_matching_token(';');
590 if (token.type == ';')
594 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
597 * Report a parse error because an expected token was not found.
600 #if defined __GNUC__ && __GNUC__ >= 4
601 __attribute__((sentinel))
603 void parse_error_expected(const char *message, ...)
605 if (message != NULL) {
606 errorf(HERE, "%s", message);
609 va_start(ap, message);
610 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
615 * Report a type error.
617 static void type_error(const char *msg, const source_position_t *source_position,
620 errorf(source_position, "%s, but found type '%T'", msg, type);
624 * Report an incompatible type.
626 static void type_error_incompatible(const char *msg,
627 const source_position_t *source_position, type_t *type1, type_t *type2)
629 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
634 * Expect the the current token is the expected token.
635 * If not, generate an error, eat the current statement,
636 * and goto the end_error label.
638 #define expect(expected) \
640 if (UNLIKELY(token.type != (expected))) { \
641 parse_error_expected(NULL, (expected), NULL); \
642 add_anchor_token(expected); \
643 eat_until_anchor(); \
644 if (token.type == expected) \
646 rem_anchor_token(expected); \
652 static void set_scope(scope_t *new_scope)
655 scope->last_declaration = last_declaration;
659 last_declaration = new_scope->last_declaration;
663 * Search a symbol in a given namespace and returns its declaration or
664 * NULL if this symbol was not found.
666 static declaration_t *get_declaration(const symbol_t *const symbol,
667 const namespace_t namespc)
669 declaration_t *declaration = symbol->declaration;
670 for( ; declaration != NULL; declaration = declaration->symbol_next) {
671 if (declaration->namespc == namespc)
679 * pushs an environment_entry on the environment stack and links the
680 * corresponding symbol to the new entry
682 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
684 symbol_t *symbol = declaration->symbol;
685 namespace_t namespc = (namespace_t) declaration->namespc;
687 /* replace/add declaration into declaration list of the symbol */
688 declaration_t *iter = symbol->declaration;
690 symbol->declaration = declaration;
692 declaration_t *iter_last = NULL;
693 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
694 /* replace an entry? */
695 if (iter->namespc == namespc) {
696 if (iter_last == NULL) {
697 symbol->declaration = declaration;
699 iter_last->symbol_next = declaration;
701 declaration->symbol_next = iter->symbol_next;
706 assert(iter_last->symbol_next == NULL);
707 iter_last->symbol_next = declaration;
711 /* remember old declaration */
713 entry.symbol = symbol;
714 entry.old_declaration = iter;
715 entry.namespc = (unsigned short) namespc;
716 ARR_APP1(stack_entry_t, *stack_ptr, entry);
719 static void environment_push(declaration_t *declaration)
721 assert(declaration->source_position.input_name != NULL);
722 assert(declaration->parent_scope != NULL);
723 stack_push(&environment_stack, declaration);
726 static void label_push(declaration_t *declaration)
728 declaration->parent_scope = ¤t_function->scope;
729 stack_push(&label_stack, declaration);
733 * pops symbols from the environment stack until @p new_top is the top element
735 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
737 stack_entry_t *stack = *stack_ptr;
738 size_t top = ARR_LEN(stack);
741 assert(new_top <= top);
745 for(i = top; i > new_top; --i) {
746 stack_entry_t *entry = &stack[i - 1];
748 declaration_t *old_declaration = entry->old_declaration;
749 symbol_t *symbol = entry->symbol;
750 namespace_t namespc = (namespace_t)entry->namespc;
752 /* replace/remove declaration */
753 declaration_t *declaration = symbol->declaration;
754 assert(declaration != NULL);
755 if (declaration->namespc == namespc) {
756 if (old_declaration == NULL) {
757 symbol->declaration = declaration->symbol_next;
759 symbol->declaration = old_declaration;
762 declaration_t *iter_last = declaration;
763 declaration_t *iter = declaration->symbol_next;
764 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
765 /* replace an entry? */
766 if (iter->namespc == namespc) {
767 assert(iter_last != NULL);
768 iter_last->symbol_next = old_declaration;
769 if (old_declaration != NULL) {
770 old_declaration->symbol_next = iter->symbol_next;
775 assert(iter != NULL);
779 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
782 static void environment_pop_to(size_t new_top)
784 stack_pop_to(&environment_stack, new_top);
787 static void label_pop_to(size_t new_top)
789 stack_pop_to(&label_stack, new_top);
793 static int get_rank(const type_t *type)
795 assert(!is_typeref(type));
796 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
797 * and esp. footnote 108). However we can't fold constants (yet), so we
798 * can't decide whether unsigned int is possible, while int always works.
799 * (unsigned int would be preferable when possible... for stuff like
800 * struct { enum { ... } bla : 4; } ) */
801 if (type->kind == TYPE_ENUM)
802 return ATOMIC_TYPE_INT;
804 assert(type->kind == TYPE_ATOMIC);
805 return type->atomic.akind;
808 static type_t *promote_integer(type_t *type)
810 if (type->kind == TYPE_BITFIELD)
811 type = type->bitfield.base_type;
813 if (get_rank(type) < ATOMIC_TYPE_INT)
820 * Create a cast expression.
822 * @param expression the expression to cast
823 * @param dest_type the destination type
825 static expression_t *create_cast_expression(expression_t *expression,
828 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
830 cast->unary.value = expression;
831 cast->base.type = dest_type;
837 * Check if a given expression represents the 0 pointer constant.
839 static bool is_null_pointer_constant(const expression_t *expression)
841 /* skip void* cast */
842 if (expression->kind == EXPR_UNARY_CAST
843 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
844 expression = expression->unary.value;
847 /* TODO: not correct yet, should be any constant integer expression
848 * which evaluates to 0 */
849 if (expression->kind != EXPR_CONST)
852 type_t *const type = skip_typeref(expression->base.type);
853 if (!is_type_integer(type))
856 return expression->conste.v.int_value == 0;
860 * Create an implicit cast expression.
862 * @param expression the expression to cast
863 * @param dest_type the destination type
865 static expression_t *create_implicit_cast(expression_t *expression,
868 type_t *const source_type = expression->base.type;
870 if (source_type == dest_type)
873 return create_cast_expression(expression, dest_type);
876 typedef enum assign_error_t {
878 ASSIGN_ERROR_INCOMPATIBLE,
879 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
880 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
881 ASSIGN_WARNING_POINTER_FROM_INT,
882 ASSIGN_WARNING_INT_FROM_POINTER
885 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
886 const expression_t *const right,
888 const source_position_t *source_position)
890 type_t *const orig_type_right = right->base.type;
891 type_t *const type_left = skip_typeref(orig_type_left);
892 type_t *const type_right = skip_typeref(orig_type_right);
897 case ASSIGN_ERROR_INCOMPATIBLE:
898 errorf(source_position,
899 "destination type '%T' in %s is incompatible with type '%T'",
900 orig_type_left, context, orig_type_right);
903 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
904 type_t *points_to_left
905 = skip_typeref(type_left->pointer.points_to);
906 type_t *points_to_right
907 = skip_typeref(type_right->pointer.points_to);
909 /* the left type has all qualifiers from the right type */
910 unsigned missing_qualifiers
911 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
912 errorf(source_position,
913 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type",
914 orig_type_left, context, orig_type_right, missing_qualifiers);
918 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
919 warningf(source_position,
920 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
921 orig_type_left, context, right, orig_type_right);
924 case ASSIGN_WARNING_POINTER_FROM_INT:
925 warningf(source_position,
926 "%s makes integer '%T' from pointer '%T' without a cast",
927 context, orig_type_left, orig_type_right);
930 case ASSIGN_WARNING_INT_FROM_POINTER:
931 warningf(source_position,
932 "%s makes integer '%T' from pointer '%T' without a cast",
933 context, orig_type_left, orig_type_right);
937 panic("invalid error value");
941 /** Implements the rules from § 6.5.16.1 */
942 static assign_error_t semantic_assign(type_t *orig_type_left,
943 const expression_t *const right)
945 type_t *const orig_type_right = right->base.type;
946 type_t *const type_left = skip_typeref(orig_type_left);
947 type_t *const type_right = skip_typeref(orig_type_right);
949 if (is_type_pointer(type_left)) {
950 if (is_null_pointer_constant(right)) {
951 return ASSIGN_SUCCESS;
952 } else if (is_type_pointer(type_right)) {
953 type_t *points_to_left
954 = skip_typeref(type_left->pointer.points_to);
955 type_t *points_to_right
956 = skip_typeref(type_right->pointer.points_to);
958 /* the left type has all qualifiers from the right type */
959 unsigned missing_qualifiers
960 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
961 if (missing_qualifiers != 0) {
962 return ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
965 points_to_left = get_unqualified_type(points_to_left);
966 points_to_right = get_unqualified_type(points_to_right);
968 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
969 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
970 return ASSIGN_SUCCESS;
973 if (!types_compatible(points_to_left, points_to_right)) {
974 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
977 return ASSIGN_SUCCESS;
978 } else if (is_type_integer(type_right)) {
979 return ASSIGN_WARNING_POINTER_FROM_INT;
981 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
982 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
983 && is_type_pointer(type_right))) {
984 return ASSIGN_SUCCESS;
985 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
986 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
987 type_t *const unqual_type_left = get_unqualified_type(type_left);
988 type_t *const unqual_type_right = get_unqualified_type(type_right);
989 if (types_compatible(unqual_type_left, unqual_type_right)) {
990 return ASSIGN_SUCCESS;
992 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
993 return ASSIGN_WARNING_INT_FROM_POINTER;
996 if (!is_type_valid(type_left) || !is_type_valid(type_right))
997 return ASSIGN_SUCCESS;
999 return ASSIGN_ERROR_INCOMPATIBLE;
1002 static expression_t *parse_constant_expression(void)
1004 /* start parsing at precedence 7 (conditional expression) */
1005 expression_t *result = parse_sub_expression(7);
1007 if (!is_constant_expression(result)) {
1008 errorf(&result->base.source_position,
1009 "expression '%E' is not constant\n", result);
1015 static expression_t *parse_assignment_expression(void)
1017 /* start parsing at precedence 2 (assignment expression) */
1018 return parse_sub_expression(2);
1021 static type_t *make_global_typedef(const char *name, type_t *type)
1023 symbol_t *const symbol = symbol_table_insert(name);
1025 declaration_t *const declaration = allocate_declaration_zero();
1026 declaration->namespc = NAMESPACE_NORMAL;
1027 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1028 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1029 declaration->type = type;
1030 declaration->symbol = symbol;
1031 declaration->source_position = builtin_source_position;
1033 record_declaration(declaration);
1035 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1036 typedef_type->typedeft.declaration = declaration;
1038 return typedef_type;
1041 static string_t parse_string_literals(void)
1043 assert(token.type == T_STRING_LITERAL);
1044 string_t result = token.v.string;
1048 while (token.type == T_STRING_LITERAL) {
1049 result = concat_strings(&result, &token.v.string);
1056 static const char *gnu_attribute_names[GNU_AK_LAST] = {
1057 [GNU_AK_CONST] = "const",
1058 [GNU_AK_VOLATILE] = "volatile",
1059 [GNU_AK_CDECL] = "cdecl",
1060 [GNU_AK_STDCALL] = "stdcall",
1061 [GNU_AK_FASTCALL] = "fastcall",
1062 [GNU_AK_DEPRECATED] = "deprecated",
1063 [GNU_AK_NOINLINE] = "noinline",
1064 [GNU_AK_NORETURN] = "noreturn",
1065 [GNU_AK_NAKED] = "naked",
1066 [GNU_AK_PURE] = "pure",
1067 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1068 [GNU_AK_MALLOC] = "malloc",
1069 [GNU_AK_WEAK] = "weak",
1070 [GNU_AK_CONSTRUCTOR] = "constructor",
1071 [GNU_AK_DESTRUCTOR] = "destructor",
1072 [GNU_AK_NOTHROW] = "nothrow",
1073 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1074 [GNU_AK_COMMON] = "common",
1075 [GNU_AK_NOCOMMON] = "nocommon",
1076 [GNU_AK_PACKED] = "packed",
1077 [GNU_AK_SHARED] = "shared",
1078 [GNU_AK_NOTSHARED] = "notshared",
1079 [GNU_AK_USED] = "used",
1080 [GNU_AK_UNUSED] = "unused",
1081 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1082 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1083 [GNU_AK_LONGCALL] = "longcall",
1084 [GNU_AK_SHORTCALL] = "shortcall",
1085 [GNU_AK_LONG_CALL] = "long_call",
1086 [GNU_AK_SHORT_CALL] = "short_call",
1087 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1088 [GNU_AK_INTERRUPT] = "interrupt",
1089 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1090 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1091 [GNU_AK_NESTING] = "nesting",
1092 [GNU_AK_NEAR] = "near",
1093 [GNU_AK_FAR] = "far",
1094 [GNU_AK_SIGNAL] = "signal",
1095 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1096 [GNU_AK_TINY_DATA] = "tiny_data",
1097 [GNU_AK_SAVEALL] = "saveall",
1098 [GNU_AK_FLATTEN] = "flatten",
1099 [GNU_AK_SSEREGPARM] = "sseregparm",
1100 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1101 [GNU_AK_RETURN_TWICE] = "return_twice",
1102 [GNU_AK_MAY_ALIAS] = "may_alias",
1103 [GNU_AK_MS_STRUCT] = "ms_struct",
1104 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1105 [GNU_AK_DLLIMPORT] = "dllimport",
1106 [GNU_AK_DLLEXPORT] = "dllexport",
1107 [GNU_AK_ALIGNED] = "aligned",
1108 [GNU_AK_ALIAS] = "alias",
1109 [GNU_AK_SECTION] = "section",
1110 [GNU_AK_FORMAT] = "format",
1111 [GNU_AK_FORMAT_ARG] = "format_arg",
1112 [GNU_AK_WEAKREF] = "weakref",
1113 [GNU_AK_NONNULL] = "nonnull",
1114 [GNU_AK_TLS_MODEL] = "tls_model",
1115 [GNU_AK_VISIBILITY] = "visibility",
1116 [GNU_AK_REGPARM] = "regparm",
1117 [GNU_AK_MODE] = "mode",
1118 [GNU_AK_MODEL] = "model",
1119 [GNU_AK_TRAP_EXIT] = "trap_exit",
1120 [GNU_AK_SP_SWITCH] = "sp_switch",
1121 [GNU_AK_SENTINEL] = "sentinel"
1125 * compare two string, ignoring double underscores on the second.
1127 static int strcmp_underscore(const char *s1, const char *s2) {
1128 if (s2[0] == '_' && s2[1] == '_') {
1129 size_t len2 = strlen(s2);
1130 size_t len1 = strlen(s1);
1131 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1132 return strncmp(s1, s2+2, len2-4);
1136 return strcmp(s1, s2);
1140 * Allocate a new gnu temporal attribute.
1142 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1143 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1144 attribute->kind = kind;
1145 attribute->next = NULL;
1146 attribute->invalid = false;
1147 attribute->have_arguments = false;
1153 * parse one constant expression argument.
1155 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1156 expression_t *expression;
1157 add_anchor_token(')');
1158 expression = parse_constant_expression();
1159 rem_anchor_token(')');
1164 attribute->invalid = true;
1168 * parse a list of constant expressions arguments.
1170 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1171 expression_t *expression;
1172 add_anchor_token(')');
1173 add_anchor_token(',');
1175 expression = parse_constant_expression();
1176 if (token.type != ',')
1180 rem_anchor_token(',');
1181 rem_anchor_token(')');
1186 attribute->invalid = true;
1190 * parse one string literal argument.
1192 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1195 add_anchor_token('(');
1196 if (token.type != T_STRING_LITERAL) {
1197 parse_error_expected("while parsing attribute directive",
1198 T_STRING_LITERAL, NULL);
1201 *string = parse_string_literals();
1202 rem_anchor_token('(');
1206 attribute->invalid = true;
1210 * parse one tls model.
1212 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1213 static const char *tls_models[] = {
1219 string_t string = { NULL, 0 };
1220 parse_gnu_attribute_string_arg(attribute, &string);
1221 if (string.begin != NULL) {
1222 for(size_t i = 0; i < 4; ++i) {
1223 if (strcmp(tls_models[i], string.begin) == 0) {
1224 attribute->u.value = i;
1228 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1230 attribute->invalid = true;
1234 * parse one tls model.
1236 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1237 static const char *visibilities[] = {
1243 string_t string = { NULL, 0 };
1244 parse_gnu_attribute_string_arg(attribute, &string);
1245 if (string.begin != NULL) {
1246 for(size_t i = 0; i < 4; ++i) {
1247 if (strcmp(visibilities[i], string.begin) == 0) {
1248 attribute->u.value = i;
1252 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1254 attribute->invalid = true;
1258 * parse one (code) model.
1260 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1261 static const char *visibilities[] = {
1266 string_t string = { NULL, 0 };
1267 parse_gnu_attribute_string_arg(attribute, &string);
1268 if (string.begin != NULL) {
1269 for(int i = 0; i < 3; ++i) {
1270 if (strcmp(visibilities[i], string.begin) == 0) {
1271 attribute->u.value = i;
1275 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1277 attribute->invalid = true;
1280 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1282 /* TODO: find out what is allowed here... */
1284 /* at least: byte, word, pointer, list of machine modes
1285 * __XXX___ is interpreted as XXX */
1286 add_anchor_token(')');
1287 expect(T_IDENTIFIER);
1288 rem_anchor_token(')');
1292 attribute->invalid = true;
1296 * parse one interrupt argument.
1298 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1299 static const char *interrupts[] = {
1306 string_t string = { NULL, 0 };
1307 parse_gnu_attribute_string_arg(attribute, &string);
1308 if (string.begin != NULL) {
1309 for(size_t i = 0; i < 5; ++i) {
1310 if (strcmp(interrupts[i], string.begin) == 0) {
1311 attribute->u.value = i;
1315 errorf(HERE, "'%s' is not an interrupt", string.begin);
1317 attribute->invalid = true;
1321 * parse ( identifier, const expression, const expression )
1323 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1324 static const char *format_names[] = {
1332 if (token.type != T_IDENTIFIER) {
1333 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1336 const char *name = token.v.symbol->string;
1337 for(i = 0; i < 4; ++i) {
1338 if (strcmp_underscore(format_names[i], name) == 0)
1342 if (warning.attribute)
1343 warningf(HERE, "'%s' is an unrecognized format function type", name);
1348 add_anchor_token(')');
1349 add_anchor_token(',');
1350 parse_constant_expression();
1351 rem_anchor_token(',');
1352 rem_anchor_token('(');
1355 add_anchor_token(')');
1356 parse_constant_expression();
1357 rem_anchor_token('(');
1361 attribute->u.value = true;
1364 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1366 if (!attribute->have_arguments)
1369 /* should have no arguments */
1370 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1371 eat_until_matching_token('(');
1372 /* we have already consumed '(', so we stop before ')', eat it */
1374 attribute->invalid = true;
1378 * Parse one GNU attribute.
1380 * Note that attribute names can be specified WITH or WITHOUT
1381 * double underscores, ie const or __const__.
1383 * The following attributes are parsed without arguments
1408 * no_instrument_function
1409 * warn_unused_result
1426 * externally_visible
1434 * The following attributes are parsed with arguments
1435 * aligned( const expression )
1436 * alias( string literal )
1437 * section( string literal )
1438 * format( identifier, const expression, const expression )
1439 * format_arg( const expression )
1440 * tls_model( string literal )
1441 * visibility( string literal )
1442 * regparm( const expression )
1443 * model( string leteral )
1444 * trap_exit( const expression )
1445 * sp_switch( string literal )
1447 * The following attributes might have arguments
1448 * weak_ref( string literal )
1449 * non_null( const expression // ',' )
1450 * interrupt( string literal )
1451 * sentinel( constant expression )
1453 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1455 gnu_attribute_t *head = *attributes;
1456 gnu_attribute_t *last = *attributes;
1457 decl_modifiers_t modifiers = 0;
1458 gnu_attribute_t *attribute;
1460 eat(T___attribute__);
1464 if (token.type != ')') {
1465 /* find the end of the list */
1467 while(last->next != NULL)
1471 /* non-empty attribute list */
1474 if (token.type == T_const) {
1476 } else if (token.type == T_volatile) {
1478 } else if (token.type == T_cdecl) {
1479 /* __attribute__((cdecl)), WITH ms mode */
1481 } else if (token.type == T_IDENTIFIER) {
1482 const symbol_t *sym = token.v.symbol;
1485 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1492 for(i = 0; i < GNU_AK_LAST; ++i) {
1493 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1496 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1499 if (kind == GNU_AK_LAST) {
1500 if (warning.attribute)
1501 warningf(HERE, "'%s' attribute directive ignored", name);
1503 /* skip possible arguments */
1504 if (token.type == '(') {
1505 eat_until_matching_token(')');
1508 /* check for arguments */
1509 attribute = allocate_gnu_attribute(kind);
1510 if (token.type == '(') {
1512 if (token.type == ')') {
1513 /* empty args are allowed */
1516 attribute->have_arguments = true;
1521 case GNU_AK_VOLATILE:
1523 case GNU_AK_STDCALL:
1524 case GNU_AK_FASTCALL:
1525 case GNU_AK_DEPRECATED:
1530 case GNU_AK_NOCOMMON:
1532 case GNU_AK_NOTSHARED:
1535 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1536 case GNU_AK_WARN_UNUSED_RESULT:
1537 case GNU_AK_LONGCALL:
1538 case GNU_AK_SHORTCALL:
1539 case GNU_AK_LONG_CALL:
1540 case GNU_AK_SHORT_CALL:
1541 case GNU_AK_FUNCTION_VECTOR:
1542 case GNU_AK_INTERRUPT_HANDLER:
1543 case GNU_AK_NMI_HANDLER:
1544 case GNU_AK_NESTING:
1548 case GNU_AK_EIGTHBIT_DATA:
1549 case GNU_AK_TINY_DATA:
1550 case GNU_AK_SAVEALL:
1551 case GNU_AK_FLATTEN:
1552 case GNU_AK_SSEREGPARM:
1553 case GNU_AK_EXTERNALLY_VISIBLE:
1554 case GNU_AK_RETURN_TWICE:
1555 case GNU_AK_MAY_ALIAS:
1556 case GNU_AK_MS_STRUCT:
1557 case GNU_AK_GCC_STRUCT:
1558 check_no_argument(attribute, name);
1562 check_no_argument(attribute, name);
1563 modifiers |= DM_PURE;
1566 case GNU_AK_ALWAYS_INLINE:
1567 check_no_argument(attribute, name);
1568 modifiers |= DM_FORCEINLINE;
1571 case GNU_AK_DLLIMPORT:
1572 check_no_argument(attribute, name);
1573 modifiers |= DM_DLLIMPORT;
1576 case GNU_AK_DLLEXPORT:
1577 check_no_argument(attribute, name);
1578 modifiers |= DM_DLLEXPORT;
1582 check_no_argument(attribute, name);
1583 modifiers |= DM_PACKED;
1586 case GNU_AK_NOINLINE:
1587 check_no_argument(attribute, name);
1588 modifiers |= DM_NOINLINE;
1591 case GNU_AK_NORETURN:
1592 check_no_argument(attribute, name);
1593 modifiers |= DM_NORETURN;
1596 case GNU_AK_NOTHROW:
1597 check_no_argument(attribute, name);
1598 modifiers |= DM_NOTHROW;
1601 case GNU_AK_TRANSPARENT_UNION:
1602 check_no_argument(attribute, name);
1603 modifiers |= DM_TRANSPARENT_UNION;
1606 case GNU_AK_CONSTRUCTOR:
1607 check_no_argument(attribute, name);
1608 modifiers |= DM_CONSTRUCTOR;
1611 case GNU_AK_DESTRUCTOR:
1612 check_no_argument(attribute, name);
1613 modifiers |= DM_DESTRUCTOR;
1616 case GNU_AK_ALIGNED:
1617 /* __align__ may be used without an argument */
1618 if (attribute->have_arguments) {
1619 parse_gnu_attribute_const_arg(attribute);
1623 case GNU_AK_FORMAT_ARG:
1624 case GNU_AK_REGPARM:
1625 case GNU_AK_TRAP_EXIT:
1626 if (!attribute->have_arguments) {
1627 /* should have arguments */
1628 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1629 attribute->invalid = true;
1631 parse_gnu_attribute_const_arg(attribute);
1634 case GNU_AK_SECTION:
1635 case GNU_AK_SP_SWITCH:
1636 if (!attribute->have_arguments) {
1637 /* should have arguments */
1638 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1639 attribute->invalid = true;
1641 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1644 if (!attribute->have_arguments) {
1645 /* should have arguments */
1646 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1647 attribute->invalid = true;
1649 parse_gnu_attribute_format_args(attribute);
1651 case GNU_AK_WEAKREF:
1652 /* may have one string argument */
1653 if (attribute->have_arguments)
1654 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1656 case GNU_AK_NONNULL:
1657 if (attribute->have_arguments)
1658 parse_gnu_attribute_const_arg_list(attribute);
1660 case GNU_AK_TLS_MODEL:
1661 if (!attribute->have_arguments) {
1662 /* should have arguments */
1663 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1665 parse_gnu_attribute_tls_model_arg(attribute);
1667 case GNU_AK_VISIBILITY:
1668 if (!attribute->have_arguments) {
1669 /* should have arguments */
1670 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1672 parse_gnu_attribute_visibility_arg(attribute);
1675 if (!attribute->have_arguments) {
1676 /* should have arguments */
1677 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1679 parse_gnu_attribute_model_arg(attribute);
1683 if (!attribute->have_arguments) {
1684 /* should have arguments */
1685 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1687 parse_gnu_attribute_mode_arg(attribute);
1690 case GNU_AK_INTERRUPT:
1691 /* may have one string argument */
1692 if (attribute->have_arguments)
1693 parse_gnu_attribute_interrupt_arg(attribute);
1695 case GNU_AK_SENTINEL:
1696 /* may have one string argument */
1697 if (attribute->have_arguments)
1698 parse_gnu_attribute_const_arg(attribute);
1701 /* already handled */
1705 if (attribute != NULL) {
1707 last->next = attribute;
1710 head = last = attribute;
1714 if (token.type != ',')
1728 * Parse GNU attributes.
1730 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1732 decl_modifiers_t modifiers = 0;
1735 switch(token.type) {
1736 case T___attribute__:
1737 modifiers |= parse_gnu_attribute(attributes);
1743 if (token.type != T_STRING_LITERAL) {
1744 parse_error_expected("while parsing assembler attribute",
1745 T_STRING_LITERAL, NULL);
1746 eat_until_matching_token('(');
1749 parse_string_literals();
1758 /* TODO record modifier */
1759 warningf(HERE, "Ignoring declaration modifier %K", &token);
1764 goto attributes_finished;
1768 attributes_finished:
1773 static designator_t *parse_designation(void)
1775 designator_t *result = NULL;
1776 designator_t *last = NULL;
1779 designator_t *designator;
1780 switch(token.type) {
1782 designator = allocate_ast_zero(sizeof(designator[0]));
1783 designator->source_position = token.source_position;
1785 add_anchor_token(']');
1786 designator->array_index = parse_constant_expression();
1787 rem_anchor_token(']');
1791 designator = allocate_ast_zero(sizeof(designator[0]));
1792 designator->source_position = token.source_position;
1794 if (token.type != T_IDENTIFIER) {
1795 parse_error_expected("while parsing designator",
1796 T_IDENTIFIER, NULL);
1799 designator->symbol = token.v.symbol;
1807 assert(designator != NULL);
1809 last->next = designator;
1811 result = designator;
1819 static initializer_t *initializer_from_string(array_type_t *type,
1820 const string_t *const string)
1822 /* TODO: check len vs. size of array type */
1825 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1826 initializer->string.string = *string;
1831 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1832 wide_string_t *const string)
1834 /* TODO: check len vs. size of array type */
1837 initializer_t *const initializer =
1838 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1839 initializer->wide_string.string = *string;
1845 * Build an initializer from a given expression.
1847 static initializer_t *initializer_from_expression(type_t *orig_type,
1848 expression_t *expression)
1850 /* TODO check that expression is a constant expression */
1852 /* § 6.7.8.14/15 char array may be initialized by string literals */
1853 type_t *type = skip_typeref(orig_type);
1854 type_t *expr_type_orig = expression->base.type;
1855 type_t *expr_type = skip_typeref(expr_type_orig);
1856 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1857 array_type_t *const array_type = &type->array;
1858 type_t *const element_type = skip_typeref(array_type->element_type);
1860 if (element_type->kind == TYPE_ATOMIC) {
1861 atomic_type_kind_t akind = element_type->atomic.akind;
1862 switch (expression->kind) {
1863 case EXPR_STRING_LITERAL:
1864 if (akind == ATOMIC_TYPE_CHAR
1865 || akind == ATOMIC_TYPE_SCHAR
1866 || akind == ATOMIC_TYPE_UCHAR) {
1867 return initializer_from_string(array_type,
1868 &expression->string.value);
1871 case EXPR_WIDE_STRING_LITERAL: {
1872 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1873 if (get_unqualified_type(element_type) == bare_wchar_type) {
1874 return initializer_from_wide_string(array_type,
1875 &expression->wide_string.value);
1885 assign_error_t error = semantic_assign(type, expression);
1886 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1888 report_assign_error(error, type, expression, "initializer",
1889 &expression->base.source_position);
1891 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1892 result->value.value = create_implicit_cast(expression, type);
1898 * Checks if a given expression can be used as an constant initializer.
1900 static bool is_initializer_constant(const expression_t *expression)
1902 return is_constant_expression(expression)
1903 || is_address_constant(expression);
1907 * Parses an scalar initializer.
1909 * § 6.7.8.11; eat {} without warning
1911 static initializer_t *parse_scalar_initializer(type_t *type,
1912 bool must_be_constant)
1914 /* there might be extra {} hierarchies */
1916 if (token.type == '{') {
1917 warningf(HERE, "extra curly braces around scalar initializer");
1921 } while (token.type == '{');
1924 expression_t *expression = parse_assignment_expression();
1925 if (must_be_constant && !is_initializer_constant(expression)) {
1926 errorf(&expression->base.source_position,
1927 "Initialisation expression '%E' is not constant\n",
1931 initializer_t *initializer = initializer_from_expression(type, expression);
1933 if (initializer == NULL) {
1934 errorf(&expression->base.source_position,
1935 "expression '%E' (type '%T') doesn't match expected type '%T'",
1936 expression, expression->base.type, type);
1941 bool additional_warning_displayed = false;
1943 if (token.type == ',') {
1946 if (token.type != '}') {
1947 if (!additional_warning_displayed) {
1948 warningf(HERE, "additional elements in scalar initializer");
1949 additional_warning_displayed = true;
1960 * An entry in the type path.
1962 typedef struct type_path_entry_t type_path_entry_t;
1963 struct type_path_entry_t {
1964 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1966 size_t index; /**< For array types: the current index. */
1967 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1972 * A type path expression a position inside compound or array types.
1974 typedef struct type_path_t type_path_t;
1975 struct type_path_t {
1976 type_path_entry_t *path; /**< An flexible array containing the current path. */
1977 type_t *top_type; /**< type of the element the path points */
1978 size_t max_index; /**< largest index in outermost array */
1982 * Prints a type path for debugging.
1984 static __attribute__((unused)) void debug_print_type_path(
1985 const type_path_t *path)
1987 size_t len = ARR_LEN(path->path);
1989 for(size_t i = 0; i < len; ++i) {
1990 const type_path_entry_t *entry = & path->path[i];
1992 type_t *type = skip_typeref(entry->type);
1993 if (is_type_compound(type)) {
1994 /* in gcc mode structs can have no members */
1995 if (entry->v.compound_entry == NULL) {
1999 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2000 } else if (is_type_array(type)) {
2001 fprintf(stderr, "[%zd]", entry->v.index);
2003 fprintf(stderr, "-INVALID-");
2006 if (path->top_type != NULL) {
2007 fprintf(stderr, " (");
2008 print_type(path->top_type);
2009 fprintf(stderr, ")");
2014 * Return the top type path entry, ie. in a path
2015 * (type).a.b returns the b.
2017 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2019 size_t len = ARR_LEN(path->path);
2021 return &path->path[len-1];
2025 * Enlarge the type path by an (empty) element.
2027 static type_path_entry_t *append_to_type_path(type_path_t *path)
2029 size_t len = ARR_LEN(path->path);
2030 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2032 type_path_entry_t *result = & path->path[len];
2033 memset(result, 0, sizeof(result[0]));
2038 * Descending into a sub-type. Enter the scope of the current
2041 static void descend_into_subtype(type_path_t *path)
2043 type_t *orig_top_type = path->top_type;
2044 type_t *top_type = skip_typeref(orig_top_type);
2046 assert(is_type_compound(top_type) || is_type_array(top_type));
2048 type_path_entry_t *top = append_to_type_path(path);
2049 top->type = top_type;
2051 if (is_type_compound(top_type)) {
2052 declaration_t *declaration = top_type->compound.declaration;
2053 declaration_t *entry = declaration->scope.declarations;
2054 top->v.compound_entry = entry;
2056 if (entry != NULL) {
2057 path->top_type = entry->type;
2059 path->top_type = NULL;
2062 assert(is_type_array(top_type));
2065 path->top_type = top_type->array.element_type;
2070 * Pop an entry from the given type path, ie. returning from
2071 * (type).a.b to (type).a
2073 static void ascend_from_subtype(type_path_t *path)
2075 type_path_entry_t *top = get_type_path_top(path);
2077 path->top_type = top->type;
2079 size_t len = ARR_LEN(path->path);
2080 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2084 * Pop entries from the given type path until the given
2085 * path level is reached.
2087 static void ascend_to(type_path_t *path, size_t top_path_level)
2089 size_t len = ARR_LEN(path->path);
2091 while(len > top_path_level) {
2092 ascend_from_subtype(path);
2093 len = ARR_LEN(path->path);
2097 static bool walk_designator(type_path_t *path, const designator_t *designator,
2098 bool used_in_offsetof)
2100 for( ; designator != NULL; designator = designator->next) {
2101 type_path_entry_t *top = get_type_path_top(path);
2102 type_t *orig_type = top->type;
2104 type_t *type = skip_typeref(orig_type);
2106 if (designator->symbol != NULL) {
2107 symbol_t *symbol = designator->symbol;
2108 if (!is_type_compound(type)) {
2109 if (is_type_valid(type)) {
2110 errorf(&designator->source_position,
2111 "'.%Y' designator used for non-compound type '%T'",
2117 declaration_t *declaration = type->compound.declaration;
2118 declaration_t *iter = declaration->scope.declarations;
2119 for( ; iter != NULL; iter = iter->next) {
2120 if (iter->symbol == symbol) {
2125 errorf(&designator->source_position,
2126 "'%T' has no member named '%Y'", orig_type, symbol);
2129 if (used_in_offsetof) {
2130 type_t *real_type = skip_typeref(iter->type);
2131 if (real_type->kind == TYPE_BITFIELD) {
2132 errorf(&designator->source_position,
2133 "offsetof designator '%Y' may not specify bitfield",
2139 top->type = orig_type;
2140 top->v.compound_entry = iter;
2141 orig_type = iter->type;
2143 expression_t *array_index = designator->array_index;
2144 assert(designator->array_index != NULL);
2146 if (!is_type_array(type)) {
2147 if (is_type_valid(type)) {
2148 errorf(&designator->source_position,
2149 "[%E] designator used for non-array type '%T'",
2150 array_index, orig_type);
2154 if (!is_type_valid(array_index->base.type)) {
2158 long index = fold_constant(array_index);
2159 if (!used_in_offsetof) {
2161 errorf(&designator->source_position,
2162 "array index [%E] must be positive", array_index);
2165 if (type->array.size_constant == true) {
2166 long array_size = type->array.size;
2167 if (index >= array_size) {
2168 errorf(&designator->source_position,
2169 "designator [%E] (%d) exceeds array size %d",
2170 array_index, index, array_size);
2176 top->type = orig_type;
2177 top->v.index = (size_t) index;
2178 orig_type = type->array.element_type;
2180 path->top_type = orig_type;
2182 if (designator->next != NULL) {
2183 descend_into_subtype(path);
2192 static void advance_current_object(type_path_t *path, size_t top_path_level)
2194 type_path_entry_t *top = get_type_path_top(path);
2196 type_t *type = skip_typeref(top->type);
2197 if (is_type_union(type)) {
2198 /* in unions only the first element is initialized */
2199 top->v.compound_entry = NULL;
2200 } else if (is_type_struct(type)) {
2201 declaration_t *entry = top->v.compound_entry;
2203 entry = entry->next;
2204 top->v.compound_entry = entry;
2205 if (entry != NULL) {
2206 path->top_type = entry->type;
2210 assert(is_type_array(type));
2214 if (!type->array.size_constant || top->v.index < type->array.size) {
2219 /* we're past the last member of the current sub-aggregate, try if we
2220 * can ascend in the type hierarchy and continue with another subobject */
2221 size_t len = ARR_LEN(path->path);
2223 if (len > top_path_level) {
2224 ascend_from_subtype(path);
2225 advance_current_object(path, top_path_level);
2227 path->top_type = NULL;
2232 * skip until token is found.
2234 static void skip_until(int type) {
2235 while(token.type != type) {
2236 if (token.type == T_EOF)
2243 * skip any {...} blocks until a closing bracket is reached.
2245 static void skip_initializers(void)
2247 if (token.type == '{')
2250 while(token.type != '}') {
2251 if (token.type == T_EOF)
2253 if (token.type == '{') {
2261 static initializer_t *create_empty_initializer(void)
2263 static initializer_t empty_initializer
2264 = { .list = { { INITIALIZER_LIST }, 0 } };
2265 return &empty_initializer;
2269 * Parse a part of an initialiser for a struct or union,
2271 static initializer_t *parse_sub_initializer(type_path_t *path,
2272 type_t *outer_type, size_t top_path_level,
2273 parse_initializer_env_t *env)
2275 if (token.type == '}') {
2276 /* empty initializer */
2277 return create_empty_initializer();
2280 type_t *orig_type = path->top_type;
2281 type_t *type = NULL;
2283 if (orig_type == NULL) {
2284 /* We are initializing an empty compound. */
2286 type = skip_typeref(orig_type);
2288 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2289 * initializers in this case. */
2290 if (!is_type_valid(type)) {
2291 skip_initializers();
2292 return create_empty_initializer();
2296 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2299 designator_t *designator = NULL;
2300 if (token.type == '.' || token.type == '[') {
2301 designator = parse_designation();
2303 /* reset path to toplevel, evaluate designator from there */
2304 ascend_to(path, top_path_level);
2305 if (!walk_designator(path, designator, false)) {
2306 /* can't continue after designation error */
2310 initializer_t *designator_initializer
2311 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2312 designator_initializer->designator.designator = designator;
2313 ARR_APP1(initializer_t*, initializers, designator_initializer);
2315 orig_type = path->top_type;
2316 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2321 if (token.type == '{') {
2322 if (type != NULL && is_type_scalar(type)) {
2323 sub = parse_scalar_initializer(type, env->must_be_constant);
2327 if (env->declaration != NULL) {
2328 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2329 env->declaration->symbol);
2331 errorf(HERE, "extra brace group at end of initializer");
2334 descend_into_subtype(path);
2336 add_anchor_token('}');
2337 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2339 rem_anchor_token('}');
2342 ascend_from_subtype(path);
2346 goto error_parse_next;
2350 /* must be an expression */
2351 expression_t *expression = parse_assignment_expression();
2353 if (env->must_be_constant && !is_initializer_constant(expression)) {
2354 errorf(&expression->base.source_position,
2355 "Initialisation expression '%E' is not constant\n",
2360 /* we are already outside, ... */
2364 /* handle { "string" } special case */
2365 if ((expression->kind == EXPR_STRING_LITERAL
2366 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2367 && outer_type != NULL) {
2368 sub = initializer_from_expression(outer_type, expression);
2370 if (token.type == ',') {
2373 if (token.type != '}') {
2374 warningf(HERE, "excessive elements in initializer for type '%T'",
2377 /* TODO: eat , ... */
2382 /* descend into subtypes until expression matches type */
2384 orig_type = path->top_type;
2385 type = skip_typeref(orig_type);
2387 sub = initializer_from_expression(orig_type, expression);
2391 if (!is_type_valid(type)) {
2394 if (is_type_scalar(type)) {
2395 errorf(&expression->base.source_position,
2396 "expression '%E' doesn't match expected type '%T'",
2397 expression, orig_type);
2401 descend_into_subtype(path);
2405 /* update largest index of top array */
2406 const type_path_entry_t *first = &path->path[0];
2407 type_t *first_type = first->type;
2408 first_type = skip_typeref(first_type);
2409 if (is_type_array(first_type)) {
2410 size_t index = first->v.index;
2411 if (index > path->max_index)
2412 path->max_index = index;
2416 /* append to initializers list */
2417 ARR_APP1(initializer_t*, initializers, sub);
2420 if (env->declaration != NULL)
2421 warningf(HERE, "excess elements in struct initializer for '%Y'",
2422 env->declaration->symbol);
2424 warningf(HERE, "excess elements in struct initializer");
2428 if (token.type == '}') {
2432 if (token.type == '}') {
2437 /* advance to the next declaration if we are not at the end */
2438 advance_current_object(path, top_path_level);
2439 orig_type = path->top_type;
2440 if (orig_type != NULL)
2441 type = skip_typeref(orig_type);
2447 size_t len = ARR_LEN(initializers);
2448 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2449 initializer_t *result = allocate_ast_zero(size);
2450 result->kind = INITIALIZER_LIST;
2451 result->list.len = len;
2452 memcpy(&result->list.initializers, initializers,
2453 len * sizeof(initializers[0]));
2455 DEL_ARR_F(initializers);
2456 ascend_to(path, top_path_level+1);
2461 skip_initializers();
2462 DEL_ARR_F(initializers);
2463 ascend_to(path, top_path_level+1);
2468 * Parses an initializer. Parsers either a compound literal
2469 * (env->declaration == NULL) or an initializer of a declaration.
2471 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2473 type_t *type = skip_typeref(env->type);
2474 initializer_t *result = NULL;
2477 if (is_type_scalar(type)) {
2478 result = parse_scalar_initializer(type, env->must_be_constant);
2479 } else if (token.type == '{') {
2483 memset(&path, 0, sizeof(path));
2484 path.top_type = env->type;
2485 path.path = NEW_ARR_F(type_path_entry_t, 0);
2487 descend_into_subtype(&path);
2489 add_anchor_token('}');
2490 result = parse_sub_initializer(&path, env->type, 1, env);
2491 rem_anchor_token('}');
2493 max_index = path.max_index;
2494 DEL_ARR_F(path.path);
2498 /* parse_scalar_initializer() also works in this case: we simply
2499 * have an expression without {} around it */
2500 result = parse_scalar_initializer(type, env->must_be_constant);
2503 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2504 * the array type size */
2505 if (is_type_array(type) && type->array.size_expression == NULL
2506 && result != NULL) {
2508 switch (result->kind) {
2509 case INITIALIZER_LIST:
2510 size = max_index + 1;
2513 case INITIALIZER_STRING:
2514 size = result->string.string.size;
2517 case INITIALIZER_WIDE_STRING:
2518 size = result->wide_string.string.size;
2521 case INITIALIZER_DESIGNATOR:
2522 case INITIALIZER_VALUE:
2523 /* can happen for parse errors */
2528 internal_errorf(HERE, "invalid initializer type");
2531 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2532 cnst->base.type = type_size_t;
2533 cnst->conste.v.int_value = size;
2535 type_t *new_type = duplicate_type(type);
2537 new_type->array.size_expression = cnst;
2538 new_type->array.size_constant = true;
2539 new_type->array.size = size;
2540 env->type = new_type;
2548 static declaration_t *append_declaration(declaration_t *declaration);
2550 static declaration_t *parse_compound_type_specifier(bool is_struct)
2552 gnu_attribute_t *attributes = NULL;
2553 decl_modifiers_t modifiers = 0;
2560 symbol_t *symbol = NULL;
2561 declaration_t *declaration = NULL;
2563 if (token.type == T___attribute__) {
2564 modifiers |= parse_attributes(&attributes);
2567 if (token.type == T_IDENTIFIER) {
2568 symbol = token.v.symbol;
2572 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2574 declaration = get_declaration(symbol, NAMESPACE_UNION);
2576 } else if (token.type != '{') {
2578 parse_error_expected("while parsing struct type specifier",
2579 T_IDENTIFIER, '{', NULL);
2581 parse_error_expected("while parsing union type specifier",
2582 T_IDENTIFIER, '{', NULL);
2588 if (declaration == NULL) {
2589 declaration = allocate_declaration_zero();
2590 declaration->namespc =
2591 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2592 declaration->source_position = token.source_position;
2593 declaration->symbol = symbol;
2594 declaration->parent_scope = scope;
2595 if (symbol != NULL) {
2596 environment_push(declaration);
2598 append_declaration(declaration);
2601 if (token.type == '{') {
2602 if (declaration->init.complete) {
2603 assert(symbol != NULL);
2604 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2605 is_struct ? "struct" : "union", symbol,
2606 &declaration->source_position);
2607 declaration->scope.declarations = NULL;
2609 declaration->init.complete = true;
2611 parse_compound_type_entries(declaration);
2612 modifiers |= parse_attributes(&attributes);
2615 declaration->modifiers |= modifiers;
2619 static void parse_enum_entries(type_t *const enum_type)
2623 if (token.type == '}') {
2625 errorf(HERE, "empty enum not allowed");
2629 add_anchor_token('}');
2631 if (token.type != T_IDENTIFIER) {
2632 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2634 rem_anchor_token('}');
2638 declaration_t *const entry = allocate_declaration_zero();
2639 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2640 entry->type = enum_type;
2641 entry->symbol = token.v.symbol;
2642 entry->source_position = token.source_position;
2645 if (token.type == '=') {
2647 expression_t *value = parse_constant_expression();
2649 value = create_implicit_cast(value, enum_type);
2650 entry->init.enum_value = value;
2655 record_declaration(entry);
2657 if (token.type != ',')
2660 } while(token.type != '}');
2661 rem_anchor_token('}');
2669 static type_t *parse_enum_specifier(void)
2671 gnu_attribute_t *attributes = NULL;
2672 declaration_t *declaration;
2676 if (token.type == T_IDENTIFIER) {
2677 symbol = token.v.symbol;
2680 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2681 } else if (token.type != '{') {
2682 parse_error_expected("while parsing enum type specifier",
2683 T_IDENTIFIER, '{', NULL);
2690 if (declaration == NULL) {
2691 declaration = allocate_declaration_zero();
2692 declaration->namespc = NAMESPACE_ENUM;
2693 declaration->source_position = token.source_position;
2694 declaration->symbol = symbol;
2695 declaration->parent_scope = scope;
2698 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2699 type->enumt.declaration = declaration;
2701 if (token.type == '{') {
2702 if (declaration->init.complete) {
2703 errorf(HERE, "multiple definitions of enum %Y", symbol);
2705 if (symbol != NULL) {
2706 environment_push(declaration);
2708 append_declaration(declaration);
2709 declaration->init.complete = true;
2711 parse_enum_entries(type);
2712 parse_attributes(&attributes);
2719 * if a symbol is a typedef to another type, return true
2721 static bool is_typedef_symbol(symbol_t *symbol)
2723 const declaration_t *const declaration =
2724 get_declaration(symbol, NAMESPACE_NORMAL);
2726 declaration != NULL &&
2727 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2730 static type_t *parse_typeof(void)
2737 add_anchor_token(')');
2739 expression_t *expression = NULL;
2742 switch(token.type) {
2743 case T___extension__:
2744 /* this can be a prefix to a typename or an expression */
2745 /* we simply eat it now. */
2748 } while(token.type == T___extension__);
2752 if (is_typedef_symbol(token.v.symbol)) {
2753 type = parse_typename();
2755 expression = parse_expression();
2756 type = expression->base.type;
2761 type = parse_typename();
2765 expression = parse_expression();
2766 type = expression->base.type;
2770 rem_anchor_token(')');
2773 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2774 typeof_type->typeoft.expression = expression;
2775 typeof_type->typeoft.typeof_type = type;
2783 SPECIFIER_SIGNED = 1 << 0,
2784 SPECIFIER_UNSIGNED = 1 << 1,
2785 SPECIFIER_LONG = 1 << 2,
2786 SPECIFIER_INT = 1 << 3,
2787 SPECIFIER_DOUBLE = 1 << 4,
2788 SPECIFIER_CHAR = 1 << 5,
2789 SPECIFIER_SHORT = 1 << 6,
2790 SPECIFIER_LONG_LONG = 1 << 7,
2791 SPECIFIER_FLOAT = 1 << 8,
2792 SPECIFIER_BOOL = 1 << 9,
2793 SPECIFIER_VOID = 1 << 10,
2794 SPECIFIER_INT8 = 1 << 11,
2795 SPECIFIER_INT16 = 1 << 12,
2796 SPECIFIER_INT32 = 1 << 13,
2797 SPECIFIER_INT64 = 1 << 14,
2798 SPECIFIER_INT128 = 1 << 15,
2799 SPECIFIER_COMPLEX = 1 << 16,
2800 SPECIFIER_IMAGINARY = 1 << 17,
2803 static type_t *create_builtin_type(symbol_t *const symbol,
2804 type_t *const real_type)
2806 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2807 type->builtin.symbol = symbol;
2808 type->builtin.real_type = real_type;
2810 type_t *result = typehash_insert(type);
2811 if (type != result) {
2818 static type_t *get_typedef_type(symbol_t *symbol)
2820 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2821 if (declaration == NULL ||
2822 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2825 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2826 type->typedeft.declaration = declaration;
2832 * check for the allowed MS alignment values.
2834 static bool check_elignment_value(long long intvalue) {
2835 if (intvalue < 1 || intvalue > 8192) {
2836 errorf(HERE, "illegal alignment value");
2839 unsigned v = (unsigned)intvalue;
2840 for(unsigned i = 1; i <= 8192; i += i) {
2844 errorf(HERE, "alignment must be power of two");
2848 #define DET_MOD(name, tag) do { \
2849 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2850 *modifiers |= tag; \
2853 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2855 decl_modifiers_t *modifiers = &specifiers->modifiers;
2858 if (token.type == T_restrict) {
2860 DET_MOD(restrict, DM_RESTRICT);
2862 } else if (token.type != T_IDENTIFIER)
2864 symbol_t *symbol = token.v.symbol;
2865 if (symbol == sym_align) {
2868 if (token.type != T_INTEGER)
2870 if (check_elignment_value(token.v.intvalue)) {
2871 if (specifiers->alignment != 0)
2872 warningf(HERE, "align used more than once");
2873 specifiers->alignment = (unsigned char)token.v.intvalue;
2877 } else if (symbol == sym_allocate) {
2880 if (token.type != T_IDENTIFIER)
2882 (void)token.v.symbol;
2884 } else if (symbol == sym_dllimport) {
2886 DET_MOD(dllimport, DM_DLLIMPORT);
2887 } else if (symbol == sym_dllexport) {
2889 DET_MOD(dllexport, DM_DLLEXPORT);
2890 } else if (symbol == sym_thread) {
2892 DET_MOD(thread, DM_THREAD);
2893 } else if (symbol == sym_naked) {
2895 DET_MOD(naked, DM_NAKED);
2896 } else if (symbol == sym_noinline) {
2898 DET_MOD(noinline, DM_NOINLINE);
2899 } else if (symbol == sym_noreturn) {
2901 DET_MOD(noreturn, DM_NORETURN);
2902 } else if (symbol == sym_nothrow) {
2904 DET_MOD(nothrow, DM_NOTHROW);
2905 } else if (symbol == sym_novtable) {
2907 DET_MOD(novtable, DM_NOVTABLE);
2908 } else if (symbol == sym_property) {
2912 bool is_get = false;
2913 if (token.type != T_IDENTIFIER)
2915 if (token.v.symbol == sym_get) {
2917 } else if (token.v.symbol == sym_put) {
2919 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2924 if (token.type != T_IDENTIFIER)
2927 if (specifiers->get_property_sym != NULL) {
2928 errorf(HERE, "get property name already specified");
2930 specifiers->get_property_sym = token.v.symbol;
2933 if (specifiers->put_property_sym != NULL) {
2934 errorf(HERE, "put property name already specified");
2936 specifiers->put_property_sym = token.v.symbol;
2940 if (token.type == ',') {
2947 } else if (symbol == sym_selectany) {
2949 DET_MOD(selectany, DM_SELECTANY);
2950 } else if (symbol == sym_uuid) {
2953 if (token.type != T_STRING_LITERAL)
2957 } else if (symbol == sym_deprecated) {
2959 if (specifiers->deprecated != 0)
2960 warningf(HERE, "deprecated used more than once");
2961 specifiers->deprecated = 1;
2962 if (token.type == '(') {
2964 if (token.type == T_STRING_LITERAL) {
2965 specifiers->deprecated_string = token.v.string.begin;
2968 errorf(HERE, "string literal expected");
2972 } else if (symbol == sym_noalias) {
2974 DET_MOD(noalias, DM_NOALIAS);
2976 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2978 if (token.type == '(')
2982 if (token.type == ',')
2989 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2991 type_t *type = NULL;
2992 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2993 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
2994 unsigned type_specifiers = 0;
2997 specifiers->source_position = token.source_position;
3000 switch(token.type) {
3003 #define MATCH_STORAGE_CLASS(token, class) \
3005 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3006 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3008 specifiers->declared_storage_class = class; \
3012 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3013 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3014 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3015 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3016 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3021 add_anchor_token(')');
3022 parse_microsoft_extended_decl_modifier(specifiers);
3023 rem_anchor_token(')');
3028 switch (specifiers->declared_storage_class) {
3029 case STORAGE_CLASS_NONE:
3030 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3033 case STORAGE_CLASS_EXTERN:
3034 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3037 case STORAGE_CLASS_STATIC:
3038 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3042 errorf(HERE, "multiple storage classes in declaration specifiers");
3048 /* type qualifiers */
3049 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3051 qualifiers |= qualifier; \
3055 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3056 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3057 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3058 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3059 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3060 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3061 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3062 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3064 case T___extension__:
3069 /* type specifiers */
3070 #define MATCH_SPECIFIER(token, specifier, name) \
3073 if (type_specifiers & specifier) { \
3074 errorf(HERE, "multiple " name " type specifiers given"); \
3076 type_specifiers |= specifier; \
3080 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3081 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3082 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3083 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3084 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3085 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3086 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3087 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3088 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3089 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3090 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3091 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3092 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3093 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3094 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3095 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3097 case T__forceinline:
3098 /* only in microsoft mode */
3099 specifiers->modifiers |= DM_FORCEINLINE;
3103 specifiers->is_inline = true;
3108 if (type_specifiers & SPECIFIER_LONG_LONG) {
3109 errorf(HERE, "multiple type specifiers given");
3110 } else if (type_specifiers & SPECIFIER_LONG) {
3111 type_specifiers |= SPECIFIER_LONG_LONG;
3113 type_specifiers |= SPECIFIER_LONG;
3118 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3120 type->compound.declaration = parse_compound_type_specifier(true);
3124 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3125 type->compound.declaration = parse_compound_type_specifier(false);
3126 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3127 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3131 type = parse_enum_specifier();
3134 type = parse_typeof();
3136 case T___builtin_va_list:
3137 type = duplicate_type(type_valist);
3141 case T___attribute__:
3142 specifiers->modifiers
3143 |= parse_attributes(&specifiers->gnu_attributes);
3144 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3145 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3148 case T_IDENTIFIER: {
3149 /* only parse identifier if we haven't found a type yet */
3150 if (type != NULL || type_specifiers != 0)
3151 goto finish_specifiers;
3153 type_t *typedef_type = get_typedef_type(token.v.symbol);
3155 if (typedef_type == NULL)
3156 goto finish_specifiers;
3159 type = typedef_type;
3163 /* function specifier */
3165 goto finish_specifiers;
3172 atomic_type_kind_t atomic_type;
3174 /* match valid basic types */
3175 switch(type_specifiers) {
3176 case SPECIFIER_VOID:
3177 atomic_type = ATOMIC_TYPE_VOID;
3179 case SPECIFIER_CHAR:
3180 atomic_type = ATOMIC_TYPE_CHAR;
3182 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3183 atomic_type = ATOMIC_TYPE_SCHAR;
3185 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3186 atomic_type = ATOMIC_TYPE_UCHAR;
3188 case SPECIFIER_SHORT:
3189 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3190 case SPECIFIER_SHORT | SPECIFIER_INT:
3191 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3192 atomic_type = ATOMIC_TYPE_SHORT;
3194 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3195 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3196 atomic_type = ATOMIC_TYPE_USHORT;
3199 case SPECIFIER_SIGNED:
3200 case SPECIFIER_SIGNED | SPECIFIER_INT:
3201 atomic_type = ATOMIC_TYPE_INT;
3203 case SPECIFIER_UNSIGNED:
3204 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3205 atomic_type = ATOMIC_TYPE_UINT;
3207 case SPECIFIER_LONG:
3208 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3209 case SPECIFIER_LONG | SPECIFIER_INT:
3210 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3211 atomic_type = ATOMIC_TYPE_LONG;
3213 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3214 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3215 atomic_type = ATOMIC_TYPE_ULONG;
3217 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3218 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3219 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3220 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3222 atomic_type = ATOMIC_TYPE_LONGLONG;
3224 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3225 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3227 atomic_type = ATOMIC_TYPE_ULONGLONG;
3230 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3231 atomic_type = unsigned_int8_type_kind;
3234 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3235 atomic_type = unsigned_int16_type_kind;
3238 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3239 atomic_type = unsigned_int32_type_kind;
3242 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3243 atomic_type = unsigned_int64_type_kind;
3246 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3247 atomic_type = unsigned_int128_type_kind;
3250 case SPECIFIER_INT8:
3251 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3252 atomic_type = int8_type_kind;
3255 case SPECIFIER_INT16:
3256 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3257 atomic_type = int16_type_kind;
3260 case SPECIFIER_INT32:
3261 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3262 atomic_type = int32_type_kind;
3265 case SPECIFIER_INT64:
3266 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3267 atomic_type = int64_type_kind;
3270 case SPECIFIER_INT128:
3271 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3272 atomic_type = int128_type_kind;
3275 case SPECIFIER_FLOAT:
3276 atomic_type = ATOMIC_TYPE_FLOAT;
3278 case SPECIFIER_DOUBLE:
3279 atomic_type = ATOMIC_TYPE_DOUBLE;
3281 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3282 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3284 case SPECIFIER_BOOL:
3285 atomic_type = ATOMIC_TYPE_BOOL;
3287 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3288 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3289 atomic_type = ATOMIC_TYPE_FLOAT;
3291 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3292 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3293 atomic_type = ATOMIC_TYPE_DOUBLE;
3295 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3296 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3297 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3300 /* invalid specifier combination, give an error message */
3301 if (type_specifiers == 0) {
3302 if (! strict_mode) {
3303 if (warning.implicit_int) {
3304 warningf(HERE, "no type specifiers in declaration, using 'int'");
3306 atomic_type = ATOMIC_TYPE_INT;
3309 errorf(HERE, "no type specifiers given in declaration");
3311 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3312 (type_specifiers & SPECIFIER_UNSIGNED)) {
3313 errorf(HERE, "signed and unsigned specifiers gives");
3314 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3315 errorf(HERE, "only integer types can be signed or unsigned");
3317 errorf(HERE, "multiple datatypes in declaration");
3319 atomic_type = ATOMIC_TYPE_INVALID;
3322 if (type_specifiers & SPECIFIER_COMPLEX &&
3323 atomic_type != ATOMIC_TYPE_INVALID) {
3324 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3325 type->complex.akind = atomic_type;
3326 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3327 atomic_type != ATOMIC_TYPE_INVALID) {
3328 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3329 type->imaginary.akind = atomic_type;
3331 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3332 type->atomic.akind = atomic_type;
3336 if (type_specifiers != 0) {
3337 errorf(HERE, "multiple datatypes in declaration");
3341 /* FIXME: check type qualifiers here */
3343 type->base.qualifiers = qualifiers;
3344 type->base.modifiers = modifiers;
3346 type_t *result = typehash_insert(type);
3347 if (newtype && result != type) {
3351 specifiers->type = result;
3356 static type_qualifiers_t parse_type_qualifiers(void)
3358 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3361 switch(token.type) {
3362 /* type qualifiers */
3363 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3364 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3365 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3366 /* microsoft extended type modifiers */
3367 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3368 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3369 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3370 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3371 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3379 static declaration_t *parse_identifier_list(void)
3381 declaration_t *declarations = NULL;
3382 declaration_t *last_declaration = NULL;
3384 declaration_t *const declaration = allocate_declaration_zero();
3385 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3386 declaration->source_position = token.source_position;
3387 declaration->symbol = token.v.symbol;
3390 if (last_declaration != NULL) {
3391 last_declaration->next = declaration;
3393 declarations = declaration;
3395 last_declaration = declaration;
3397 if (token.type != ',') {
3401 } while(token.type == T_IDENTIFIER);
3403 return declarations;
3406 static void semantic_parameter(declaration_t *declaration)
3408 /* TODO: improve error messages */
3410 if (declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3411 errorf(HERE, "typedef not allowed in parameter list");
3412 } else if (declaration->declared_storage_class != STORAGE_CLASS_NONE
3413 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3414 errorf(HERE, "parameter may only have none or register storage class");
3417 type_t *const orig_type = declaration->type;
3418 type_t * type = skip_typeref(orig_type);
3420 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3421 * into a pointer. § 6.7.5.3 (7) */
3422 if (is_type_array(type)) {
3423 type_t *const element_type = type->array.element_type;
3425 type = make_pointer_type(element_type, type->base.qualifiers);
3427 declaration->type = type;
3430 if (is_type_incomplete(type)) {
3431 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3432 orig_type, declaration->symbol);
3436 static declaration_t *parse_parameter(void)
3438 declaration_specifiers_t specifiers;
3439 memset(&specifiers, 0, sizeof(specifiers));
3441 parse_declaration_specifiers(&specifiers);
3443 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3448 static declaration_t *parse_parameters(function_type_t *type)
3450 declaration_t *declarations = NULL;
3453 add_anchor_token(')');
3454 int saved_comma_state = save_and_reset_anchor_state(',');
3456 if (token.type == T_IDENTIFIER) {
3457 symbol_t *symbol = token.v.symbol;
3458 if (!is_typedef_symbol(symbol)) {
3459 type->kr_style_parameters = true;
3460 declarations = parse_identifier_list();
3461 goto parameters_finished;
3465 if (token.type == ')') {
3466 type->unspecified_parameters = 1;
3467 goto parameters_finished;
3470 declaration_t *declaration;
3471 declaration_t *last_declaration = NULL;
3472 function_parameter_t *parameter;
3473 function_parameter_t *last_parameter = NULL;
3476 switch(token.type) {
3480 goto parameters_finished;
3483 case T___extension__:
3485 declaration = parse_parameter();
3487 /* func(void) is not a parameter */
3488 if (last_parameter == NULL
3489 && token.type == ')'
3490 && declaration->symbol == NULL
3491 && skip_typeref(declaration->type) == type_void) {
3492 goto parameters_finished;
3494 semantic_parameter(declaration);
3496 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3497 memset(parameter, 0, sizeof(parameter[0]));
3498 parameter->type = declaration->type;
3500 if (last_parameter != NULL) {
3501 last_declaration->next = declaration;
3502 last_parameter->next = parameter;
3504 type->parameters = parameter;
3505 declarations = declaration;
3507 last_parameter = parameter;
3508 last_declaration = declaration;
3512 goto parameters_finished;
3514 if (token.type != ',') {
3515 goto parameters_finished;
3521 parameters_finished:
3522 rem_anchor_token(')');
3525 restore_anchor_state(',', saved_comma_state);
3526 return declarations;
3529 restore_anchor_state(',', saved_comma_state);
3538 } construct_type_kind_t;
3540 typedef struct construct_type_t construct_type_t;
3541 struct construct_type_t {
3542 construct_type_kind_t kind;
3543 construct_type_t *next;
3546 typedef struct parsed_pointer_t parsed_pointer_t;
3547 struct parsed_pointer_t {
3548 construct_type_t construct_type;
3549 type_qualifiers_t type_qualifiers;
3552 typedef struct construct_function_type_t construct_function_type_t;
3553 struct construct_function_type_t {
3554 construct_type_t construct_type;
3555 type_t *function_type;
3558 typedef struct parsed_array_t parsed_array_t;
3559 struct parsed_array_t {
3560 construct_type_t construct_type;
3561 type_qualifiers_t type_qualifiers;
3567 typedef struct construct_base_type_t construct_base_type_t;
3568 struct construct_base_type_t {
3569 construct_type_t construct_type;
3573 static construct_type_t *parse_pointer_declarator(void)
3577 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3578 memset(pointer, 0, sizeof(pointer[0]));
3579 pointer->construct_type.kind = CONSTRUCT_POINTER;
3580 pointer->type_qualifiers = parse_type_qualifiers();
3582 return (construct_type_t*) pointer;
3585 static construct_type_t *parse_array_declarator(void)
3588 add_anchor_token(']');
3590 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3591 memset(array, 0, sizeof(array[0]));
3592 array->construct_type.kind = CONSTRUCT_ARRAY;
3594 if (token.type == T_static) {
3595 array->is_static = true;
3599 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3600 if (type_qualifiers != 0) {
3601 if (token.type == T_static) {
3602 array->is_static = true;
3606 array->type_qualifiers = type_qualifiers;
3608 if (token.type == '*' && look_ahead(1)->type == ']') {
3609 array->is_variable = true;
3611 } else if (token.type != ']') {
3612 array->size = parse_assignment_expression();
3615 rem_anchor_token(']');
3618 return (construct_type_t*) array;
3623 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3626 if (declaration != NULL) {
3627 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3629 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3632 declaration_t *parameters = parse_parameters(&type->function);
3633 if (declaration != NULL) {
3634 declaration->scope.declarations = parameters;
3637 construct_function_type_t *construct_function_type =
3638 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3639 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3640 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3641 construct_function_type->function_type = type;
3643 return (construct_type_t*) construct_function_type;
3646 static void fix_declaration_type(declaration_t *declaration)
3648 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3649 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3651 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3652 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3654 if (declaration->type->base.modifiers == type_modifiers)
3657 type_t *copy = duplicate_type(declaration->type);
3658 copy->base.modifiers = type_modifiers;
3660 type_t *result = typehash_insert(copy);
3661 if (result != copy) {
3662 obstack_free(type_obst, copy);
3665 declaration->type = result;
3668 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3669 bool may_be_abstract)
3671 /* construct a single linked list of construct_type_t's which describe
3672 * how to construct the final declarator type */
3673 construct_type_t *first = NULL;
3674 construct_type_t *last = NULL;
3675 gnu_attribute_t *attributes = NULL;
3677 decl_modifiers_t modifiers = parse_attributes(&attributes);
3680 while(token.type == '*') {
3681 construct_type_t *type = parse_pointer_declarator();
3691 /* TODO: find out if this is correct */
3692 modifiers |= parse_attributes(&attributes);
3695 construct_type_t *inner_types = NULL;
3697 switch(token.type) {
3699 if (declaration == NULL) {
3700 errorf(HERE, "no identifier expected in typename");
3702 declaration->symbol = token.v.symbol;
3703 declaration->source_position = token.source_position;
3709 add_anchor_token(')');
3710 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3711 rem_anchor_token(')');
3715 if (may_be_abstract)
3717 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3718 /* avoid a loop in the outermost scope, because eat_statement doesn't
3720 if (token.type == '}' && current_function == NULL) {
3728 construct_type_t *p = last;
3731 construct_type_t *type;
3732 switch(token.type) {
3734 type = parse_function_declarator(declaration);
3737 type = parse_array_declarator();
3740 goto declarator_finished;
3743 /* insert in the middle of the list (behind p) */
3745 type->next = p->next;
3756 declarator_finished:
3757 modifiers |= parse_attributes(&attributes);
3758 if (declaration != NULL) {
3759 declaration->modifiers |= modifiers;
3762 /* append inner_types at the end of the list, we don't to set last anymore
3763 * as it's not needed anymore */
3765 assert(first == NULL);
3766 first = inner_types;
3768 last->next = inner_types;
3776 static type_t *construct_declarator_type(construct_type_t *construct_list,
3779 construct_type_t *iter = construct_list;
3780 for( ; iter != NULL; iter = iter->next) {
3781 switch(iter->kind) {
3782 case CONSTRUCT_INVALID:
3783 internal_errorf(HERE, "invalid type construction found");
3784 case CONSTRUCT_FUNCTION: {
3785 construct_function_type_t *construct_function_type
3786 = (construct_function_type_t*) iter;
3788 type_t *function_type = construct_function_type->function_type;
3790 function_type->function.return_type = type;
3792 type_t *skipped_return_type = skip_typeref(type);
3793 if (is_type_function(skipped_return_type)) {
3794 errorf(HERE, "function returning function is not allowed");
3795 type = type_error_type;
3796 } else if (is_type_array(skipped_return_type)) {
3797 errorf(HERE, "function returning array is not allowed");
3798 type = type_error_type;
3800 type = function_type;
3805 case CONSTRUCT_POINTER: {
3806 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3807 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3808 pointer_type->pointer.points_to = type;
3809 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3811 type = pointer_type;
3815 case CONSTRUCT_ARRAY: {
3816 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3817 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3819 expression_t *size_expression = parsed_array->size;
3820 if (size_expression != NULL) {
3822 = create_implicit_cast(size_expression, type_size_t);
3825 array_type->base.qualifiers = parsed_array->type_qualifiers;
3826 array_type->array.element_type = type;
3827 array_type->array.is_static = parsed_array->is_static;
3828 array_type->array.is_variable = parsed_array->is_variable;
3829 array_type->array.size_expression = size_expression;
3831 if (size_expression != NULL) {
3832 if (is_constant_expression(size_expression)) {
3833 array_type->array.size_constant = true;
3834 array_type->array.size
3835 = fold_constant(size_expression);
3837 array_type->array.is_vla = true;
3841 type_t *skipped_type = skip_typeref(type);
3842 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3843 errorf(HERE, "array of void is not allowed");
3844 type = type_error_type;
3852 type_t *hashed_type = typehash_insert(type);
3853 if (hashed_type != type) {
3854 /* the function type was constructed earlier freeing it here will
3855 * destroy other types... */
3856 if (iter->kind != CONSTRUCT_FUNCTION) {
3866 static declaration_t *parse_declarator(
3867 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3869 declaration_t *const declaration = allocate_declaration_zero();
3870 declaration->declared_storage_class = specifiers->declared_storage_class;
3871 declaration->modifiers = specifiers->modifiers;
3872 declaration->deprecated = specifiers->deprecated;
3873 declaration->deprecated_string = specifiers->deprecated_string;
3874 declaration->get_property_sym = specifiers->get_property_sym;
3875 declaration->put_property_sym = specifiers->put_property_sym;
3876 declaration->is_inline = specifiers->is_inline;
3878 declaration->storage_class = specifiers->declared_storage_class;
3879 if (declaration->storage_class == STORAGE_CLASS_NONE
3880 && scope != global_scope) {
3881 declaration->storage_class = STORAGE_CLASS_AUTO;
3884 if (specifiers->alignment != 0) {
3885 /* TODO: add checks here */
3886 declaration->alignment = specifiers->alignment;
3889 construct_type_t *construct_type
3890 = parse_inner_declarator(declaration, may_be_abstract);
3891 type_t *const type = specifiers->type;
3892 declaration->type = construct_declarator_type(construct_type, type);
3894 fix_declaration_type(declaration);
3896 if (construct_type != NULL) {
3897 obstack_free(&temp_obst, construct_type);
3903 static type_t *parse_abstract_declarator(type_t *base_type)
3905 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3907 type_t *result = construct_declarator_type(construct_type, base_type);
3908 if (construct_type != NULL) {
3909 obstack_free(&temp_obst, construct_type);
3915 static declaration_t *append_declaration(declaration_t* const declaration)
3917 if (last_declaration != NULL) {
3918 last_declaration->next = declaration;
3920 scope->declarations = declaration;
3922 last_declaration = declaration;
3927 * Check if the declaration of main is suspicious. main should be a
3928 * function with external linkage, returning int, taking either zero
3929 * arguments, two, or three arguments of appropriate types, ie.
3931 * int main([ int argc, char **argv [, char **env ] ]).
3933 * @param decl the declaration to check
3934 * @param type the function type of the declaration
3936 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3938 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3939 warningf(&decl->source_position,
3940 "'main' is normally a non-static function");
3942 if (skip_typeref(func_type->return_type) != type_int) {
3943 warningf(&decl->source_position,
3944 "return type of 'main' should be 'int', but is '%T'",
3945 func_type->return_type);
3947 const function_parameter_t *parm = func_type->parameters;
3949 type_t *const first_type = parm->type;
3950 if (!types_compatible(skip_typeref(first_type), type_int)) {
3951 warningf(&decl->source_position,
3952 "first argument of 'main' should be 'int', but is '%T'", first_type);
3956 type_t *const second_type = parm->type;
3957 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3958 warningf(&decl->source_position,
3959 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3963 type_t *const third_type = parm->type;
3964 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3965 warningf(&decl->source_position,
3966 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3970 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3974 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3980 * Check if a symbol is the equal to "main".
3982 static bool is_sym_main(const symbol_t *const sym)
3984 return strcmp(sym->string, "main") == 0;
3987 static declaration_t *internal_record_declaration(
3988 declaration_t *const declaration,
3989 const bool is_function_definition)
3991 const symbol_t *const symbol = declaration->symbol;
3992 const namespace_t namespc = (namespace_t)declaration->namespc;
3994 assert(declaration->symbol != NULL);
3995 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3997 type_t *const orig_type = declaration->type;
3998 type_t *const type = skip_typeref(orig_type);
3999 if (is_type_function(type) &&
4000 type->function.unspecified_parameters &&
4001 warning.strict_prototypes &&
4002 previous_declaration == NULL) {
4003 warningf(&declaration->source_position,
4004 "function declaration '%#T' is not a prototype",
4005 orig_type, declaration->symbol);
4008 if (is_function_definition && warning.main && is_sym_main(symbol)) {
4009 check_type_of_main(declaration, &type->function);
4012 assert(declaration != previous_declaration);
4013 if (previous_declaration != NULL
4014 && previous_declaration->parent_scope == scope) {
4015 /* can happen for K&R style declarations */
4016 if (previous_declaration->type == NULL) {
4017 previous_declaration->type = declaration->type;
4020 const type_t *prev_type = skip_typeref(previous_declaration->type);
4021 if (!types_compatible(type, prev_type)) {
4022 errorf(&declaration->source_position,
4023 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4024 orig_type, symbol, previous_declaration->type, symbol,
4025 &previous_declaration->source_position);
4027 unsigned old_storage_class = previous_declaration->storage_class;
4028 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4029 errorf(&declaration->source_position,
4030 "redeclaration of enum entry '%Y' (declared %P)",
4031 symbol, &previous_declaration->source_position);
4032 return previous_declaration;
4035 unsigned new_storage_class = declaration->storage_class;
4037 if (is_type_incomplete(prev_type)) {
4038 previous_declaration->type = type;
4042 /* pretend no storage class means extern for function
4043 * declarations (except if the previous declaration is neither
4044 * none nor extern) */
4045 if (is_type_function(type)) {
4046 if (prev_type->function.unspecified_parameters) {
4047 previous_declaration->type = type;
4051 switch (old_storage_class) {
4052 case STORAGE_CLASS_NONE:
4053 old_storage_class = STORAGE_CLASS_EXTERN;
4056 case STORAGE_CLASS_EXTERN:
4057 if (is_function_definition) {
4058 if (warning.missing_prototypes &&
4059 prev_type->function.unspecified_parameters &&
4060 !is_sym_main(symbol)) {
4061 warningf(&declaration->source_position,
4062 "no previous prototype for '%#T'",
4065 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4066 new_storage_class = STORAGE_CLASS_EXTERN;
4075 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4076 new_storage_class == STORAGE_CLASS_EXTERN) {
4077 warn_redundant_declaration:
4078 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4079 warningf(&declaration->source_position,
4080 "redundant declaration for '%Y' (declared %P)",
4081 symbol, &previous_declaration->source_position);
4083 } else if (current_function == NULL) {
4084 if (old_storage_class != STORAGE_CLASS_STATIC &&
4085 new_storage_class == STORAGE_CLASS_STATIC) {
4086 errorf(&declaration->source_position,
4087 "static declaration of '%Y' follows non-static declaration (declared %P)",
4088 symbol, &previous_declaration->source_position);
4089 } else if (old_storage_class != STORAGE_CLASS_EXTERN
4090 && !is_function_definition) {
4091 goto warn_redundant_declaration;
4092 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4093 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4094 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4096 } else if (old_storage_class == new_storage_class) {
4097 errorf(&declaration->source_position,
4098 "redeclaration of '%Y' (declared %P)",
4099 symbol, &previous_declaration->source_position);
4101 errorf(&declaration->source_position,
4102 "redeclaration of '%Y' with different linkage (declared %P)",
4103 symbol, &previous_declaration->source_position);
4107 if (declaration->is_inline)
4108 previous_declaration->is_inline = true;
4109 return previous_declaration;
4110 } else if (is_function_definition) {
4111 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4112 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4113 warningf(&declaration->source_position,
4114 "no previous prototype for '%#T'", orig_type, symbol);
4115 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4116 warningf(&declaration->source_position,
4117 "no previous declaration for '%#T'", orig_type,
4121 } else if (warning.missing_declarations &&
4122 scope == global_scope &&
4123 !is_type_function(type) && (
4124 declaration->storage_class == STORAGE_CLASS_NONE ||
4125 declaration->storage_class == STORAGE_CLASS_THREAD
4127 warningf(&declaration->source_position,
4128 "no previous declaration for '%#T'", orig_type, symbol);
4131 assert(declaration->parent_scope == NULL);
4132 assert(scope != NULL);
4134 declaration->parent_scope = scope;
4136 environment_push(declaration);
4137 return append_declaration(declaration);
4140 static declaration_t *record_declaration(declaration_t *declaration)
4142 return internal_record_declaration(declaration, false);
4145 static declaration_t *record_function_definition(declaration_t *declaration)
4147 return internal_record_declaration(declaration, true);
4150 static void parser_error_multiple_definition(declaration_t *declaration,
4151 const source_position_t *source_position)
4153 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4154 declaration->symbol, &declaration->source_position);
4157 static bool is_declaration_specifier(const token_t *token,
4158 bool only_specifiers_qualifiers)
4160 switch(token->type) {
4165 return is_typedef_symbol(token->v.symbol);
4167 case T___extension__:
4169 return !only_specifiers_qualifiers;
4176 static void parse_init_declarator_rest(declaration_t *declaration)
4180 type_t *orig_type = declaration->type;
4181 type_t *type = skip_typeref(orig_type);
4183 if (declaration->init.initializer != NULL) {
4184 parser_error_multiple_definition(declaration, HERE);
4187 bool must_be_constant = false;
4188 if (declaration->storage_class == STORAGE_CLASS_STATIC
4189 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4190 || declaration->parent_scope == global_scope) {
4191 must_be_constant = true;
4194 parse_initializer_env_t env;
4195 env.type = orig_type;
4196 env.must_be_constant = must_be_constant;
4197 env.declaration = declaration;
4199 initializer_t *initializer = parse_initializer(&env);
4201 if (env.type != orig_type) {
4202 orig_type = env.type;
4203 type = skip_typeref(orig_type);
4204 declaration->type = env.type;
4207 if (is_type_function(type)) {
4208 errorf(&declaration->source_position,
4209 "initializers not allowed for function types at declator '%Y' (type '%T')",
4210 declaration->symbol, orig_type);
4212 declaration->init.initializer = initializer;
4216 /* parse rest of a declaration without any declarator */
4217 static void parse_anonymous_declaration_rest(
4218 const declaration_specifiers_t *specifiers,
4219 parsed_declaration_func finished_declaration)
4223 declaration_t *const declaration = allocate_declaration_zero();
4224 declaration->type = specifiers->type;
4225 declaration->declared_storage_class = specifiers->declared_storage_class;
4226 declaration->source_position = specifiers->source_position;
4227 declaration->modifiers = specifiers->modifiers;
4229 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4230 warningf(&declaration->source_position,
4231 "useless storage class in empty declaration");
4233 declaration->storage_class = STORAGE_CLASS_NONE;
4235 type_t *type = declaration->type;
4236 switch (type->kind) {
4237 case TYPE_COMPOUND_STRUCT:
4238 case TYPE_COMPOUND_UNION: {
4239 if (type->compound.declaration->symbol == NULL) {
4240 warningf(&declaration->source_position,
4241 "unnamed struct/union that defines no instances");
4250 warningf(&declaration->source_position, "empty declaration");
4254 finished_declaration(declaration);
4257 static void parse_declaration_rest(declaration_t *ndeclaration,
4258 const declaration_specifiers_t *specifiers,
4259 parsed_declaration_func finished_declaration)
4261 add_anchor_token(';');
4262 add_anchor_token('=');
4263 add_anchor_token(',');
4265 declaration_t *declaration = finished_declaration(ndeclaration);
4267 type_t *orig_type = declaration->type;
4268 type_t *type = skip_typeref(orig_type);
4270 if (type->kind != TYPE_FUNCTION &&
4271 declaration->is_inline &&
4272 is_type_valid(type)) {
4273 warningf(&declaration->source_position,
4274 "variable '%Y' declared 'inline'\n", declaration->symbol);
4277 if (token.type == '=') {
4278 parse_init_declarator_rest(declaration);
4281 if (token.type != ',')
4285 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4290 rem_anchor_token(';');
4291 rem_anchor_token('=');
4292 rem_anchor_token(',');
4295 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4297 symbol_t *symbol = declaration->symbol;
4298 if (symbol == NULL) {
4299 errorf(HERE, "anonymous declaration not valid as function parameter");
4302 namespace_t namespc = (namespace_t) declaration->namespc;
4303 if (namespc != NAMESPACE_NORMAL) {
4304 return record_declaration(declaration);
4307 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4308 if (previous_declaration == NULL ||
4309 previous_declaration->parent_scope != scope) {
4310 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4315 if (previous_declaration->type == NULL) {
4316 previous_declaration->type = declaration->type;
4317 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4318 previous_declaration->storage_class = declaration->storage_class;
4319 previous_declaration->parent_scope = scope;
4320 return previous_declaration;
4322 return record_declaration(declaration);
4326 static void parse_declaration(parsed_declaration_func finished_declaration)
4328 declaration_specifiers_t specifiers;
4329 memset(&specifiers, 0, sizeof(specifiers));
4330 parse_declaration_specifiers(&specifiers);
4332 if (token.type == ';') {
4333 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4335 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4336 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4340 static type_t *get_default_promoted_type(type_t *orig_type)
4342 type_t *result = orig_type;
4344 type_t *type = skip_typeref(orig_type);
4345 if (is_type_integer(type)) {
4346 result = promote_integer(type);
4347 } else if (type == type_float) {
4348 result = type_double;
4354 static void parse_kr_declaration_list(declaration_t *declaration)
4356 type_t *type = skip_typeref(declaration->type);
4357 if (!is_type_function(type))
4360 if (!type->function.kr_style_parameters)
4363 /* push function parameters */
4364 int top = environment_top();
4365 scope_t *last_scope = scope;
4366 set_scope(&declaration->scope);
4368 declaration_t *parameter = declaration->scope.declarations;
4369 for ( ; parameter != NULL; parameter = parameter->next) {
4370 assert(parameter->parent_scope == NULL);
4371 parameter->parent_scope = scope;
4372 environment_push(parameter);
4375 /* parse declaration list */
4376 while (is_declaration_specifier(&token, false)) {
4377 parse_declaration(finished_kr_declaration);
4380 /* pop function parameters */
4381 assert(scope == &declaration->scope);
4382 set_scope(last_scope);
4383 environment_pop_to(top);
4385 /* update function type */
4386 type_t *new_type = duplicate_type(type);
4388 function_parameter_t *parameters = NULL;
4389 function_parameter_t *last_parameter = NULL;
4391 declaration_t *parameter_declaration = declaration->scope.declarations;
4392 for( ; parameter_declaration != NULL;
4393 parameter_declaration = parameter_declaration->next) {
4394 type_t *parameter_type = parameter_declaration->type;
4395 if (parameter_type == NULL) {
4397 errorf(HERE, "no type specified for function parameter '%Y'",
4398 parameter_declaration->symbol);
4400 if (warning.implicit_int) {
4401 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4402 parameter_declaration->symbol);
4404 parameter_type = type_int;
4405 parameter_declaration->type = parameter_type;
4409 semantic_parameter(parameter_declaration);
4410 parameter_type = parameter_declaration->type;
4413 * we need the default promoted types for the function type
4415 parameter_type = get_default_promoted_type(parameter_type);
4417 function_parameter_t *function_parameter
4418 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4419 memset(function_parameter, 0, sizeof(function_parameter[0]));
4421 function_parameter->type = parameter_type;
4422 if (last_parameter != NULL) {
4423 last_parameter->next = function_parameter;
4425 parameters = function_parameter;
4427 last_parameter = function_parameter;
4430 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4432 new_type->function.parameters = parameters;
4433 new_type->function.unspecified_parameters = true;
4435 type = typehash_insert(new_type);
4436 if (type != new_type) {
4437 obstack_free(type_obst, new_type);
4440 declaration->type = type;
4443 static bool first_err = true;
4446 * When called with first_err set, prints the name of the current function,
4449 static void print_in_function(void) {
4452 diagnosticf("%s: In function '%Y':\n",
4453 current_function->source_position.input_name,
4454 current_function->symbol);
4459 * Check if all labels are defined in the current function.
4460 * Check if all labels are used in the current function.
4462 static void check_labels(void)
4464 for (const goto_statement_t *goto_statement = goto_first;
4465 goto_statement != NULL;
4466 goto_statement = goto_statement->next) {
4467 declaration_t *label = goto_statement->label;
4470 if (label->source_position.input_name == NULL) {
4471 print_in_function();
4472 errorf(&goto_statement->base.source_position,
4473 "label '%Y' used but not defined", label->symbol);
4476 goto_first = goto_last = NULL;
4478 if (warning.unused_label) {
4479 for (const label_statement_t *label_statement = label_first;
4480 label_statement != NULL;
4481 label_statement = label_statement->next) {
4482 const declaration_t *label = label_statement->label;
4484 if (! label->used) {
4485 print_in_function();
4486 warningf(&label_statement->base.source_position,
4487 "label '%Y' defined but not used", label->symbol);
4491 label_first = label_last = NULL;
4495 * Check declarations of current_function for unused entities.
4497 static void check_declarations(void)
4499 if (warning.unused_parameter) {
4500 const scope_t *scope = ¤t_function->scope;
4502 const declaration_t *parameter = scope->declarations;
4503 for (; parameter != NULL; parameter = parameter->next) {
4504 if (! parameter->used) {
4505 print_in_function();
4506 warningf(¶meter->source_position,
4507 "unused parameter '%Y'", parameter->symbol);
4511 if (warning.unused_variable) {
4515 static void parse_external_declaration(void)
4517 /* function-definitions and declarations both start with declaration
4519 declaration_specifiers_t specifiers;
4520 memset(&specifiers, 0, sizeof(specifiers));
4522 add_anchor_token(';');
4523 parse_declaration_specifiers(&specifiers);
4524 rem_anchor_token(';');
4526 /* must be a declaration */
4527 if (token.type == ';') {
4528 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4532 add_anchor_token(',');
4533 add_anchor_token('=');
4534 rem_anchor_token(';');
4536 /* declarator is common to both function-definitions and declarations */
4537 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4539 rem_anchor_token(',');
4540 rem_anchor_token('=');
4541 rem_anchor_token(';');
4543 /* must be a declaration */
4544 if (token.type == ',' || token.type == '=' || token.type == ';') {
4545 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4549 /* must be a function definition */
4550 parse_kr_declaration_list(ndeclaration);
4552 if (token.type != '{') {
4553 parse_error_expected("while parsing function definition", '{', NULL);
4554 eat_until_matching_token(';');
4558 type_t *type = ndeclaration->type;
4560 /* note that we don't skip typerefs: the standard doesn't allow them here
4561 * (so we can't use is_type_function here) */
4562 if (type->kind != TYPE_FUNCTION) {
4563 if (is_type_valid(type)) {
4564 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4565 type, ndeclaration->symbol);
4571 /* § 6.7.5.3 (14) a function definition with () means no
4572 * parameters (and not unspecified parameters) */
4573 if (type->function.unspecified_parameters
4574 && type->function.parameters == NULL
4575 && !type->function.kr_style_parameters) {
4576 type_t *duplicate = duplicate_type(type);
4577 duplicate->function.unspecified_parameters = false;
4579 type = typehash_insert(duplicate);
4580 if (type != duplicate) {
4581 obstack_free(type_obst, duplicate);
4583 ndeclaration->type = type;
4586 declaration_t *const declaration = record_function_definition(ndeclaration);
4587 if (ndeclaration != declaration) {
4588 declaration->scope = ndeclaration->scope;
4590 type = skip_typeref(declaration->type);
4592 /* push function parameters and switch scope */
4593 int top = environment_top();
4594 scope_t *last_scope = scope;
4595 set_scope(&declaration->scope);
4597 declaration_t *parameter = declaration->scope.declarations;
4598 for( ; parameter != NULL; parameter = parameter->next) {
4599 if (parameter->parent_scope == &ndeclaration->scope) {
4600 parameter->parent_scope = scope;
4602 assert(parameter->parent_scope == NULL
4603 || parameter->parent_scope == scope);
4604 parameter->parent_scope = scope;
4605 if (parameter->symbol == NULL) {
4606 errorf(&ndeclaration->source_position, "parameter name omitted");
4609 environment_push(parameter);
4612 if (declaration->init.statement != NULL) {
4613 parser_error_multiple_definition(declaration, HERE);
4615 goto end_of_parse_external_declaration;
4617 /* parse function body */
4618 int label_stack_top = label_top();
4619 declaration_t *old_current_function = current_function;
4620 current_function = declaration;
4622 declaration->init.statement = parse_compound_statement(false);
4625 check_declarations();
4627 assert(current_function == declaration);
4628 current_function = old_current_function;
4629 label_pop_to(label_stack_top);
4632 end_of_parse_external_declaration:
4633 assert(scope == &declaration->scope);
4634 set_scope(last_scope);
4635 environment_pop_to(top);
4638 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4639 source_position_t *source_position)
4641 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4643 type->bitfield.base_type = base_type;
4644 type->bitfield.size = size;
4649 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4652 declaration_t *iter = compound_declaration->scope.declarations;
4653 for( ; iter != NULL; iter = iter->next) {
4654 if (iter->namespc != NAMESPACE_NORMAL)
4657 if (iter->symbol == NULL) {
4658 type_t *type = skip_typeref(iter->type);
4659 if (is_type_compound(type)) {
4660 declaration_t *result
4661 = find_compound_entry(type->compound.declaration, symbol);
4668 if (iter->symbol == symbol) {
4676 static void parse_compound_declarators(declaration_t *struct_declaration,
4677 const declaration_specifiers_t *specifiers)
4679 declaration_t *last_declaration = struct_declaration->scope.declarations;
4680 if (last_declaration != NULL) {
4681 while(last_declaration->next != NULL) {
4682 last_declaration = last_declaration->next;
4687 declaration_t *declaration;
4689 if (token.type == ':') {
4690 source_position_t source_position = *HERE;
4693 type_t *base_type = specifiers->type;
4694 expression_t *size = parse_constant_expression();
4696 if (!is_type_integer(skip_typeref(base_type))) {
4697 errorf(HERE, "bitfield base type '%T' is not an integer type",
4701 type_t *type = make_bitfield_type(base_type, size, &source_position);
4703 declaration = allocate_declaration_zero();
4704 declaration->namespc = NAMESPACE_NORMAL;
4705 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4706 declaration->storage_class = STORAGE_CLASS_NONE;
4707 declaration->source_position = source_position;
4708 declaration->modifiers = specifiers->modifiers;
4709 declaration->type = type;
4711 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4713 type_t *orig_type = declaration->type;
4714 type_t *type = skip_typeref(orig_type);
4716 if (token.type == ':') {
4717 source_position_t source_position = *HERE;
4719 expression_t *size = parse_constant_expression();
4721 if (!is_type_integer(type)) {
4722 errorf(HERE, "bitfield base type '%T' is not an "
4723 "integer type", orig_type);
4726 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4727 declaration->type = bitfield_type;
4729 /* TODO we ignore arrays for now... what is missing is a check
4730 * that they're at the end of the struct */
4731 if (is_type_incomplete(type) && !is_type_array(type)) {
4733 "compound member '%Y' has incomplete type '%T'",
4734 declaration->symbol, orig_type);
4735 } else if (is_type_function(type)) {
4736 errorf(HERE, "compound member '%Y' must not have function "
4737 "type '%T'", declaration->symbol, orig_type);
4742 /* make sure we don't define a symbol multiple times */
4743 symbol_t *symbol = declaration->symbol;
4744 if (symbol != NULL) {
4745 declaration_t *prev_decl
4746 = find_compound_entry(struct_declaration, symbol);
4748 if (prev_decl != NULL) {
4749 assert(prev_decl->symbol == symbol);
4750 errorf(&declaration->source_position,
4751 "multiple declarations of symbol '%Y' (declared %P)",
4752 symbol, &prev_decl->source_position);
4756 /* append declaration */
4757 if (last_declaration != NULL) {
4758 last_declaration->next = declaration;
4760 struct_declaration->scope.declarations = declaration;
4762 last_declaration = declaration;
4764 if (token.type != ',')
4774 static void parse_compound_type_entries(declaration_t *compound_declaration)
4777 add_anchor_token('}');
4779 while(token.type != '}' && token.type != T_EOF) {
4780 declaration_specifiers_t specifiers;
4781 memset(&specifiers, 0, sizeof(specifiers));
4782 parse_declaration_specifiers(&specifiers);
4784 parse_compound_declarators(compound_declaration, &specifiers);
4786 rem_anchor_token('}');
4788 if (token.type == T_EOF) {
4789 errorf(HERE, "EOF while parsing struct");
4794 static type_t *parse_typename(void)
4796 declaration_specifiers_t specifiers;
4797 memset(&specifiers, 0, sizeof(specifiers));
4798 parse_declaration_specifiers(&specifiers);
4799 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4800 /* TODO: improve error message, user does probably not know what a
4801 * storage class is...
4803 errorf(HERE, "typename may not have a storage class");
4806 type_t *result = parse_abstract_declarator(specifiers.type);
4814 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4815 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4816 expression_t *left);
4818 typedef struct expression_parser_function_t expression_parser_function_t;
4819 struct expression_parser_function_t {
4820 unsigned precedence;
4821 parse_expression_function parser;
4822 unsigned infix_precedence;
4823 parse_expression_infix_function infix_parser;
4826 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4829 * Prints an error message if an expression was expected but not read
4831 static expression_t *expected_expression_error(void)
4833 /* skip the error message if the error token was read */
4834 if (token.type != T_ERROR) {
4835 errorf(HERE, "expected expression, got token '%K'", &token);
4839 return create_invalid_expression();
4843 * Parse a string constant.
4845 static expression_t *parse_string_const(void)
4848 if (token.type == T_STRING_LITERAL) {
4849 string_t res = token.v.string;
4851 while (token.type == T_STRING_LITERAL) {
4852 res = concat_strings(&res, &token.v.string);
4855 if (token.type != T_WIDE_STRING_LITERAL) {
4856 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4857 /* note: that we use type_char_ptr here, which is already the
4858 * automatic converted type. revert_automatic_type_conversion
4859 * will construct the array type */
4860 cnst->base.type = type_char_ptr;
4861 cnst->string.value = res;
4865 wres = concat_string_wide_string(&res, &token.v.wide_string);
4867 wres = token.v.wide_string;
4872 switch (token.type) {
4873 case T_WIDE_STRING_LITERAL:
4874 wres = concat_wide_strings(&wres, &token.v.wide_string);
4877 case T_STRING_LITERAL:
4878 wres = concat_wide_string_string(&wres, &token.v.string);
4882 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4883 cnst->base.type = type_wchar_t_ptr;
4884 cnst->wide_string.value = wres;
4893 * Parse an integer constant.
4895 static expression_t *parse_int_const(void)
4897 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4898 cnst->base.source_position = *HERE;
4899 cnst->base.type = token.datatype;
4900 cnst->conste.v.int_value = token.v.intvalue;
4908 * Parse a character constant.
4910 static expression_t *parse_character_constant(void)
4912 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4914 cnst->base.source_position = *HERE;
4915 cnst->base.type = token.datatype;
4916 cnst->conste.v.character = token.v.string;
4918 if (cnst->conste.v.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 wide character constant.
4934 static expression_t *parse_wide_character_constant(void)
4936 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4938 cnst->base.source_position = *HERE;
4939 cnst->base.type = token.datatype;
4940 cnst->conste.v.wide_character = token.v.wide_string;
4942 if (cnst->conste.v.wide_character.size != 1) {
4943 if (warning.multichar && (c_mode & _GNUC)) {
4945 warningf(HERE, "multi-character character constant");
4947 errorf(HERE, "more than 1 characters in character constant");
4956 * Parse a float constant.
4958 static expression_t *parse_float_const(void)
4960 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4961 cnst->base.type = token.datatype;
4962 cnst->conste.v.float_value = token.v.floatvalue;
4969 static declaration_t *create_implicit_function(symbol_t *symbol,
4970 const source_position_t *source_position)
4972 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4973 ntype->function.return_type = type_int;
4974 ntype->function.unspecified_parameters = true;
4976 type_t *type = typehash_insert(ntype);
4977 if (type != ntype) {
4981 declaration_t *const declaration = allocate_declaration_zero();
4982 declaration->storage_class = STORAGE_CLASS_EXTERN;
4983 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4984 declaration->type = type;
4985 declaration->symbol = symbol;
4986 declaration->source_position = *source_position;
4988 bool strict_prototypes_old = warning.strict_prototypes;
4989 warning.strict_prototypes = false;
4990 record_declaration(declaration);
4991 warning.strict_prototypes = strict_prototypes_old;
4997 * Creates a return_type (func)(argument_type) function type if not
5000 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5001 type_t *argument_type2)
5003 function_parameter_t *parameter2
5004 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5005 memset(parameter2, 0, sizeof(parameter2[0]));
5006 parameter2->type = argument_type2;
5008 function_parameter_t *parameter1
5009 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5010 memset(parameter1, 0, sizeof(parameter1[0]));
5011 parameter1->type = argument_type1;
5012 parameter1->next = parameter2;
5014 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5015 type->function.return_type = return_type;
5016 type->function.parameters = parameter1;
5018 type_t *result = typehash_insert(type);
5019 if (result != type) {
5027 * Creates a return_type (func)(argument_type) function type if not
5030 * @param return_type the return type
5031 * @param argument_type the argument type
5033 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5035 function_parameter_t *parameter
5036 = obstack_alloc(type_obst, sizeof(parameter[0]));
5037 memset(parameter, 0, sizeof(parameter[0]));
5038 parameter->type = argument_type;
5040 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5041 type->function.return_type = return_type;
5042 type->function.parameters = parameter;
5044 type_t *result = typehash_insert(type);
5045 if (result != type) {
5052 static type_t *make_function_0_type(type_t *return_type)
5054 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5055 type->function.return_type = return_type;
5056 type->function.parameters = NULL;
5058 type_t *result = typehash_insert(type);
5059 if (result != type) {
5067 * Creates a function type for some function like builtins.
5069 * @param symbol the symbol describing the builtin
5071 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5073 switch(symbol->ID) {
5074 case T___builtin_alloca:
5075 return make_function_1_type(type_void_ptr, type_size_t);
5076 case T___builtin_huge_val:
5077 return make_function_0_type(type_double);
5078 case T___builtin_nan:
5079 return make_function_1_type(type_double, type_char_ptr);
5080 case T___builtin_nanf:
5081 return make_function_1_type(type_float, type_char_ptr);
5082 case T___builtin_nand:
5083 return make_function_1_type(type_long_double, type_char_ptr);
5084 case T___builtin_va_end:
5085 return make_function_1_type(type_void, type_valist);
5086 case T___builtin_expect:
5087 return make_function_2_type(type_long, type_long, type_long);
5089 internal_errorf(HERE, "not implemented builtin symbol found");
5094 * Performs automatic type cast as described in § 6.3.2.1.
5096 * @param orig_type the original type
5098 static type_t *automatic_type_conversion(type_t *orig_type)
5100 type_t *type = skip_typeref(orig_type);
5101 if (is_type_array(type)) {
5102 array_type_t *array_type = &type->array;
5103 type_t *element_type = array_type->element_type;
5104 unsigned qualifiers = array_type->base.qualifiers;
5106 return make_pointer_type(element_type, qualifiers);
5109 if (is_type_function(type)) {
5110 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5117 * reverts the automatic casts of array to pointer types and function
5118 * to function-pointer types as defined § 6.3.2.1
5120 type_t *revert_automatic_type_conversion(const expression_t *expression)
5122 switch (expression->kind) {
5123 case EXPR_REFERENCE: return expression->reference.declaration->type;
5124 case EXPR_SELECT: return expression->select.compound_entry->type;
5126 case EXPR_UNARY_DEREFERENCE: {
5127 const expression_t *const value = expression->unary.value;
5128 type_t *const type = skip_typeref(value->base.type);
5129 assert(is_type_pointer(type));
5130 return type->pointer.points_to;
5133 case EXPR_BUILTIN_SYMBOL:
5134 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5136 case EXPR_ARRAY_ACCESS: {
5137 const expression_t *array_ref = expression->array_access.array_ref;
5138 type_t *type_left = skip_typeref(array_ref->base.type);
5139 if (!is_type_valid(type_left))
5141 assert(is_type_pointer(type_left));
5142 return type_left->pointer.points_to;
5145 case EXPR_STRING_LITERAL: {
5146 size_t size = expression->string.value.size;
5147 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5150 case EXPR_WIDE_STRING_LITERAL: {
5151 size_t size = expression->wide_string.value.size;
5152 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5155 case EXPR_COMPOUND_LITERAL:
5156 return expression->compound_literal.type;
5161 return expression->base.type;
5164 static expression_t *parse_reference(void)
5166 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5168 reference_expression_t *ref = &expression->reference;
5169 symbol_t *const symbol = token.v.symbol;
5171 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5173 source_position_t source_position = token.source_position;
5176 if (declaration == NULL) {
5177 if (! strict_mode && token.type == '(') {
5178 /* an implicitly defined function */
5179 if (warning.implicit_function_declaration) {
5180 warningf(HERE, "implicit declaration of function '%Y'",
5184 declaration = create_implicit_function(symbol,
5187 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5188 return create_invalid_expression();
5192 type_t *type = declaration->type;
5194 /* we always do the auto-type conversions; the & and sizeof parser contains
5195 * code to revert this! */
5196 type = automatic_type_conversion(type);
5198 ref->declaration = declaration;
5199 ref->base.type = type;
5201 /* this declaration is used */
5202 declaration->used = true;
5204 /* check for deprecated functions */
5205 if (declaration->deprecated != 0) {
5206 const char *prefix = "";
5207 if (is_type_function(declaration->type))
5208 prefix = "function ";
5210 if (declaration->deprecated_string != NULL) {
5211 warningf(&source_position,
5212 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5213 declaration->deprecated_string);
5215 warningf(&source_position,
5216 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5223 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5227 /* TODO check if explicit cast is allowed and issue warnings/errors */
5230 static expression_t *parse_compound_literal(type_t *type)
5232 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5234 parse_initializer_env_t env;
5236 env.declaration = NULL;
5237 env.must_be_constant = false;
5238 initializer_t *initializer = parse_initializer(&env);
5241 expression->compound_literal.initializer = initializer;
5242 expression->compound_literal.type = type;
5243 expression->base.type = automatic_type_conversion(type);
5249 * Parse a cast expression.
5251 static expression_t *parse_cast(void)
5253 source_position_t source_position = token.source_position;
5255 type_t *type = parse_typename();
5257 /* matching add_anchor_token() is at call site */
5258 rem_anchor_token(')');
5261 if (token.type == '{') {
5262 return parse_compound_literal(type);
5265 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5266 cast->base.source_position = source_position;
5268 expression_t *value = parse_sub_expression(20);
5270 check_cast_allowed(value, type);
5272 cast->base.type = type;
5273 cast->unary.value = value;
5277 return create_invalid_expression();
5281 * Parse a statement expression.
5283 static expression_t *parse_statement_expression(void)
5285 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5287 statement_t *statement = parse_compound_statement(true);
5288 expression->statement.statement = statement;
5289 expression->base.source_position = statement->base.source_position;
5291 /* find last statement and use its type */
5292 type_t *type = type_void;
5293 const statement_t *stmt = statement->compound.statements;
5295 while (stmt->base.next != NULL)
5296 stmt = stmt->base.next;
5298 if (stmt->kind == STATEMENT_EXPRESSION) {
5299 type = stmt->expression.expression->base.type;
5302 warningf(&expression->base.source_position, "empty statement expression ({})");
5304 expression->base.type = type;
5310 return create_invalid_expression();
5314 * Parse a braced expression.
5316 static expression_t *parse_brace_expression(void)
5319 add_anchor_token(')');
5321 switch(token.type) {
5323 /* gcc extension: a statement expression */
5324 return parse_statement_expression();
5328 return parse_cast();
5330 if (is_typedef_symbol(token.v.symbol)) {
5331 return parse_cast();
5335 expression_t *result = parse_expression();
5336 rem_anchor_token(')');
5341 return create_invalid_expression();
5344 static expression_t *parse_function_keyword(void)
5349 if (current_function == NULL) {
5350 errorf(HERE, "'__func__' used outside of a function");
5353 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5354 expression->base.type = type_char_ptr;
5355 expression->funcname.kind = FUNCNAME_FUNCTION;
5360 static expression_t *parse_pretty_function_keyword(void)
5362 eat(T___PRETTY_FUNCTION__);
5364 if (current_function == NULL) {
5365 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5368 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5369 expression->base.type = type_char_ptr;
5370 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5375 static expression_t *parse_funcsig_keyword(void)
5379 if (current_function == NULL) {
5380 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5383 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5384 expression->base.type = type_char_ptr;
5385 expression->funcname.kind = FUNCNAME_FUNCSIG;
5390 static expression_t *parse_funcdname_keyword(void)
5392 eat(T___FUNCDNAME__);
5394 if (current_function == NULL) {
5395 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5398 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5399 expression->base.type = type_char_ptr;
5400 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5405 static designator_t *parse_designator(void)
5407 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5408 result->source_position = *HERE;
5410 if (token.type != T_IDENTIFIER) {
5411 parse_error_expected("while parsing member designator",
5412 T_IDENTIFIER, NULL);
5415 result->symbol = token.v.symbol;
5418 designator_t *last_designator = result;
5420 if (token.type == '.') {
5422 if (token.type != T_IDENTIFIER) {
5423 parse_error_expected("while parsing member designator",
5424 T_IDENTIFIER, NULL);
5427 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5428 designator->source_position = *HERE;
5429 designator->symbol = token.v.symbol;
5432 last_designator->next = designator;
5433 last_designator = designator;
5436 if (token.type == '[') {
5438 add_anchor_token(']');
5439 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5440 designator->source_position = *HERE;
5441 designator->array_index = parse_expression();
5442 rem_anchor_token(']');
5444 if (designator->array_index == NULL) {
5448 last_designator->next = designator;
5449 last_designator = designator;
5461 * Parse the __builtin_offsetof() expression.
5463 static expression_t *parse_offsetof(void)
5465 eat(T___builtin_offsetof);
5467 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5468 expression->base.type = type_size_t;
5471 add_anchor_token(',');
5472 type_t *type = parse_typename();
5473 rem_anchor_token(',');
5475 add_anchor_token(')');
5476 designator_t *designator = parse_designator();
5477 rem_anchor_token(')');
5480 expression->offsetofe.type = type;
5481 expression->offsetofe.designator = designator;
5484 memset(&path, 0, sizeof(path));
5485 path.top_type = type;
5486 path.path = NEW_ARR_F(type_path_entry_t, 0);
5488 descend_into_subtype(&path);
5490 if (!walk_designator(&path, designator, true)) {
5491 return create_invalid_expression();
5494 DEL_ARR_F(path.path);
5498 return create_invalid_expression();
5502 * Parses a _builtin_va_start() expression.
5504 static expression_t *parse_va_start(void)
5506 eat(T___builtin_va_start);
5508 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5511 add_anchor_token(',');
5512 expression->va_starte.ap = parse_assignment_expression();
5513 rem_anchor_token(',');
5515 expression_t *const expr = parse_assignment_expression();
5516 if (expr->kind == EXPR_REFERENCE) {
5517 declaration_t *const decl = expr->reference.declaration;
5519 return create_invalid_expression();
5520 if (decl->parent_scope == ¤t_function->scope &&
5521 decl->next == NULL) {
5522 expression->va_starte.parameter = decl;
5527 errorf(&expr->base.source_position,
5528 "second argument of 'va_start' must be last parameter of the current function");
5530 return create_invalid_expression();
5534 * Parses a _builtin_va_arg() expression.
5536 static expression_t *parse_va_arg(void)
5538 eat(T___builtin_va_arg);
5540 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5543 expression->va_arge.ap = parse_assignment_expression();
5545 expression->base.type = parse_typename();
5550 return create_invalid_expression();
5553 static expression_t *parse_builtin_symbol(void)
5555 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5557 symbol_t *symbol = token.v.symbol;
5559 expression->builtin_symbol.symbol = symbol;
5562 type_t *type = get_builtin_symbol_type(symbol);
5563 type = automatic_type_conversion(type);
5565 expression->base.type = type;
5570 * Parses a __builtin_constant() expression.
5572 static expression_t *parse_builtin_constant(void)
5574 eat(T___builtin_constant_p);
5576 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5579 add_anchor_token(')');
5580 expression->builtin_constant.value = parse_assignment_expression();
5581 rem_anchor_token(')');
5583 expression->base.type = type_int;
5587 return create_invalid_expression();
5591 * Parses a __builtin_prefetch() expression.
5593 static expression_t *parse_builtin_prefetch(void)
5595 eat(T___builtin_prefetch);
5597 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5600 add_anchor_token(')');
5601 expression->builtin_prefetch.adr = parse_assignment_expression();
5602 if (token.type == ',') {
5604 expression->builtin_prefetch.rw = parse_assignment_expression();
5606 if (token.type == ',') {
5608 expression->builtin_prefetch.locality = parse_assignment_expression();
5610 rem_anchor_token(')');
5612 expression->base.type = type_void;
5616 return create_invalid_expression();
5620 * Parses a __builtin_is_*() compare expression.
5622 static expression_t *parse_compare_builtin(void)
5624 expression_t *expression;
5626 switch(token.type) {
5627 case T___builtin_isgreater:
5628 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5630 case T___builtin_isgreaterequal:
5631 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5633 case T___builtin_isless:
5634 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5636 case T___builtin_islessequal:
5637 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5639 case T___builtin_islessgreater:
5640 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5642 case T___builtin_isunordered:
5643 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5646 internal_errorf(HERE, "invalid compare builtin found");
5649 expression->base.source_position = *HERE;
5653 expression->binary.left = parse_assignment_expression();
5655 expression->binary.right = parse_assignment_expression();
5658 type_t *const orig_type_left = expression->binary.left->base.type;
5659 type_t *const orig_type_right = expression->binary.right->base.type;
5661 type_t *const type_left = skip_typeref(orig_type_left);
5662 type_t *const type_right = skip_typeref(orig_type_right);
5663 if (!is_type_float(type_left) && !is_type_float(type_right)) {
5664 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5665 type_error_incompatible("invalid operands in comparison",
5666 &expression->base.source_position, orig_type_left, orig_type_right);
5669 semantic_comparison(&expression->binary);
5674 return create_invalid_expression();
5679 * Parses a __builtin_expect() expression.
5681 static expression_t *parse_builtin_expect(void)
5683 eat(T___builtin_expect);
5685 expression_t *expression
5686 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5689 expression->binary.left = parse_assignment_expression();
5691 expression->binary.right = parse_constant_expression();
5694 expression->base.type = expression->binary.left->base.type;
5698 return create_invalid_expression();
5703 * Parses a MS assume() expression.
5705 static expression_t *parse_assume(void) {
5708 expression_t *expression
5709 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5712 add_anchor_token(')');
5713 expression->unary.value = parse_assignment_expression();
5714 rem_anchor_token(')');
5717 expression->base.type = type_void;
5720 return create_invalid_expression();
5724 * Parse a microsoft __noop expression.
5726 static expression_t *parse_noop_expression(void) {
5727 source_position_t source_position = *HERE;
5730 if (token.type == '(') {
5731 /* parse arguments */
5733 add_anchor_token(')');
5734 add_anchor_token(',');
5736 if (token.type != ')') {
5738 (void)parse_assignment_expression();
5739 if (token.type != ',')
5745 rem_anchor_token(',');
5746 rem_anchor_token(')');
5749 /* the result is a (int)0 */
5750 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5751 cnst->base.source_position = source_position;
5752 cnst->base.type = type_int;
5753 cnst->conste.v.int_value = 0;
5754 cnst->conste.is_ms_noop = true;
5759 return create_invalid_expression();
5763 * Parses a primary expression.
5765 static expression_t *parse_primary_expression(void)
5767 switch (token.type) {
5768 case T_INTEGER: return parse_int_const();
5769 case T_CHARACTER_CONSTANT: return parse_character_constant();
5770 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5771 case T_FLOATINGPOINT: return parse_float_const();
5772 case T_STRING_LITERAL:
5773 case T_WIDE_STRING_LITERAL: return parse_string_const();
5774 case T_IDENTIFIER: return parse_reference();
5775 case T___FUNCTION__:
5776 case T___func__: return parse_function_keyword();
5777 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5778 case T___FUNCSIG__: return parse_funcsig_keyword();
5779 case T___FUNCDNAME__: return parse_funcdname_keyword();
5780 case T___builtin_offsetof: return parse_offsetof();
5781 case T___builtin_va_start: return parse_va_start();
5782 case T___builtin_va_arg: return parse_va_arg();
5783 case T___builtin_expect:
5784 case T___builtin_alloca:
5785 case T___builtin_nan:
5786 case T___builtin_nand:
5787 case T___builtin_nanf:
5788 case T___builtin_huge_val:
5789 case T___builtin_va_end: return parse_builtin_symbol();
5790 case T___builtin_isgreater:
5791 case T___builtin_isgreaterequal:
5792 case T___builtin_isless:
5793 case T___builtin_islessequal:
5794 case T___builtin_islessgreater:
5795 case T___builtin_isunordered: return parse_compare_builtin();
5796 case T___builtin_constant_p: return parse_builtin_constant();
5797 case T___builtin_prefetch: return parse_builtin_prefetch();
5798 case T__assume: return parse_assume();
5800 case '(': return parse_brace_expression();
5801 case T___noop: return parse_noop_expression();
5804 errorf(HERE, "unexpected token %K, expected an expression", &token);
5805 return create_invalid_expression();
5809 * Check if the expression has the character type and issue a warning then.
5811 static void check_for_char_index_type(const expression_t *expression) {
5812 type_t *const type = expression->base.type;
5813 const type_t *const base_type = skip_typeref(type);
5815 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5816 warning.char_subscripts) {
5817 warningf(&expression->base.source_position,
5818 "array subscript has type '%T'", type);
5822 static expression_t *parse_array_expression(unsigned precedence,
5828 add_anchor_token(']');
5830 expression_t *inside = parse_expression();
5832 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5834 array_access_expression_t *array_access = &expression->array_access;
5836 type_t *const orig_type_left = left->base.type;
5837 type_t *const orig_type_inside = inside->base.type;
5839 type_t *const type_left = skip_typeref(orig_type_left);
5840 type_t *const type_inside = skip_typeref(orig_type_inside);
5842 type_t *return_type;
5843 if (is_type_pointer(type_left)) {
5844 return_type = type_left->pointer.points_to;
5845 array_access->array_ref = left;
5846 array_access->index = inside;
5847 check_for_char_index_type(inside);
5848 } else if (is_type_pointer(type_inside)) {
5849 return_type = type_inside->pointer.points_to;
5850 array_access->array_ref = inside;
5851 array_access->index = left;
5852 array_access->flipped = true;
5853 check_for_char_index_type(left);
5855 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5857 "array access on object with non-pointer types '%T', '%T'",
5858 orig_type_left, orig_type_inside);
5860 return_type = type_error_type;
5861 array_access->array_ref = create_invalid_expression();
5864 rem_anchor_token(']');
5865 if (token.type != ']') {
5866 parse_error_expected("Problem while parsing array access", ']', NULL);
5871 return_type = automatic_type_conversion(return_type);
5872 expression->base.type = return_type;
5877 static expression_t *parse_typeprop(expression_kind_t const kind,
5878 source_position_t const pos,
5879 unsigned const precedence)
5881 expression_t *tp_expression = allocate_expression_zero(kind);
5882 tp_expression->base.type = type_size_t;
5883 tp_expression->base.source_position = pos;
5885 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5887 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5889 add_anchor_token(')');
5890 type_t* const orig_type = parse_typename();
5891 tp_expression->typeprop.type = orig_type;
5893 type_t const* const type = skip_typeref(orig_type);
5894 char const* const wrong_type =
5895 is_type_incomplete(type) ? "incomplete" :
5896 type->kind == TYPE_FUNCTION ? "function designator" :
5897 type->kind == TYPE_BITFIELD ? "bitfield" :
5899 if (wrong_type != NULL) {
5900 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5901 what, wrong_type, type);
5904 rem_anchor_token(')');
5907 expression_t *expression = parse_sub_expression(precedence);
5909 type_t* const orig_type = revert_automatic_type_conversion(expression);
5910 expression->base.type = orig_type;
5912 type_t const* const type = skip_typeref(orig_type);
5913 char const* const wrong_type =
5914 is_type_incomplete(type) ? "incomplete" :
5915 type->kind == TYPE_FUNCTION ? "function designator" :
5916 type->kind == TYPE_BITFIELD ? "bitfield" :
5918 if (wrong_type != NULL) {
5919 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5922 tp_expression->typeprop.type = expression->base.type;
5923 tp_expression->typeprop.tp_expression = expression;
5926 return tp_expression;
5928 return create_invalid_expression();
5931 static expression_t *parse_sizeof(unsigned precedence)
5933 source_position_t pos = *HERE;
5935 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5938 static expression_t *parse_alignof(unsigned precedence)
5940 source_position_t pos = *HERE;
5942 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5945 static expression_t *parse_select_expression(unsigned precedence,
5946 expression_t *compound)
5949 assert(token.type == '.' || token.type == T_MINUSGREATER);
5951 bool is_pointer = (token.type == T_MINUSGREATER);
5954 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5955 select->select.compound = compound;
5957 if (token.type != T_IDENTIFIER) {
5958 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5961 symbol_t *symbol = token.v.symbol;
5962 select->select.symbol = symbol;
5965 type_t *const orig_type = compound->base.type;
5966 type_t *const type = skip_typeref(orig_type);
5968 type_t *type_left = type;
5970 if (!is_type_pointer(type)) {
5971 if (is_type_valid(type)) {
5972 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5974 return create_invalid_expression();
5976 type_left = type->pointer.points_to;
5978 type_left = skip_typeref(type_left);
5980 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5981 type_left->kind != TYPE_COMPOUND_UNION) {
5982 if (is_type_valid(type_left)) {
5983 errorf(HERE, "request for member '%Y' in something not a struct or "
5984 "union, but '%T'", symbol, type_left);
5986 return create_invalid_expression();
5989 declaration_t *const declaration = type_left->compound.declaration;
5991 if (!declaration->init.complete) {
5992 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5994 return create_invalid_expression();
5997 declaration_t *iter = find_compound_entry(declaration, symbol);
5999 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6000 return create_invalid_expression();
6003 /* we always do the auto-type conversions; the & and sizeof parser contains
6004 * code to revert this! */
6005 type_t *expression_type = automatic_type_conversion(iter->type);
6007 select->select.compound_entry = iter;
6008 select->base.type = expression_type;
6010 type_t *skipped = skip_typeref(iter->type);
6011 if (skipped->kind == TYPE_BITFIELD) {
6012 select->base.type = skipped->bitfield.base_type;
6018 static void check_call_argument(const function_parameter_t *parameter,
6019 call_argument_t *argument)
6021 type_t *expected_type = parameter->type;
6022 type_t *expected_type_skip = skip_typeref(expected_type);
6023 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6024 expression_t *arg_expr = argument->expression;
6026 /* handle transparent union gnu extension */
6027 if (is_type_union(expected_type_skip)
6028 && (expected_type_skip->base.modifiers
6029 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6030 declaration_t *union_decl = expected_type_skip->compound.declaration;
6032 declaration_t *declaration = union_decl->scope.declarations;
6033 type_t *best_type = NULL;
6034 for ( ; declaration != NULL; declaration = declaration->next) {
6035 type_t *decl_type = declaration->type;
6036 error = semantic_assign(decl_type, arg_expr);
6037 if (error == ASSIGN_ERROR_INCOMPATIBLE
6038 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6041 if (error == ASSIGN_SUCCESS) {
6042 best_type = decl_type;
6043 } else if (best_type == NULL) {
6044 best_type = decl_type;
6048 if (best_type != NULL) {
6049 expected_type = best_type;
6053 error = semantic_assign(expected_type, arg_expr);
6054 argument->expression = create_implicit_cast(argument->expression,
6057 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6058 report_assign_error(error, expected_type, arg_expr, "function call",
6059 &arg_expr->base.source_position);
6063 * Parse a call expression, ie. expression '( ... )'.
6065 * @param expression the function address
6067 static expression_t *parse_call_expression(unsigned precedence,
6068 expression_t *expression)
6071 expression_t *result = allocate_expression_zero(EXPR_CALL);
6072 result->base.source_position = expression->base.source_position;
6074 call_expression_t *call = &result->call;
6075 call->function = expression;
6077 type_t *const orig_type = expression->base.type;
6078 type_t *const type = skip_typeref(orig_type);
6080 function_type_t *function_type = NULL;
6081 if (is_type_pointer(type)) {
6082 type_t *const to_type = skip_typeref(type->pointer.points_to);
6084 if (is_type_function(to_type)) {
6085 function_type = &to_type->function;
6086 call->base.type = function_type->return_type;
6090 if (function_type == NULL && is_type_valid(type)) {
6091 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6094 /* parse arguments */
6096 add_anchor_token(')');
6097 add_anchor_token(',');
6099 if (token.type != ')') {
6100 call_argument_t *last_argument = NULL;
6103 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6105 argument->expression = parse_assignment_expression();
6106 if (last_argument == NULL) {
6107 call->arguments = argument;
6109 last_argument->next = argument;
6111 last_argument = argument;
6113 if (token.type != ',')
6118 rem_anchor_token(',');
6119 rem_anchor_token(')');
6122 if (function_type == NULL)
6125 function_parameter_t *parameter = function_type->parameters;
6126 call_argument_t *argument = call->arguments;
6127 if (!function_type->unspecified_parameters) {
6128 for( ; parameter != NULL && argument != NULL;
6129 parameter = parameter->next, argument = argument->next) {
6130 check_call_argument(parameter, argument);
6133 if (parameter != NULL) {
6134 errorf(HERE, "too few arguments to function '%E'", expression);
6135 } else if (argument != NULL && !function_type->variadic) {
6136 errorf(HERE, "too many arguments to function '%E'", expression);
6140 /* do default promotion */
6141 for( ; argument != NULL; argument = argument->next) {
6142 type_t *type = argument->expression->base.type;
6144 type = get_default_promoted_type(type);
6146 argument->expression
6147 = create_implicit_cast(argument->expression, type);
6150 check_format(&result->call);
6154 return create_invalid_expression();
6157 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6159 static bool same_compound_type(const type_t *type1, const type_t *type2)
6162 is_type_compound(type1) &&
6163 type1->kind == type2->kind &&
6164 type1->compound.declaration == type2->compound.declaration;
6168 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6170 * @param expression the conditional expression
6172 static expression_t *parse_conditional_expression(unsigned precedence,
6173 expression_t *expression)
6176 add_anchor_token(':');
6178 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6180 conditional_expression_t *conditional = &result->conditional;
6181 conditional->condition = expression;
6184 type_t *const condition_type_orig = expression->base.type;
6185 type_t *const condition_type = skip_typeref(condition_type_orig);
6186 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6187 type_error("expected a scalar type in conditional condition",
6188 &expression->base.source_position, condition_type_orig);
6191 expression_t *true_expression = parse_expression();
6192 rem_anchor_token(':');
6194 expression_t *false_expression = parse_sub_expression(precedence);
6196 type_t *const orig_true_type = true_expression->base.type;
6197 type_t *const orig_false_type = false_expression->base.type;
6198 type_t *const true_type = skip_typeref(orig_true_type);
6199 type_t *const false_type = skip_typeref(orig_false_type);
6202 type_t *result_type;
6203 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6204 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6205 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6206 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6207 warningf(&expression->base.source_position,
6208 "ISO C forbids conditional expression with only one void side");
6210 result_type = type_void;
6211 } else if (is_type_arithmetic(true_type)
6212 && is_type_arithmetic(false_type)) {
6213 result_type = semantic_arithmetic(true_type, false_type);
6215 true_expression = create_implicit_cast(true_expression, result_type);
6216 false_expression = create_implicit_cast(false_expression, result_type);
6218 conditional->true_expression = true_expression;
6219 conditional->false_expression = false_expression;
6220 conditional->base.type = result_type;
6221 } else if (same_compound_type(true_type, false_type)) {
6222 /* just take 1 of the 2 types */
6223 result_type = true_type;
6224 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6225 type_t *pointer_type;
6227 expression_t *other_expression;
6228 if (is_type_pointer(true_type) &&
6229 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6230 pointer_type = true_type;
6231 other_type = false_type;
6232 other_expression = false_expression;
6234 pointer_type = false_type;
6235 other_type = true_type;
6236 other_expression = true_expression;
6239 if (is_null_pointer_constant(other_expression)) {
6240 result_type = pointer_type;
6241 } else if (is_type_pointer(other_type)) {
6242 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6243 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6246 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6247 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6249 } else if (types_compatible(get_unqualified_type(to1),
6250 get_unqualified_type(to2))) {
6253 warningf(&expression->base.source_position,
6254 "pointer types '%T' and '%T' in conditional expression are incompatible",
6255 true_type, false_type);
6259 type_t *const copy = duplicate_type(to);
6260 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6262 type_t *const type = typehash_insert(copy);
6266 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6267 } else if (is_type_integer(other_type)) {
6268 warningf(&expression->base.source_position,
6269 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6270 result_type = pointer_type;
6272 type_error_incompatible("while parsing conditional",
6273 &expression->base.source_position, true_type, false_type);
6274 result_type = type_error_type;
6277 /* TODO: one pointer to void*, other some pointer */
6279 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6280 type_error_incompatible("while parsing conditional",
6281 &expression->base.source_position, true_type,
6284 result_type = type_error_type;
6287 conditional->true_expression
6288 = create_implicit_cast(true_expression, result_type);
6289 conditional->false_expression
6290 = create_implicit_cast(false_expression, result_type);
6291 conditional->base.type = result_type;
6294 return create_invalid_expression();
6298 * Parse an extension expression.
6300 static expression_t *parse_extension(unsigned precedence)
6302 eat(T___extension__);
6304 /* TODO enable extensions */
6305 expression_t *expression = parse_sub_expression(precedence);
6306 /* TODO disable extensions */
6311 * Parse a __builtin_classify_type() expression.
6313 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6315 eat(T___builtin_classify_type);
6317 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6318 result->base.type = type_int;
6321 add_anchor_token(')');
6322 expression_t *expression = parse_sub_expression(precedence);
6323 rem_anchor_token(')');
6325 result->classify_type.type_expression = expression;
6329 return create_invalid_expression();
6332 static void check_pointer_arithmetic(const source_position_t *source_position,
6333 type_t *pointer_type,
6334 type_t *orig_pointer_type)
6336 type_t *points_to = pointer_type->pointer.points_to;
6337 points_to = skip_typeref(points_to);
6339 if (is_type_incomplete(points_to) &&
6341 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6342 errorf(source_position,
6343 "arithmetic with pointer to incomplete type '%T' not allowed",
6345 } else if (is_type_function(points_to)) {
6346 errorf(source_position,
6347 "arithmetic with pointer to function type '%T' not allowed",
6352 static void semantic_incdec(unary_expression_t *expression)
6354 type_t *const orig_type = expression->value->base.type;
6355 type_t *const type = skip_typeref(orig_type);
6356 if (is_type_pointer(type)) {
6357 check_pointer_arithmetic(&expression->base.source_position,
6359 } else if (!is_type_real(type) && is_type_valid(type)) {
6360 /* TODO: improve error message */
6361 errorf(HERE, "operation needs an arithmetic or pointer type");
6363 expression->base.type = orig_type;
6366 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6368 type_t *const orig_type = expression->value->base.type;
6369 type_t *const type = skip_typeref(orig_type);
6370 if (!is_type_arithmetic(type)) {
6371 if (is_type_valid(type)) {
6372 /* TODO: improve error message */
6373 errorf(HERE, "operation needs an arithmetic type");
6378 expression->base.type = orig_type;
6381 static void semantic_unexpr_scalar(unary_expression_t *expression)
6383 type_t *const orig_type = expression->value->base.type;
6384 type_t *const type = skip_typeref(orig_type);
6385 if (!is_type_scalar(type)) {
6386 if (is_type_valid(type)) {
6387 errorf(HERE, "operand of ! must be of scalar type");
6392 expression->base.type = orig_type;
6395 static void semantic_unexpr_integer(unary_expression_t *expression)
6397 type_t *const orig_type = expression->value->base.type;
6398 type_t *const type = skip_typeref(orig_type);
6399 if (!is_type_integer(type)) {
6400 if (is_type_valid(type)) {
6401 errorf(HERE, "operand of ~ must be of integer type");
6406 expression->base.type = orig_type;
6409 static void semantic_dereference(unary_expression_t *expression)
6411 type_t *const orig_type = expression->value->base.type;
6412 type_t *const type = skip_typeref(orig_type);
6413 if (!is_type_pointer(type)) {
6414 if (is_type_valid(type)) {
6415 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6420 type_t *result_type = type->pointer.points_to;
6421 result_type = automatic_type_conversion(result_type);
6422 expression->base.type = result_type;
6425 static void set_address_taken(expression_t *expression, bool may_be_register)
6427 if (expression->kind != EXPR_REFERENCE)
6430 declaration_t *const declaration = expression->reference.declaration;
6431 /* happens for parse errors */
6432 if (declaration == NULL)
6435 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6436 errorf(&expression->base.source_position,
6437 "address of register variable '%Y' requested",
6438 declaration->symbol);
6440 declaration->address_taken = 1;
6445 * Check the semantic of the address taken expression.
6447 static void semantic_take_addr(unary_expression_t *expression)
6449 expression_t *value = expression->value;
6450 value->base.type = revert_automatic_type_conversion(value);
6452 type_t *orig_type = value->base.type;
6453 if (!is_type_valid(orig_type))
6456 set_address_taken(value, false);
6458 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6461 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6462 static expression_t *parse_##unexpression_type(unsigned precedence) \
6466 expression_t *unary_expression \
6467 = allocate_expression_zero(unexpression_type); \
6468 unary_expression->base.source_position = *HERE; \
6469 unary_expression->unary.value = parse_sub_expression(precedence); \
6471 sfunc(&unary_expression->unary); \
6473 return unary_expression; \
6476 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6477 semantic_unexpr_arithmetic)
6478 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6479 semantic_unexpr_arithmetic)
6480 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6481 semantic_unexpr_scalar)
6482 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6483 semantic_dereference)
6484 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6486 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6487 semantic_unexpr_integer)
6488 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6490 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6493 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6495 static expression_t *parse_##unexpression_type(unsigned precedence, \
6496 expression_t *left) \
6498 (void) precedence; \
6501 expression_t *unary_expression \
6502 = allocate_expression_zero(unexpression_type); \
6503 unary_expression->unary.value = left; \
6505 sfunc(&unary_expression->unary); \
6507 return unary_expression; \
6510 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6511 EXPR_UNARY_POSTFIX_INCREMENT,
6513 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6514 EXPR_UNARY_POSTFIX_DECREMENT,
6517 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6519 /* TODO: handle complex + imaginary types */
6521 /* § 6.3.1.8 Usual arithmetic conversions */
6522 if (type_left == type_long_double || type_right == type_long_double) {
6523 return type_long_double;
6524 } else if (type_left == type_double || type_right == type_double) {
6526 } else if (type_left == type_float || type_right == type_float) {
6530 type_right = promote_integer(type_right);
6531 type_left = promote_integer(type_left);
6533 if (type_left == type_right)
6536 bool signed_left = is_type_signed(type_left);
6537 bool signed_right = is_type_signed(type_right);
6538 int rank_left = get_rank(type_left);
6539 int rank_right = get_rank(type_right);
6540 if (rank_left < rank_right) {
6541 if (signed_left == signed_right || !signed_right) {
6547 if (signed_left == signed_right || !signed_left) {
6556 * Check the semantic restrictions for a binary expression.
6558 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6560 expression_t *const left = expression->left;
6561 expression_t *const right = expression->right;
6562 type_t *const orig_type_left = left->base.type;
6563 type_t *const orig_type_right = right->base.type;
6564 type_t *const type_left = skip_typeref(orig_type_left);
6565 type_t *const type_right = skip_typeref(orig_type_right);
6567 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6568 /* TODO: improve error message */
6569 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6570 errorf(HERE, "operation needs arithmetic types");
6575 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6576 expression->left = create_implicit_cast(left, arithmetic_type);
6577 expression->right = create_implicit_cast(right, arithmetic_type);
6578 expression->base.type = arithmetic_type;
6581 static void semantic_shift_op(binary_expression_t *expression)
6583 expression_t *const left = expression->left;
6584 expression_t *const right = expression->right;
6585 type_t *const orig_type_left = left->base.type;
6586 type_t *const orig_type_right = right->base.type;
6587 type_t * type_left = skip_typeref(orig_type_left);
6588 type_t * type_right = skip_typeref(orig_type_right);
6590 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
6591 /* TODO: improve error message */
6592 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6593 errorf(HERE, "operation needs integer types");
6598 type_left = promote_integer(type_left);
6599 type_right = promote_integer(type_right);
6601 expression->left = create_implicit_cast(left, type_left);
6602 expression->right = create_implicit_cast(right, type_right);
6603 expression->base.type = type_left;
6606 static void semantic_add(binary_expression_t *expression)
6608 expression_t *const left = expression->left;
6609 expression_t *const right = expression->right;
6610 type_t *const orig_type_left = left->base.type;
6611 type_t *const orig_type_right = right->base.type;
6612 type_t *const type_left = skip_typeref(orig_type_left);
6613 type_t *const type_right = skip_typeref(orig_type_right);
6616 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6617 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6618 expression->left = create_implicit_cast(left, arithmetic_type);
6619 expression->right = create_implicit_cast(right, arithmetic_type);
6620 expression->base.type = arithmetic_type;
6622 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6623 check_pointer_arithmetic(&expression->base.source_position,
6624 type_left, orig_type_left);
6625 expression->base.type = type_left;
6626 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6627 check_pointer_arithmetic(&expression->base.source_position,
6628 type_right, orig_type_right);
6629 expression->base.type = type_right;
6630 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6631 errorf(&expression->base.source_position,
6632 "invalid operands to binary + ('%T', '%T')",
6633 orig_type_left, orig_type_right);
6637 static void semantic_sub(binary_expression_t *expression)
6639 expression_t *const left = expression->left;
6640 expression_t *const right = expression->right;
6641 type_t *const orig_type_left = left->base.type;
6642 type_t *const orig_type_right = right->base.type;
6643 type_t *const type_left = skip_typeref(orig_type_left);
6644 type_t *const type_right = skip_typeref(orig_type_right);
6647 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6648 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6649 expression->left = create_implicit_cast(left, arithmetic_type);
6650 expression->right = create_implicit_cast(right, arithmetic_type);
6651 expression->base.type = arithmetic_type;
6653 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6654 check_pointer_arithmetic(&expression->base.source_position,
6655 type_left, orig_type_left);
6656 expression->base.type = type_left;
6657 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6658 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6659 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6660 if (!types_compatible(unqual_left, unqual_right)) {
6661 errorf(&expression->base.source_position,
6662 "subtracting pointers to incompatible types '%T' and '%T'",
6663 orig_type_left, orig_type_right);
6664 } else if (!is_type_object(unqual_left)) {
6665 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6666 warningf(&expression->base.source_position,
6667 "subtracting pointers to void");
6669 errorf(&expression->base.source_position,
6670 "subtracting pointers to non-object types '%T'",
6674 expression->base.type = type_ptrdiff_t;
6675 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6676 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6677 orig_type_left, orig_type_right);
6682 * Check the semantics of comparison expressions.
6684 * @param expression The expression to check.
6686 static void semantic_comparison(binary_expression_t *expression)
6688 expression_t *left = expression->left;
6689 expression_t *right = expression->right;
6690 type_t *orig_type_left = left->base.type;
6691 type_t *orig_type_right = right->base.type;
6693 type_t *type_left = skip_typeref(orig_type_left);
6694 type_t *type_right = skip_typeref(orig_type_right);
6696 /* TODO non-arithmetic types */
6697 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6698 /* test for signed vs unsigned compares */
6699 if (warning.sign_compare &&
6700 (expression->base.kind != EXPR_BINARY_EQUAL &&
6701 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6702 (is_type_signed(type_left) != is_type_signed(type_right))) {
6704 /* check if 1 of the operands is a constant, in this case we just
6705 * check wether we can safely represent the resulting constant in
6706 * the type of the other operand. */
6707 expression_t *const_expr = NULL;
6708 expression_t *other_expr = NULL;
6710 if (is_constant_expression(left)) {
6713 } else if (is_constant_expression(right)) {
6718 if (const_expr != NULL) {
6719 type_t *other_type = skip_typeref(other_expr->base.type);
6720 long val = fold_constant(const_expr);
6721 /* TODO: check if val can be represented by other_type */
6725 warningf(&expression->base.source_position,
6726 "comparison between signed and unsigned");
6728 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6729 expression->left = create_implicit_cast(left, arithmetic_type);
6730 expression->right = create_implicit_cast(right, arithmetic_type);
6731 expression->base.type = arithmetic_type;
6732 if (warning.float_equal &&
6733 (expression->base.kind == EXPR_BINARY_EQUAL ||
6734 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6735 is_type_float(arithmetic_type)) {
6736 warningf(&expression->base.source_position,
6737 "comparing floating point with == or != is unsafe");
6739 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6740 /* TODO check compatibility */
6741 } else if (is_type_pointer(type_left)) {
6742 expression->right = create_implicit_cast(right, type_left);
6743 } else if (is_type_pointer(type_right)) {
6744 expression->left = create_implicit_cast(left, type_right);
6745 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6746 type_error_incompatible("invalid operands in comparison",
6747 &expression->base.source_position,
6748 type_left, type_right);
6750 expression->base.type = type_int;
6754 * Checks if a compound type has constant fields.
6756 static bool has_const_fields(const compound_type_t *type)
6758 const scope_t *scope = &type->declaration->scope;
6759 const declaration_t *declaration = scope->declarations;
6761 for (; declaration != NULL; declaration = declaration->next) {
6762 if (declaration->namespc != NAMESPACE_NORMAL)
6765 const type_t *decl_type = skip_typeref(declaration->type);
6766 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6773 static bool is_lvalue(const expression_t *expression)
6775 switch (expression->kind) {
6776 case EXPR_REFERENCE:
6777 case EXPR_ARRAY_ACCESS:
6779 case EXPR_UNARY_DEREFERENCE:
6787 static bool is_valid_assignment_lhs(expression_t const* const left)
6789 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6790 type_t *const type_left = skip_typeref(orig_type_left);
6792 if (!is_lvalue(left)) {
6793 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6798 if (is_type_array(type_left)) {
6799 errorf(HERE, "cannot assign to arrays ('%E')", left);
6802 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6803 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6807 if (is_type_incomplete(type_left)) {
6808 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6809 left, orig_type_left);
6812 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6813 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6814 left, orig_type_left);
6821 static void semantic_arithmetic_assign(binary_expression_t *expression)
6823 expression_t *left = expression->left;
6824 expression_t *right = expression->right;
6825 type_t *orig_type_left = left->base.type;
6826 type_t *orig_type_right = right->base.type;
6828 if (!is_valid_assignment_lhs(left))
6831 type_t *type_left = skip_typeref(orig_type_left);
6832 type_t *type_right = skip_typeref(orig_type_right);
6834 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6835 /* TODO: improve error message */
6836 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6837 errorf(HERE, "operation needs arithmetic types");
6842 /* combined instructions are tricky. We can't create an implicit cast on
6843 * the left side, because we need the uncasted form for the store.
6844 * The ast2firm pass has to know that left_type must be right_type
6845 * for the arithmetic operation and create a cast by itself */
6846 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6847 expression->right = create_implicit_cast(right, arithmetic_type);
6848 expression->base.type = type_left;
6851 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6853 expression_t *const left = expression->left;
6854 expression_t *const right = expression->right;
6855 type_t *const orig_type_left = left->base.type;
6856 type_t *const orig_type_right = right->base.type;
6857 type_t *const type_left = skip_typeref(orig_type_left);
6858 type_t *const type_right = skip_typeref(orig_type_right);
6860 if (!is_valid_assignment_lhs(left))
6863 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6864 /* combined instructions are tricky. We can't create an implicit cast on
6865 * the left side, because we need the uncasted form for the store.
6866 * The ast2firm pass has to know that left_type must be right_type
6867 * for the arithmetic operation and create a cast by itself */
6868 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6869 expression->right = create_implicit_cast(right, arithmetic_type);
6870 expression->base.type = type_left;
6871 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6872 check_pointer_arithmetic(&expression->base.source_position,
6873 type_left, orig_type_left);
6874 expression->base.type = type_left;
6875 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6876 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6881 * Check the semantic restrictions of a logical expression.
6883 static void semantic_logical_op(binary_expression_t *expression)
6885 expression_t *const left = expression->left;
6886 expression_t *const right = expression->right;
6887 type_t *const orig_type_left = left->base.type;
6888 type_t *const orig_type_right = right->base.type;
6889 type_t *const type_left = skip_typeref(orig_type_left);
6890 type_t *const type_right = skip_typeref(orig_type_right);
6892 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6893 /* TODO: improve error message */
6894 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6895 errorf(HERE, "operation needs scalar types");
6900 expression->base.type = type_int;
6904 * Check the semantic restrictions of a binary assign expression.
6906 static void semantic_binexpr_assign(binary_expression_t *expression)
6908 expression_t *left = expression->left;
6909 type_t *orig_type_left = left->base.type;
6911 type_t *type_left = revert_automatic_type_conversion(left);
6912 type_left = skip_typeref(orig_type_left);
6914 if (!is_valid_assignment_lhs(left))
6917 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6918 report_assign_error(error, orig_type_left, expression->right,
6919 "assignment", &left->base.source_position);
6920 expression->right = create_implicit_cast(expression->right, orig_type_left);
6921 expression->base.type = orig_type_left;
6925 * Determine if the outermost operation (or parts thereof) of the given
6926 * expression has no effect in order to generate a warning about this fact.
6927 * Therefore in some cases this only examines some of the operands of the
6928 * expression (see comments in the function and examples below).
6930 * f() + 23; // warning, because + has no effect
6931 * x || f(); // no warning, because x controls execution of f()
6932 * x ? y : f(); // warning, because y has no effect
6933 * (void)x; // no warning to be able to suppress the warning
6934 * This function can NOT be used for an "expression has definitely no effect"-
6936 static bool expression_has_effect(const expression_t *const expr)
6938 switch (expr->kind) {
6939 case EXPR_UNKNOWN: break;
6940 case EXPR_INVALID: return true; /* do NOT warn */
6941 case EXPR_REFERENCE: return false;
6942 /* suppress the warning for microsoft __noop operations */
6943 case EXPR_CONST: return expr->conste.is_ms_noop;
6944 case EXPR_CHARACTER_CONSTANT: return false;
6945 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6946 case EXPR_STRING_LITERAL: return false;
6947 case EXPR_WIDE_STRING_LITERAL: return false;
6950 const call_expression_t *const call = &expr->call;
6951 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6954 switch (call->function->builtin_symbol.symbol->ID) {
6955 case T___builtin_va_end: return true;
6956 default: return false;
6960 /* Generate the warning if either the left or right hand side of a
6961 * conditional expression has no effect */
6962 case EXPR_CONDITIONAL: {
6963 const conditional_expression_t *const cond = &expr->conditional;
6965 expression_has_effect(cond->true_expression) &&
6966 expression_has_effect(cond->false_expression);
6969 case EXPR_SELECT: return false;
6970 case EXPR_ARRAY_ACCESS: return false;
6971 case EXPR_SIZEOF: return false;
6972 case EXPR_CLASSIFY_TYPE: return false;
6973 case EXPR_ALIGNOF: return false;
6975 case EXPR_FUNCNAME: return false;
6976 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6977 case EXPR_BUILTIN_CONSTANT_P: return false;
6978 case EXPR_BUILTIN_PREFETCH: return true;
6979 case EXPR_OFFSETOF: return false;
6980 case EXPR_VA_START: return true;
6981 case EXPR_VA_ARG: return true;
6982 case EXPR_STATEMENT: return true; // TODO
6983 case EXPR_COMPOUND_LITERAL: return false;
6985 case EXPR_UNARY_NEGATE: return false;
6986 case EXPR_UNARY_PLUS: return false;
6987 case EXPR_UNARY_BITWISE_NEGATE: return false;
6988 case EXPR_UNARY_NOT: return false;
6989 case EXPR_UNARY_DEREFERENCE: return false;
6990 case EXPR_UNARY_TAKE_ADDRESS: return false;
6991 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6992 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6993 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6994 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6996 /* Treat void casts as if they have an effect in order to being able to
6997 * suppress the warning */
6998 case EXPR_UNARY_CAST: {
6999 type_t *const type = skip_typeref(expr->base.type);
7000 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7003 case EXPR_UNARY_CAST_IMPLICIT: return true;
7004 case EXPR_UNARY_ASSUME: return true;
7006 case EXPR_BINARY_ADD: return false;
7007 case EXPR_BINARY_SUB: return false;
7008 case EXPR_BINARY_MUL: return false;
7009 case EXPR_BINARY_DIV: return false;
7010 case EXPR_BINARY_MOD: return false;
7011 case EXPR_BINARY_EQUAL: return false;
7012 case EXPR_BINARY_NOTEQUAL: return false;
7013 case EXPR_BINARY_LESS: return false;
7014 case EXPR_BINARY_LESSEQUAL: return false;
7015 case EXPR_BINARY_GREATER: return false;
7016 case EXPR_BINARY_GREATEREQUAL: return false;
7017 case EXPR_BINARY_BITWISE_AND: return false;
7018 case EXPR_BINARY_BITWISE_OR: return false;
7019 case EXPR_BINARY_BITWISE_XOR: return false;
7020 case EXPR_BINARY_SHIFTLEFT: return false;
7021 case EXPR_BINARY_SHIFTRIGHT: return false;
7022 case EXPR_BINARY_ASSIGN: return true;
7023 case EXPR_BINARY_MUL_ASSIGN: return true;
7024 case EXPR_BINARY_DIV_ASSIGN: return true;
7025 case EXPR_BINARY_MOD_ASSIGN: return true;
7026 case EXPR_BINARY_ADD_ASSIGN: return true;
7027 case EXPR_BINARY_SUB_ASSIGN: return true;
7028 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7029 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7030 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7031 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7032 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7034 /* Only examine the right hand side of && and ||, because the left hand
7035 * side already has the effect of controlling the execution of the right
7037 case EXPR_BINARY_LOGICAL_AND:
7038 case EXPR_BINARY_LOGICAL_OR:
7039 /* Only examine the right hand side of a comma expression, because the left
7040 * hand side has a separate warning */
7041 case EXPR_BINARY_COMMA:
7042 return expression_has_effect(expr->binary.right);
7044 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7045 case EXPR_BINARY_ISGREATER: return false;
7046 case EXPR_BINARY_ISGREATEREQUAL: return false;
7047 case EXPR_BINARY_ISLESS: return false;
7048 case EXPR_BINARY_ISLESSEQUAL: return false;
7049 case EXPR_BINARY_ISLESSGREATER: return false;
7050 case EXPR_BINARY_ISUNORDERED: return false;
7053 internal_errorf(HERE, "unexpected expression");
7056 static void semantic_comma(binary_expression_t *expression)
7058 if (warning.unused_value) {
7059 const expression_t *const left = expression->left;
7060 if (!expression_has_effect(left)) {
7061 warningf(&left->base.source_position,
7062 "left-hand operand of comma expression has no effect");
7065 expression->base.type = expression->right->base.type;
7068 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7069 static expression_t *parse_##binexpression_type(unsigned precedence, \
7070 expression_t *left) \
7073 source_position_t pos = *HERE; \
7075 expression_t *right = parse_sub_expression(precedence + lr); \
7077 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7078 binexpr->base.source_position = pos; \
7079 binexpr->binary.left = left; \
7080 binexpr->binary.right = right; \
7081 sfunc(&binexpr->binary); \
7086 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7087 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7088 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7089 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7090 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7091 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7092 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7093 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7094 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7096 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7097 semantic_comparison, 1)
7098 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7099 semantic_comparison, 1)
7100 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7101 semantic_comparison, 1)
7102 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7103 semantic_comparison, 1)
7105 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7106 semantic_binexpr_arithmetic, 1)
7107 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7108 semantic_binexpr_arithmetic, 1)
7109 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7110 semantic_binexpr_arithmetic, 1)
7111 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7112 semantic_logical_op, 1)
7113 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7114 semantic_logical_op, 1)
7115 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7116 semantic_shift_op, 1)
7117 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7118 semantic_shift_op, 1)
7119 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7120 semantic_arithmetic_addsubb_assign, 0)
7121 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7122 semantic_arithmetic_addsubb_assign, 0)
7123 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7124 semantic_arithmetic_assign, 0)
7125 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7126 semantic_arithmetic_assign, 0)
7127 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7128 semantic_arithmetic_assign, 0)
7129 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7130 semantic_arithmetic_assign, 0)
7131 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7132 semantic_arithmetic_assign, 0)
7133 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7134 semantic_arithmetic_assign, 0)
7135 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7136 semantic_arithmetic_assign, 0)
7137 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7138 semantic_arithmetic_assign, 0)
7140 static expression_t *parse_sub_expression(unsigned precedence)
7142 if (token.type < 0) {
7143 return expected_expression_error();
7146 expression_parser_function_t *parser
7147 = &expression_parsers[token.type];
7148 source_position_t source_position = token.source_position;
7151 if (parser->parser != NULL) {
7152 left = parser->parser(parser->precedence);
7154 left = parse_primary_expression();
7156 assert(left != NULL);
7157 left->base.source_position = source_position;
7160 if (token.type < 0) {
7161 return expected_expression_error();
7164 parser = &expression_parsers[token.type];
7165 if (parser->infix_parser == NULL)
7167 if (parser->infix_precedence < precedence)
7170 left = parser->infix_parser(parser->infix_precedence, left);
7172 assert(left != NULL);
7173 assert(left->kind != EXPR_UNKNOWN);
7174 left->base.source_position = source_position;
7181 * Parse an expression.
7183 static expression_t *parse_expression(void)
7185 return parse_sub_expression(1);
7189 * Register a parser for a prefix-like operator with given precedence.
7191 * @param parser the parser function
7192 * @param token_type the token type of the prefix token
7193 * @param precedence the precedence of the operator
7195 static void register_expression_parser(parse_expression_function parser,
7196 int token_type, unsigned precedence)
7198 expression_parser_function_t *entry = &expression_parsers[token_type];
7200 if (entry->parser != NULL) {
7201 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7202 panic("trying to register multiple expression parsers for a token");
7204 entry->parser = parser;
7205 entry->precedence = precedence;
7209 * Register a parser for an infix operator with given precedence.
7211 * @param parser the parser function
7212 * @param token_type the token type of the infix operator
7213 * @param precedence the precedence of the operator
7215 static void register_infix_parser(parse_expression_infix_function parser,
7216 int token_type, unsigned precedence)
7218 expression_parser_function_t *entry = &expression_parsers[token_type];
7220 if (entry->infix_parser != NULL) {
7221 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7222 panic("trying to register multiple infix expression parsers for a "
7225 entry->infix_parser = parser;
7226 entry->infix_precedence = precedence;
7230 * Initialize the expression parsers.
7232 static void init_expression_parsers(void)
7234 memset(&expression_parsers, 0, sizeof(expression_parsers));
7236 register_infix_parser(parse_array_expression, '[', 30);
7237 register_infix_parser(parse_call_expression, '(', 30);
7238 register_infix_parser(parse_select_expression, '.', 30);
7239 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7240 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7242 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7245 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7246 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7247 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7248 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7249 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7250 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7251 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7252 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7253 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7254 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7255 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7256 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7257 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7258 T_EXCLAMATIONMARKEQUAL, 13);
7259 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7260 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7261 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7262 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7263 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7264 register_infix_parser(parse_conditional_expression, '?', 7);
7265 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7266 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7267 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7268 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7269 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7270 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7271 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7272 T_LESSLESSEQUAL, 2);
7273 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7274 T_GREATERGREATEREQUAL, 2);
7275 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7277 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7279 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7282 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7284 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7285 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7286 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7287 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7288 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7289 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7290 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7292 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7294 register_expression_parser(parse_sizeof, T_sizeof, 25);
7295 register_expression_parser(parse_alignof, T___alignof__, 25);
7296 register_expression_parser(parse_extension, T___extension__, 25);
7297 register_expression_parser(parse_builtin_classify_type,
7298 T___builtin_classify_type, 25);
7302 * Parse a asm statement arguments specification.
7304 static asm_argument_t *parse_asm_arguments(bool is_out)
7306 asm_argument_t *result = NULL;
7307 asm_argument_t *last = NULL;
7309 while (token.type == T_STRING_LITERAL || token.type == '[') {
7310 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7311 memset(argument, 0, sizeof(argument[0]));
7313 if (token.type == '[') {
7315 if (token.type != T_IDENTIFIER) {
7316 parse_error_expected("while parsing asm argument",
7317 T_IDENTIFIER, NULL);
7320 argument->symbol = token.v.symbol;
7325 argument->constraints = parse_string_literals();
7327 expression_t *expression = parse_expression();
7328 argument->expression = expression;
7329 if (is_out && !is_lvalue(expression)) {
7330 errorf(&expression->base.source_position,
7331 "asm output argument is not an lvalue");
7335 set_address_taken(expression, true);
7338 last->next = argument;
7344 if (token.type != ',')
7355 * Parse a asm statement clobber specification.
7357 static asm_clobber_t *parse_asm_clobbers(void)
7359 asm_clobber_t *result = NULL;
7360 asm_clobber_t *last = NULL;
7362 while(token.type == T_STRING_LITERAL) {
7363 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7364 clobber->clobber = parse_string_literals();
7367 last->next = clobber;
7373 if (token.type != ',')
7382 * Parse an asm statement.
7384 static statement_t *parse_asm_statement(void)
7388 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7389 statement->base.source_position = token.source_position;
7391 asm_statement_t *asm_statement = &statement->asms;
7393 if (token.type == T_volatile) {
7395 asm_statement->is_volatile = true;
7399 add_anchor_token(')');
7400 add_anchor_token(':');
7401 asm_statement->asm_text = parse_string_literals();
7403 if (token.type != ':') {
7404 rem_anchor_token(':');
7409 asm_statement->outputs = parse_asm_arguments(true);
7410 if (token.type != ':') {
7411 rem_anchor_token(':');
7416 asm_statement->inputs = parse_asm_arguments(false);
7417 if (token.type != ':') {
7418 rem_anchor_token(':');
7421 rem_anchor_token(':');
7424 asm_statement->clobbers = parse_asm_clobbers();
7427 rem_anchor_token(')');
7432 return create_invalid_statement();
7436 * Parse a case statement.
7438 static statement_t *parse_case_statement(void)
7442 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7444 statement->base.source_position = token.source_position;
7445 statement->case_label.expression = parse_expression();
7447 if (c_mode & _GNUC) {
7448 if (token.type == T_DOTDOTDOT) {
7450 statement->case_label.end_range = parse_expression();
7456 if (! is_constant_expression(statement->case_label.expression)) {
7457 errorf(&statement->base.source_position,
7458 "case label does not reduce to an integer constant");
7460 /* TODO: check if the case label is already known */
7461 if (current_switch != NULL) {
7462 /* link all cases into the switch statement */
7463 if (current_switch->last_case == NULL) {
7464 current_switch->first_case =
7465 current_switch->last_case = &statement->case_label;
7467 current_switch->last_case->next = &statement->case_label;
7470 errorf(&statement->base.source_position,
7471 "case label not within a switch statement");
7474 statement->case_label.statement = parse_statement();
7478 return create_invalid_statement();
7482 * Finds an existing default label of a switch statement.
7484 static case_label_statement_t *
7485 find_default_label(const switch_statement_t *statement)
7487 case_label_statement_t *label = statement->first_case;
7488 for ( ; label != NULL; label = label->next) {
7489 if (label->expression == NULL)
7496 * Parse a default statement.
7498 static statement_t *parse_default_statement(void)
7502 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7504 statement->base.source_position = token.source_position;
7507 if (current_switch != NULL) {
7508 const case_label_statement_t *def_label = find_default_label(current_switch);
7509 if (def_label != NULL) {
7510 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7511 &def_label->base.source_position);
7513 /* link all cases into the switch statement */
7514 if (current_switch->last_case == NULL) {
7515 current_switch->first_case =
7516 current_switch->last_case = &statement->case_label;
7518 current_switch->last_case->next = &statement->case_label;
7522 errorf(&statement->base.source_position,
7523 "'default' label not within a switch statement");
7525 statement->case_label.statement = parse_statement();
7529 return create_invalid_statement();
7533 * Return the declaration for a given label symbol or create a new one.
7535 static declaration_t *get_label(symbol_t *symbol)
7537 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7538 assert(current_function != NULL);
7539 /* if we found a label in the same function, then we already created the
7541 if (candidate != NULL
7542 && candidate->parent_scope == ¤t_function->scope) {
7546 /* otherwise we need to create a new one */
7547 declaration_t *const declaration = allocate_declaration_zero();
7548 declaration->namespc = NAMESPACE_LABEL;
7549 declaration->symbol = symbol;
7551 label_push(declaration);
7557 * Parse a label statement.
7559 static statement_t *parse_label_statement(void)
7561 assert(token.type == T_IDENTIFIER);
7562 symbol_t *symbol = token.v.symbol;
7565 declaration_t *label = get_label(symbol);
7567 /* if source position is already set then the label is defined twice,
7568 * otherwise it was just mentioned in a goto so far */
7569 if (label->source_position.input_name != NULL) {
7570 errorf(HERE, "duplicate label '%Y' (declared %P)",
7571 symbol, &label->source_position);
7573 label->source_position = token.source_position;
7576 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7578 statement->base.source_position = token.source_position;
7579 statement->label.label = label;
7583 if (token.type == '}') {
7584 /* TODO only warn? */
7586 warningf(HERE, "label at end of compound statement");
7587 statement->label.statement = create_empty_statement();
7589 errorf(HERE, "label at end of compound statement");
7590 statement->label.statement = create_invalid_statement();
7594 if (token.type == ';') {
7595 /* eat an empty statement here, to avoid the warning about an empty
7596 * after a label. label:; is commonly used to have a label before
7598 statement->label.statement = create_empty_statement();
7601 statement->label.statement = parse_statement();
7605 /* remember the labels's in a list for later checking */
7606 if (label_last == NULL) {
7607 label_first = &statement->label;
7609 label_last->next = &statement->label;
7611 label_last = &statement->label;
7617 * Parse an if statement.
7619 static statement_t *parse_if(void)
7623 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7624 statement->base.source_position = token.source_position;
7627 add_anchor_token(')');
7628 statement->ifs.condition = parse_expression();
7629 rem_anchor_token(')');
7632 add_anchor_token(T_else);
7633 statement->ifs.true_statement = parse_statement();
7634 rem_anchor_token(T_else);
7636 if (token.type == T_else) {
7638 statement->ifs.false_statement = parse_statement();
7643 return create_invalid_statement();
7647 * Parse a switch statement.
7649 static statement_t *parse_switch(void)
7653 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7654 statement->base.source_position = token.source_position;
7657 expression_t *const expr = parse_expression();
7658 type_t * type = skip_typeref(expr->base.type);
7659 if (is_type_integer(type)) {
7660 type = promote_integer(type);
7661 } else if (is_type_valid(type)) {
7662 errorf(&expr->base.source_position,
7663 "switch quantity is not an integer, but '%T'", type);
7664 type = type_error_type;
7666 statement->switchs.expression = create_implicit_cast(expr, type);
7669 switch_statement_t *rem = current_switch;
7670 current_switch = &statement->switchs;
7671 statement->switchs.body = parse_statement();
7672 current_switch = rem;
7674 if (warning.switch_default &&
7675 find_default_label(&statement->switchs) == NULL) {
7676 warningf(&statement->base.source_position, "switch has no default case");
7681 return create_invalid_statement();
7684 static statement_t *parse_loop_body(statement_t *const loop)
7686 statement_t *const rem = current_loop;
7687 current_loop = loop;
7689 statement_t *const body = parse_statement();
7696 * Parse a while statement.
7698 static statement_t *parse_while(void)
7702 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7703 statement->base.source_position = token.source_position;
7706 add_anchor_token(')');
7707 statement->whiles.condition = parse_expression();
7708 rem_anchor_token(')');
7711 statement->whiles.body = parse_loop_body(statement);
7715 return create_invalid_statement();
7719 * Parse a do statement.
7721 static statement_t *parse_do(void)
7725 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7727 statement->base.source_position = token.source_position;
7729 add_anchor_token(T_while);
7730 statement->do_while.body = parse_loop_body(statement);
7731 rem_anchor_token(T_while);
7735 add_anchor_token(')');
7736 statement->do_while.condition = parse_expression();
7737 rem_anchor_token(')');
7743 return create_invalid_statement();
7747 * Parse a for statement.
7749 static statement_t *parse_for(void)
7753 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7754 statement->base.source_position = token.source_position;
7756 int top = environment_top();
7757 scope_t *last_scope = scope;
7758 set_scope(&statement->fors.scope);
7761 add_anchor_token(')');
7763 if (token.type != ';') {
7764 if (is_declaration_specifier(&token, false)) {
7765 parse_declaration(record_declaration);
7767 add_anchor_token(';');
7768 expression_t *const init = parse_expression();
7769 statement->fors.initialisation = init;
7770 if (warning.unused_value && !expression_has_effect(init)) {
7771 warningf(&init->base.source_position,
7772 "initialisation of 'for'-statement has no effect");
7774 rem_anchor_token(';');
7781 if (token.type != ';') {
7782 add_anchor_token(';');
7783 statement->fors.condition = parse_expression();
7784 rem_anchor_token(';');
7787 if (token.type != ')') {
7788 expression_t *const step = parse_expression();
7789 statement->fors.step = step;
7790 if (warning.unused_value && !expression_has_effect(step)) {
7791 warningf(&step->base.source_position,
7792 "step of 'for'-statement has no effect");
7795 rem_anchor_token(')');
7797 statement->fors.body = parse_loop_body(statement);
7799 assert(scope == &statement->fors.scope);
7800 set_scope(last_scope);
7801 environment_pop_to(top);
7806 rem_anchor_token(')');
7807 assert(scope == &statement->fors.scope);
7808 set_scope(last_scope);
7809 environment_pop_to(top);
7811 return create_invalid_statement();
7815 * Parse a goto statement.
7817 static statement_t *parse_goto(void)
7821 if (token.type != T_IDENTIFIER) {
7822 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7826 symbol_t *symbol = token.v.symbol;
7829 declaration_t *label = get_label(symbol);
7831 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7832 statement->base.source_position = token.source_position;
7834 statement->gotos.label = label;
7836 /* remember the goto's in a list for later checking */
7837 if (goto_last == NULL) {
7838 goto_first = &statement->gotos;
7840 goto_last->next = &statement->gotos;
7842 goto_last = &statement->gotos;
7848 return create_invalid_statement();
7852 * Parse a continue statement.
7854 static statement_t *parse_continue(void)
7856 statement_t *statement;
7857 if (current_loop == NULL) {
7858 errorf(HERE, "continue statement not within loop");
7859 statement = create_invalid_statement();
7861 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7863 statement->base.source_position = token.source_position;
7871 return create_invalid_statement();
7875 * Parse a break statement.
7877 static statement_t *parse_break(void)
7879 statement_t *statement;
7880 if (current_switch == NULL && current_loop == NULL) {
7881 errorf(HERE, "break statement not within loop or switch");
7882 statement = create_invalid_statement();
7884 statement = allocate_statement_zero(STATEMENT_BREAK);
7886 statement->base.source_position = token.source_position;
7894 return create_invalid_statement();
7898 * Parse a __leave statement.
7900 static statement_t *parse_leave(void)
7902 statement_t *statement;
7903 if (current_try == NULL) {
7904 errorf(HERE, "__leave statement not within __try");
7905 statement = create_invalid_statement();
7907 statement = allocate_statement_zero(STATEMENT_LEAVE);
7909 statement->base.source_position = token.source_position;
7917 return create_invalid_statement();
7921 * Check if a given declaration represents a local variable.
7923 static bool is_local_var_declaration(const declaration_t *declaration) {
7924 switch ((storage_class_tag_t) declaration->storage_class) {
7925 case STORAGE_CLASS_AUTO:
7926 case STORAGE_CLASS_REGISTER: {
7927 const type_t *type = skip_typeref(declaration->type);
7928 if (is_type_function(type)) {
7940 * Check if a given declaration represents a variable.
7942 static bool is_var_declaration(const declaration_t *declaration) {
7943 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7946 const type_t *type = skip_typeref(declaration->type);
7947 return !is_type_function(type);
7951 * Check if a given expression represents a local variable.
7953 static bool is_local_variable(const expression_t *expression)
7955 if (expression->base.kind != EXPR_REFERENCE) {
7958 const declaration_t *declaration = expression->reference.declaration;
7959 return is_local_var_declaration(declaration);
7963 * Check if a given expression represents a local variable and
7964 * return its declaration then, else return NULL.
7966 declaration_t *expr_is_variable(const expression_t *expression)
7968 if (expression->base.kind != EXPR_REFERENCE) {
7971 declaration_t *declaration = expression->reference.declaration;
7972 if (is_var_declaration(declaration))
7978 * Parse a return statement.
7980 static statement_t *parse_return(void)
7982 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7983 statement->base.source_position = token.source_position;
7987 expression_t *return_value = NULL;
7988 if (token.type != ';') {
7989 return_value = parse_expression();
7993 const type_t *const func_type = current_function->type;
7994 assert(is_type_function(func_type));
7995 type_t *const return_type = skip_typeref(func_type->function.return_type);
7997 if (return_value != NULL) {
7998 type_t *return_value_type = skip_typeref(return_value->base.type);
8000 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8001 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8002 warningf(&statement->base.source_position,
8003 "'return' with a value, in function returning void");
8004 return_value = NULL;
8006 assign_error_t error = semantic_assign(return_type, return_value);
8007 report_assign_error(error, return_type, return_value, "'return'",
8008 &statement->base.source_position);
8009 return_value = create_implicit_cast(return_value, return_type);
8011 /* check for returning address of a local var */
8012 if (return_value != NULL &&
8013 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8014 const expression_t *expression = return_value->unary.value;
8015 if (is_local_variable(expression)) {
8016 warningf(&statement->base.source_position,
8017 "function returns address of local variable");
8021 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8022 warningf(&statement->base.source_position,
8023 "'return' without value, in function returning non-void");
8026 statement->returns.value = return_value;
8030 return create_invalid_statement();
8034 * Parse a declaration statement.
8036 static statement_t *parse_declaration_statement(void)
8038 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8040 statement->base.source_position = token.source_position;
8042 declaration_t *before = last_declaration;
8043 parse_declaration(record_declaration);
8045 if (before == NULL) {
8046 statement->declaration.declarations_begin = scope->declarations;
8048 statement->declaration.declarations_begin = before->next;
8050 statement->declaration.declarations_end = last_declaration;
8056 * Parse an expression statement, ie. expr ';'.
8058 static statement_t *parse_expression_statement(void)
8060 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8062 statement->base.source_position = token.source_position;
8063 expression_t *const expr = parse_expression();
8064 statement->expression.expression = expr;
8070 return create_invalid_statement();
8074 * Parse a microsoft __try { } __finally { } or
8075 * __try{ } __except() { }
8077 static statement_t *parse_ms_try_statment(void) {
8078 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8080 statement->base.source_position = token.source_position;
8083 ms_try_statement_t *rem = current_try;
8084 current_try = &statement->ms_try;
8085 statement->ms_try.try_statement = parse_compound_statement(false);
8088 if (token.type == T___except) {
8091 add_anchor_token(')');
8092 expression_t *const expr = parse_expression();
8093 type_t * type = skip_typeref(expr->base.type);
8094 if (is_type_integer(type)) {
8095 type = promote_integer(type);
8096 } else if (is_type_valid(type)) {
8097 errorf(&expr->base.source_position,
8098 "__expect expression is not an integer, but '%T'", type);
8099 type = type_error_type;
8101 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8102 rem_anchor_token(')');
8104 statement->ms_try.final_statement = parse_compound_statement(false);
8105 } else if (token.type == T__finally) {
8107 statement->ms_try.final_statement = parse_compound_statement(false);
8109 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8110 return create_invalid_statement();
8114 return create_invalid_statement();
8118 * Parse a statement.
8119 * There's also parse_statement() which additionally checks for
8120 * "statement has no effect" warnings
8122 static statement_t *intern_parse_statement(void)
8124 statement_t *statement = NULL;
8126 /* declaration or statement */
8127 add_anchor_token(';');
8128 switch(token.type) {
8130 statement = parse_asm_statement();
8134 statement = parse_case_statement();
8138 statement = parse_default_statement();
8142 statement = parse_compound_statement(false);
8146 statement = parse_if ();
8150 statement = parse_switch();
8154 statement = parse_while();
8158 statement = parse_do();
8162 statement = parse_for();
8166 statement = parse_goto();
8170 statement = parse_continue();
8174 statement = parse_break();
8178 statement = parse_leave();
8182 statement = parse_return();
8186 if (warning.empty_statement) {
8187 warningf(HERE, "statement is empty");
8189 statement = create_empty_statement();
8194 if (look_ahead(1)->type == ':') {
8195 statement = parse_label_statement();
8199 if (is_typedef_symbol(token.v.symbol)) {
8200 statement = parse_declaration_statement();
8204 statement = parse_expression_statement();
8207 case T___extension__:
8208 /* this can be a prefix to a declaration or an expression statement */
8209 /* we simply eat it now and parse the rest with tail recursion */
8212 } while(token.type == T___extension__);
8213 statement = parse_statement();
8217 statement = parse_declaration_statement();
8221 statement = parse_ms_try_statment();
8225 statement = parse_expression_statement();
8228 rem_anchor_token(';');
8230 assert(statement != NULL
8231 && statement->base.source_position.input_name != NULL);
8237 * parse a statement and emits "statement has no effect" warning if needed
8238 * (This is really a wrapper around intern_parse_statement with check for 1
8239 * single warning. It is needed, because for statement expressions we have
8240 * to avoid the warning on the last statement)
8242 static statement_t *parse_statement(void)
8244 statement_t *statement = intern_parse_statement();
8246 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8247 expression_t *expression = statement->expression.expression;
8248 if (!expression_has_effect(expression)) {
8249 warningf(&expression->base.source_position,
8250 "statement has no effect");
8258 * Parse a compound statement.
8260 static statement_t *parse_compound_statement(bool inside_expression_statement)
8262 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8264 statement->base.source_position = token.source_position;
8267 add_anchor_token('}');
8269 int top = environment_top();
8270 scope_t *last_scope = scope;
8271 set_scope(&statement->compound.scope);
8273 statement_t *last_statement = NULL;
8275 while(token.type != '}' && token.type != T_EOF) {
8276 statement_t *sub_statement = intern_parse_statement();
8277 if (is_invalid_statement(sub_statement)) {
8278 /* an error occurred. if we are at an anchor, return */
8284 if (last_statement != NULL) {
8285 last_statement->base.next = sub_statement;
8287 statement->compound.statements = sub_statement;
8290 while(sub_statement->base.next != NULL)
8291 sub_statement = sub_statement->base.next;
8293 last_statement = sub_statement;
8296 if (token.type == '}') {
8299 errorf(&statement->base.source_position,
8300 "end of file while looking for closing '}'");
8303 /* look over all statements again to produce no effect warnings */
8304 if (warning.unused_value) {
8305 statement_t *sub_statement = statement->compound.statements;
8306 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8307 if (sub_statement->kind != STATEMENT_EXPRESSION)
8309 /* don't emit a warning for the last expression in an expression
8310 * statement as it has always an effect */
8311 if (inside_expression_statement && sub_statement->base.next == NULL)
8314 expression_t *expression = sub_statement->expression.expression;
8315 if (!expression_has_effect(expression)) {
8316 warningf(&expression->base.source_position,
8317 "statement has no effect");
8323 rem_anchor_token('}');
8324 assert(scope == &statement->compound.scope);
8325 set_scope(last_scope);
8326 environment_pop_to(top);
8332 * Initialize builtin types.
8334 static void initialize_builtin_types(void)
8336 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8337 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8338 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8339 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8340 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8341 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8342 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8343 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8345 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8346 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8347 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8348 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8352 * Check for unused global static functions and variables
8354 static void check_unused_globals(void)
8356 if (!warning.unused_function && !warning.unused_variable)
8359 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8360 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
8363 type_t *const type = decl->type;
8365 if (is_type_function(skip_typeref(type))) {
8366 if (!warning.unused_function || decl->is_inline)
8369 s = (decl->init.statement != NULL ? "defined" : "declared");
8371 if (!warning.unused_variable)
8377 warningf(&decl->source_position, "'%#T' %s but not used",
8378 type, decl->symbol, s);
8383 * Parse a translation unit.
8385 static void parse_translation_unit(void)
8387 while(token.type != T_EOF) {
8388 if (token.type == ';') {
8389 /* TODO error in strict mode */
8390 warningf(HERE, "stray ';' outside of function");
8393 parse_external_declaration();
8401 * @return the translation unit or NULL if errors occurred.
8403 void start_parsing(void)
8405 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8406 label_stack = NEW_ARR_F(stack_entry_t, 0);
8407 diagnostic_count = 0;
8411 type_set_output(stderr);
8412 ast_set_output(stderr);
8414 assert(unit == NULL);
8415 unit = allocate_ast_zero(sizeof(unit[0]));
8417 assert(global_scope == NULL);
8418 global_scope = &unit->scope;
8420 assert(scope == NULL);
8421 set_scope(&unit->scope);
8423 initialize_builtin_types();
8426 translation_unit_t *finish_parsing(void)
8428 assert(scope == &unit->scope);
8430 last_declaration = NULL;
8432 assert(global_scope == &unit->scope);
8433 check_unused_globals();
8434 global_scope = NULL;
8436 DEL_ARR_F(environment_stack);
8437 DEL_ARR_F(label_stack);
8439 translation_unit_t *result = unit;
8446 lookahead_bufpos = 0;
8447 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8450 parse_translation_unit();
8454 * Initialize the parser.
8456 void init_parser(void)
8459 /* add predefined symbols for extended-decl-modifier */
8460 sym_align = symbol_table_insert("align");
8461 sym_allocate = symbol_table_insert("allocate");
8462 sym_dllimport = symbol_table_insert("dllimport");
8463 sym_dllexport = symbol_table_insert("dllexport");
8464 sym_naked = symbol_table_insert("naked");
8465 sym_noinline = symbol_table_insert("noinline");
8466 sym_noreturn = symbol_table_insert("noreturn");
8467 sym_nothrow = symbol_table_insert("nothrow");
8468 sym_novtable = symbol_table_insert("novtable");
8469 sym_property = symbol_table_insert("property");
8470 sym_get = symbol_table_insert("get");
8471 sym_put = symbol_table_insert("put");
8472 sym_selectany = symbol_table_insert("selectany");
8473 sym_thread = symbol_table_insert("thread");
8474 sym_uuid = symbol_table_insert("uuid");
8475 sym_deprecated = symbol_table_insert("deprecated");
8476 sym_restrict = symbol_table_insert("restrict");
8477 sym_noalias = symbol_table_insert("noalias");
8479 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8481 init_expression_parsers();
8482 obstack_init(&temp_obst);
8484 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8485 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8489 * Terminate the parser.
8491 void exit_parser(void)
8493 obstack_free(&temp_obst, NULL);