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 /** if wchar_t is equal to unsigned short. */
43 bool opt_short_wchar_t =
50 //#define PRINT_TOKENS
51 #define MAX_LOOKAHEAD 2
54 declaration_t *old_declaration;
56 unsigned short namespc;
59 typedef struct argument_list_t argument_list_t;
60 struct argument_list_t {
62 argument_list_t *next;
65 typedef struct gnu_attribute_t gnu_attribute_t;
66 struct gnu_attribute_t {
67 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
68 gnu_attribute_t *next;
69 bool invalid; /**< Set if this attribute had argument errors, */
70 bool have_arguments; /**< True, if this attribute has arguments. */
74 atomic_type_kind_t akind;
75 long argument; /**< Single argument. */
76 argument_list_t *arguments; /**< List of argument expressions. */
80 typedef struct declaration_specifiers_t declaration_specifiers_t;
81 struct declaration_specifiers_t {
82 source_position_t source_position;
83 unsigned char declared_storage_class;
84 unsigned char alignment; /**< Alignment, 0 if not set. */
85 unsigned int is_inline : 1;
86 unsigned int deprecated : 1;
87 decl_modifiers_t modifiers; /**< declaration modifiers */
88 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
89 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
90 symbol_t *get_property_sym; /**< the name of the get property if set. */
91 symbol_t *put_property_sym; /**< the name of the put property if set. */
96 * An environment for parsing initializers (and compound literals).
98 typedef struct parse_initializer_env_t {
99 type_t *type; /**< the type of the initializer. In case of an
100 array type with unspecified size this gets
101 adjusted to the actual size. */
102 declaration_t *declaration; /**< the declaration that is initialized if any */
103 bool must_be_constant;
104 } parse_initializer_env_t;
106 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
108 static token_t token;
109 static token_t lookahead_buffer[MAX_LOOKAHEAD];
110 static int lookahead_bufpos;
111 static stack_entry_t *environment_stack = NULL;
112 static stack_entry_t *label_stack = NULL;
113 static scope_t *global_scope = NULL;
114 static scope_t *scope = NULL;
115 static declaration_t *last_declaration = NULL;
116 static declaration_t *current_function = NULL;
117 static switch_statement_t *current_switch = NULL;
118 static statement_t *current_loop = NULL;
119 static statement_t *current_parent = NULL;
120 static ms_try_statement_t *current_try = NULL;
121 static goto_statement_t *goto_first = NULL;
122 static goto_statement_t *goto_last = NULL;
123 static label_statement_t *label_first = NULL;
124 static label_statement_t *label_last = NULL;
125 static translation_unit_t *unit = NULL;
126 static struct obstack temp_obst;
128 #define PUSH_PARENT(stmt) \
129 statement_t *const prev_parent = current_parent; \
130 current_parent = (stmt);
131 #define POP_PARENT ((void)(current_parent = prev_parent))
133 static source_position_t null_position = { NULL, 0 };
135 /* symbols for Microsoft extended-decl-modifier */
136 static const symbol_t *sym_align = NULL;
137 static const symbol_t *sym_allocate = NULL;
138 static const symbol_t *sym_dllimport = NULL;
139 static const symbol_t *sym_dllexport = NULL;
140 static const symbol_t *sym_naked = NULL;
141 static const symbol_t *sym_noinline = NULL;
142 static const symbol_t *sym_noreturn = NULL;
143 static const symbol_t *sym_nothrow = NULL;
144 static const symbol_t *sym_novtable = NULL;
145 static const symbol_t *sym_property = NULL;
146 static const symbol_t *sym_get = NULL;
147 static const symbol_t *sym_put = NULL;
148 static const symbol_t *sym_selectany = NULL;
149 static const symbol_t *sym_thread = NULL;
150 static const symbol_t *sym_uuid = NULL;
151 static const symbol_t *sym_deprecated = NULL;
152 static const symbol_t *sym_restrict = NULL;
153 static const symbol_t *sym_noalias = NULL;
155 /** The token anchor set */
156 static unsigned char token_anchor_set[T_LAST_TOKEN];
158 /** The current source position. */
159 #define HERE (&token.source_position)
161 static type_t *type_valist;
163 static statement_t *parse_compound_statement(bool inside_expression_statement);
164 static statement_t *parse_statement(void);
166 static expression_t *parse_sub_expression(unsigned precedence);
167 static expression_t *parse_expression(void);
168 static type_t *parse_typename(void);
170 static void parse_compound_type_entries(declaration_t *compound_declaration);
171 static declaration_t *parse_declarator(
172 const declaration_specifiers_t *specifiers, bool may_be_abstract);
173 static declaration_t *record_declaration(declaration_t *declaration);
175 static void semantic_comparison(binary_expression_t *expression);
177 #define STORAGE_CLASSES \
185 #define TYPE_QUALIFIERS \
190 case T__forceinline: \
191 case T___attribute__:
193 #ifdef PROVIDE_COMPLEX
194 #define COMPLEX_SPECIFIERS \
196 #define IMAGINARY_SPECIFIERS \
199 #define COMPLEX_SPECIFIERS
200 #define IMAGINARY_SPECIFIERS
203 #define TYPE_SPECIFIERS \
218 case T___builtin_va_list: \
223 #define DECLARATION_START \
228 #define TYPENAME_START \
233 * Allocate an AST node with given size and
234 * initialize all fields with zero.
236 static void *allocate_ast_zero(size_t size)
238 void *res = allocate_ast(size);
239 memset(res, 0, size);
243 static declaration_t *allocate_declaration_zero(void)
245 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
246 declaration->type = type_error_type;
247 declaration->alignment = 0;
252 * Returns the size of a statement node.
254 * @param kind the statement kind
256 static size_t get_statement_struct_size(statement_kind_t kind)
258 static const size_t sizes[] = {
259 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
260 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
261 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
262 [STATEMENT_RETURN] = sizeof(return_statement_t),
263 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
264 [STATEMENT_IF] = sizeof(if_statement_t),
265 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
266 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
267 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
268 [STATEMENT_BREAK] = sizeof(statement_base_t),
269 [STATEMENT_GOTO] = sizeof(goto_statement_t),
270 [STATEMENT_LABEL] = sizeof(label_statement_t),
271 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
272 [STATEMENT_WHILE] = sizeof(while_statement_t),
273 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
274 [STATEMENT_FOR] = sizeof(for_statement_t),
275 [STATEMENT_ASM] = sizeof(asm_statement_t),
276 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
277 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
279 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
280 assert(sizes[kind] != 0);
285 * Returns the size of an expression node.
287 * @param kind the expression kind
289 static size_t get_expression_struct_size(expression_kind_t kind)
291 static const size_t sizes[] = {
292 [EXPR_INVALID] = sizeof(expression_base_t),
293 [EXPR_REFERENCE] = sizeof(reference_expression_t),
294 [EXPR_CONST] = sizeof(const_expression_t),
295 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
296 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
297 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
298 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
299 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
300 [EXPR_CALL] = sizeof(call_expression_t),
301 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
302 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
303 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
304 [EXPR_SELECT] = sizeof(select_expression_t),
305 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
306 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
307 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
308 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
309 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
310 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
311 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
312 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
313 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
314 [EXPR_VA_START] = sizeof(va_start_expression_t),
315 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
316 [EXPR_STATEMENT] = sizeof(statement_expression_t),
318 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
319 return sizes[EXPR_UNARY_FIRST];
321 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
322 return sizes[EXPR_BINARY_FIRST];
324 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
325 assert(sizes[kind] != 0);
330 * Allocate a statement node of given kind and initialize all
333 static statement_t *allocate_statement_zero(statement_kind_t kind)
335 size_t size = get_statement_struct_size(kind);
336 statement_t *res = allocate_ast_zero(size);
338 res->base.kind = kind;
339 res->base.parent = current_parent;
344 * Allocate an expression node of given kind and initialize all
347 static expression_t *allocate_expression_zero(expression_kind_t kind)
349 size_t size = get_expression_struct_size(kind);
350 expression_t *res = allocate_ast_zero(size);
352 res->base.kind = kind;
353 res->base.type = type_error_type;
358 * Creates a new invalid expression.
360 static expression_t *create_invalid_expression(void)
362 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
363 expression->base.source_position = token.source_position;
368 * Creates a new invalid statement.
370 static statement_t *create_invalid_statement(void)
372 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
373 statement->base.source_position = token.source_position;
378 * Allocate a new empty statement.
380 static statement_t *create_empty_statement(void)
382 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
383 statement->base.source_position = token.source_position;
388 * Returns the size of a type node.
390 * @param kind the type kind
392 static size_t get_type_struct_size(type_kind_t kind)
394 static const size_t sizes[] = {
395 [TYPE_ATOMIC] = sizeof(atomic_type_t),
396 [TYPE_COMPLEX] = sizeof(complex_type_t),
397 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
398 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
399 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
400 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
401 [TYPE_ENUM] = sizeof(enum_type_t),
402 [TYPE_FUNCTION] = sizeof(function_type_t),
403 [TYPE_POINTER] = sizeof(pointer_type_t),
404 [TYPE_ARRAY] = sizeof(array_type_t),
405 [TYPE_BUILTIN] = sizeof(builtin_type_t),
406 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
407 [TYPE_TYPEOF] = sizeof(typeof_type_t),
409 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
410 assert(kind <= TYPE_TYPEOF);
411 assert(sizes[kind] != 0);
416 * Allocate a type node of given kind and initialize all
419 * @param kind type kind to allocate
420 * @param source_position the source position of the type definition
422 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
424 size_t size = get_type_struct_size(kind);
425 type_t *res = obstack_alloc(type_obst, size);
426 memset(res, 0, size);
428 res->base.kind = kind;
429 res->base.source_position = *source_position;
434 * Returns the size of an initializer node.
436 * @param kind the initializer kind
438 static size_t get_initializer_size(initializer_kind_t kind)
440 static const size_t sizes[] = {
441 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
442 [INITIALIZER_STRING] = sizeof(initializer_string_t),
443 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
444 [INITIALIZER_LIST] = sizeof(initializer_list_t),
445 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
447 assert(kind < sizeof(sizes) / sizeof(*sizes));
448 assert(sizes[kind] != 0);
453 * Allocate an initializer node of given kind and initialize all
456 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
458 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
465 * Free a type from the type obstack.
467 static void free_type(void *type)
469 obstack_free(type_obst, type);
473 * Returns the index of the top element of the environment stack.
475 static size_t environment_top(void)
477 return ARR_LEN(environment_stack);
481 * Returns the index of the top element of the label stack.
483 static size_t label_top(void)
485 return ARR_LEN(label_stack);
489 * Return the next token.
491 static inline void next_token(void)
493 token = lookahead_buffer[lookahead_bufpos];
494 lookahead_buffer[lookahead_bufpos] = lexer_token;
497 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
500 print_token(stderr, &token);
501 fprintf(stderr, "\n");
506 * Return the next token with a given lookahead.
508 static inline const token_t *look_ahead(int num)
510 assert(num > 0 && num <= MAX_LOOKAHEAD);
511 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
512 return &lookahead_buffer[pos];
516 * Adds a token to the token anchor set (a multi-set).
518 static void add_anchor_token(int token_type)
520 assert(0 <= token_type && token_type < T_LAST_TOKEN);
521 ++token_anchor_set[token_type];
524 static int save_and_reset_anchor_state(int token_type)
526 assert(0 <= token_type && token_type < T_LAST_TOKEN);
527 int count = token_anchor_set[token_type];
528 token_anchor_set[token_type] = 0;
532 static void restore_anchor_state(int token_type, int count)
534 assert(0 <= token_type && token_type < T_LAST_TOKEN);
535 token_anchor_set[token_type] = count;
539 * Remove a token from the token anchor set (a multi-set).
541 static void rem_anchor_token(int token_type)
543 assert(0 <= token_type && token_type < T_LAST_TOKEN);
544 --token_anchor_set[token_type];
547 static bool at_anchor(void)
551 return token_anchor_set[token.type];
555 * Eat tokens until a matching token is found.
557 static void eat_until_matching_token(int type)
561 case '(': end_token = ')'; break;
562 case '{': end_token = '}'; break;
563 case '[': end_token = ']'; break;
564 default: end_token = type; break;
567 unsigned parenthesis_count = 0;
568 unsigned brace_count = 0;
569 unsigned bracket_count = 0;
570 while (token.type != end_token ||
571 parenthesis_count != 0 ||
573 bracket_count != 0) {
574 switch (token.type) {
576 case '(': ++parenthesis_count; break;
577 case '{': ++brace_count; break;
578 case '[': ++bracket_count; break;
581 if (parenthesis_count > 0)
591 if (bracket_count > 0)
594 if (token.type == end_token &&
595 parenthesis_count == 0 &&
609 * Eat input tokens until an anchor is found.
611 static void eat_until_anchor(void)
613 if (token.type == T_EOF)
615 while (token_anchor_set[token.type] == 0) {
616 if (token.type == '(' || token.type == '{' || token.type == '[')
617 eat_until_matching_token(token.type);
618 if (token.type == T_EOF)
624 static void eat_block(void)
626 eat_until_matching_token('{');
627 if (token.type == '}')
632 * eat all token until a ';' is reached or a stop token is found.
634 static void eat_statement(void)
636 eat_until_matching_token(';');
637 if (token.type == ';')
641 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
644 * Report a parse error because an expected token was not found.
647 #if defined __GNUC__ && __GNUC__ >= 4
648 __attribute__((sentinel))
650 void parse_error_expected(const char *message, ...)
652 if (message != NULL) {
653 errorf(HERE, "%s", message);
656 va_start(ap, message);
657 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
662 * Report a type error.
664 static void type_error(const char *msg, const source_position_t *source_position,
667 errorf(source_position, "%s, but found type '%T'", msg, type);
671 * Report an incompatible type.
673 static void type_error_incompatible(const char *msg,
674 const source_position_t *source_position, type_t *type1, type_t *type2)
676 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
681 * Expect the the current token is the expected token.
682 * If not, generate an error, eat the current statement,
683 * and goto the end_error label.
685 #define expect(expected) \
687 if (UNLIKELY(token.type != (expected))) { \
688 parse_error_expected(NULL, (expected), NULL); \
689 add_anchor_token(expected); \
690 eat_until_anchor(); \
691 if (token.type == expected) \
693 rem_anchor_token(expected); \
699 static void set_scope(scope_t *new_scope)
702 scope->last_declaration = last_declaration;
706 last_declaration = new_scope->last_declaration;
710 * Search a symbol in a given namespace and returns its declaration or
711 * NULL if this symbol was not found.
713 static declaration_t *get_declaration(const symbol_t *const symbol,
714 const namespace_t namespc)
716 declaration_t *declaration = symbol->declaration;
717 for( ; declaration != NULL; declaration = declaration->symbol_next) {
718 if (declaration->namespc == namespc)
726 * pushs an environment_entry on the environment stack and links the
727 * corresponding symbol to the new entry
729 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
731 symbol_t *symbol = declaration->symbol;
732 namespace_t namespc = (namespace_t) declaration->namespc;
734 /* replace/add declaration into declaration list of the symbol */
735 declaration_t *iter = symbol->declaration;
737 symbol->declaration = declaration;
739 declaration_t *iter_last = NULL;
740 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
741 /* replace an entry? */
742 if (iter->namespc == namespc) {
743 if (iter_last == NULL) {
744 symbol->declaration = declaration;
746 iter_last->symbol_next = declaration;
748 declaration->symbol_next = iter->symbol_next;
753 assert(iter_last->symbol_next == NULL);
754 iter_last->symbol_next = declaration;
758 /* remember old declaration */
760 entry.symbol = symbol;
761 entry.old_declaration = iter;
762 entry.namespc = (unsigned short) namespc;
763 ARR_APP1(stack_entry_t, *stack_ptr, entry);
766 static void environment_push(declaration_t *declaration)
768 assert(declaration->source_position.input_name != NULL);
769 assert(declaration->parent_scope != NULL);
770 stack_push(&environment_stack, declaration);
774 * Push a declaration of the label stack.
776 * @param declaration the declaration
778 static void label_push(declaration_t *declaration)
780 declaration->parent_scope = ¤t_function->scope;
781 stack_push(&label_stack, declaration);
785 * pops symbols from the environment stack until @p new_top is the top element
787 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
789 stack_entry_t *stack = *stack_ptr;
790 size_t top = ARR_LEN(stack);
793 assert(new_top <= top);
797 for(i = top; i > new_top; --i) {
798 stack_entry_t *entry = &stack[i - 1];
800 declaration_t *old_declaration = entry->old_declaration;
801 symbol_t *symbol = entry->symbol;
802 namespace_t namespc = (namespace_t)entry->namespc;
804 /* replace/remove declaration */
805 declaration_t *declaration = symbol->declaration;
806 assert(declaration != NULL);
807 if (declaration->namespc == namespc) {
808 if (old_declaration == NULL) {
809 symbol->declaration = declaration->symbol_next;
811 symbol->declaration = old_declaration;
814 declaration_t *iter_last = declaration;
815 declaration_t *iter = declaration->symbol_next;
816 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
817 /* replace an entry? */
818 if (iter->namespc == namespc) {
819 assert(iter_last != NULL);
820 iter_last->symbol_next = old_declaration;
821 if (old_declaration != NULL) {
822 old_declaration->symbol_next = iter->symbol_next;
827 assert(iter != NULL);
831 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
834 static void environment_pop_to(size_t new_top)
836 stack_pop_to(&environment_stack, new_top);
840 * Pop all entries on the label stack until the new_top
843 * @param new_top the new stack top
845 static void label_pop_to(size_t new_top)
847 stack_pop_to(&label_stack, new_top);
851 static atomic_type_kind_t get_rank(const type_t *type)
853 assert(!is_typeref(type));
854 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
855 * and esp. footnote 108). However we can't fold constants (yet), so we
856 * can't decide whether unsigned int is possible, while int always works.
857 * (unsigned int would be preferable when possible... for stuff like
858 * struct { enum { ... } bla : 4; } ) */
859 if (type->kind == TYPE_ENUM)
860 return ATOMIC_TYPE_INT;
862 assert(type->kind == TYPE_ATOMIC);
863 return type->atomic.akind;
866 static type_t *promote_integer(type_t *type)
868 if (type->kind == TYPE_BITFIELD)
869 type = type->bitfield.base_type;
871 if (get_rank(type) < ATOMIC_TYPE_INT)
878 * Create a cast expression.
880 * @param expression the expression to cast
881 * @param dest_type the destination type
883 static expression_t *create_cast_expression(expression_t *expression,
886 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
888 cast->unary.value = expression;
889 cast->base.type = dest_type;
895 * Check if a given expression represents the 0 pointer constant.
897 static bool is_null_pointer_constant(const expression_t *expression)
899 /* skip void* cast */
900 if (expression->kind == EXPR_UNARY_CAST
901 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
902 expression = expression->unary.value;
905 /* TODO: not correct yet, should be any constant integer expression
906 * which evaluates to 0 */
907 if (expression->kind != EXPR_CONST)
910 type_t *const type = skip_typeref(expression->base.type);
911 if (!is_type_integer(type))
914 return expression->conste.v.int_value == 0;
918 * Create an implicit cast expression.
920 * @param expression the expression to cast
921 * @param dest_type the destination type
923 static expression_t *create_implicit_cast(expression_t *expression,
926 type_t *const source_type = expression->base.type;
928 if (source_type == dest_type)
931 return create_cast_expression(expression, dest_type);
934 typedef enum assign_error_t {
936 ASSIGN_ERROR_INCOMPATIBLE,
937 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
938 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
939 ASSIGN_WARNING_POINTER_FROM_INT,
940 ASSIGN_WARNING_INT_FROM_POINTER
943 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
944 const expression_t *const right,
946 const source_position_t *source_position)
948 type_t *const orig_type_right = right->base.type;
949 type_t *const type_left = skip_typeref(orig_type_left);
950 type_t *const type_right = skip_typeref(orig_type_right);
955 case ASSIGN_ERROR_INCOMPATIBLE:
956 errorf(source_position,
957 "destination type '%T' in %s is incompatible with type '%T'",
958 orig_type_left, context, orig_type_right);
961 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
962 type_t *points_to_left
963 = skip_typeref(type_left->pointer.points_to);
964 type_t *points_to_right
965 = skip_typeref(type_right->pointer.points_to);
967 /* the left type has all qualifiers from the right type */
968 unsigned missing_qualifiers
969 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
970 warningf(source_position,
971 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type",
972 orig_type_left, context, orig_type_right, missing_qualifiers);
976 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
977 warningf(source_position,
978 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
979 orig_type_left, context, right, orig_type_right);
982 case ASSIGN_WARNING_POINTER_FROM_INT:
983 warningf(source_position,
984 "%s makes integer '%T' from pointer '%T' without a cast",
985 context, orig_type_left, orig_type_right);
988 case ASSIGN_WARNING_INT_FROM_POINTER:
989 warningf(source_position,
990 "%s makes integer '%T' from pointer '%T' without a cast",
991 context, orig_type_left, orig_type_right);
995 panic("invalid error value");
999 /** Implements the rules from § 6.5.16.1 */
1000 static assign_error_t semantic_assign(type_t *orig_type_left,
1001 const expression_t *const right)
1003 type_t *const orig_type_right = right->base.type;
1004 type_t *const type_left = skip_typeref(orig_type_left);
1005 type_t *const type_right = skip_typeref(orig_type_right);
1007 if (is_type_pointer(type_left)) {
1008 if (is_null_pointer_constant(right)) {
1009 return ASSIGN_SUCCESS;
1010 } else if (is_type_pointer(type_right)) {
1011 type_t *points_to_left
1012 = skip_typeref(type_left->pointer.points_to);
1013 type_t *points_to_right
1014 = skip_typeref(type_right->pointer.points_to);
1016 /* the left type has all qualifiers from the right type */
1017 unsigned missing_qualifiers
1018 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1019 if (missing_qualifiers != 0) {
1020 return ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1023 points_to_left = get_unqualified_type(points_to_left);
1024 points_to_right = get_unqualified_type(points_to_right);
1026 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1027 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1028 return ASSIGN_SUCCESS;
1031 if (!types_compatible(points_to_left, points_to_right)) {
1032 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1035 return ASSIGN_SUCCESS;
1036 } else if (is_type_integer(type_right)) {
1037 return ASSIGN_WARNING_POINTER_FROM_INT;
1039 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1040 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1041 && is_type_pointer(type_right))) {
1042 return ASSIGN_SUCCESS;
1043 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1044 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1045 type_t *const unqual_type_left = get_unqualified_type(type_left);
1046 type_t *const unqual_type_right = get_unqualified_type(type_right);
1047 if (types_compatible(unqual_type_left, unqual_type_right)) {
1048 return ASSIGN_SUCCESS;
1050 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1051 return ASSIGN_WARNING_INT_FROM_POINTER;
1054 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1055 return ASSIGN_SUCCESS;
1057 return ASSIGN_ERROR_INCOMPATIBLE;
1060 static expression_t *parse_constant_expression(void)
1062 /* start parsing at precedence 7 (conditional expression) */
1063 expression_t *result = parse_sub_expression(7);
1065 if (!is_constant_expression(result)) {
1066 errorf(&result->base.source_position,
1067 "expression '%E' is not constant\n", result);
1073 static expression_t *parse_assignment_expression(void)
1075 /* start parsing at precedence 2 (assignment expression) */
1076 return parse_sub_expression(2);
1079 static type_t *make_global_typedef(const char *name, type_t *type)
1081 symbol_t *const symbol = symbol_table_insert(name);
1083 declaration_t *const declaration = allocate_declaration_zero();
1084 declaration->namespc = NAMESPACE_NORMAL;
1085 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1086 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1087 declaration->type = type;
1088 declaration->symbol = symbol;
1089 declaration->source_position = builtin_source_position;
1091 record_declaration(declaration);
1093 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1094 typedef_type->typedeft.declaration = declaration;
1096 return typedef_type;
1099 static string_t parse_string_literals(void)
1101 assert(token.type == T_STRING_LITERAL);
1102 string_t result = token.v.string;
1106 while (token.type == T_STRING_LITERAL) {
1107 result = concat_strings(&result, &token.v.string);
1114 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1115 [GNU_AK_CONST] = "const",
1116 [GNU_AK_VOLATILE] = "volatile",
1117 [GNU_AK_CDECL] = "cdecl",
1118 [GNU_AK_STDCALL] = "stdcall",
1119 [GNU_AK_FASTCALL] = "fastcall",
1120 [GNU_AK_DEPRECATED] = "deprecated",
1121 [GNU_AK_NOINLINE] = "noinline",
1122 [GNU_AK_NORETURN] = "noreturn",
1123 [GNU_AK_NAKED] = "naked",
1124 [GNU_AK_PURE] = "pure",
1125 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1126 [GNU_AK_MALLOC] = "malloc",
1127 [GNU_AK_WEAK] = "weak",
1128 [GNU_AK_CONSTRUCTOR] = "constructor",
1129 [GNU_AK_DESTRUCTOR] = "destructor",
1130 [GNU_AK_NOTHROW] = "nothrow",
1131 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1132 [GNU_AK_COMMON] = "common",
1133 [GNU_AK_NOCOMMON] = "nocommon",
1134 [GNU_AK_PACKED] = "packed",
1135 [GNU_AK_SHARED] = "shared",
1136 [GNU_AK_NOTSHARED] = "notshared",
1137 [GNU_AK_USED] = "used",
1138 [GNU_AK_UNUSED] = "unused",
1139 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1140 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1141 [GNU_AK_LONGCALL] = "longcall",
1142 [GNU_AK_SHORTCALL] = "shortcall",
1143 [GNU_AK_LONG_CALL] = "long_call",
1144 [GNU_AK_SHORT_CALL] = "short_call",
1145 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1146 [GNU_AK_INTERRUPT] = "interrupt",
1147 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1148 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1149 [GNU_AK_NESTING] = "nesting",
1150 [GNU_AK_NEAR] = "near",
1151 [GNU_AK_FAR] = "far",
1152 [GNU_AK_SIGNAL] = "signal",
1153 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1154 [GNU_AK_TINY_DATA] = "tiny_data",
1155 [GNU_AK_SAVEALL] = "saveall",
1156 [GNU_AK_FLATTEN] = "flatten",
1157 [GNU_AK_SSEREGPARM] = "sseregparm",
1158 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1159 [GNU_AK_RETURN_TWICE] = "return_twice",
1160 [GNU_AK_MAY_ALIAS] = "may_alias",
1161 [GNU_AK_MS_STRUCT] = "ms_struct",
1162 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1163 [GNU_AK_DLLIMPORT] = "dllimport",
1164 [GNU_AK_DLLEXPORT] = "dllexport",
1165 [GNU_AK_ALIGNED] = "aligned",
1166 [GNU_AK_ALIAS] = "alias",
1167 [GNU_AK_SECTION] = "section",
1168 [GNU_AK_FORMAT] = "format",
1169 [GNU_AK_FORMAT_ARG] = "format_arg",
1170 [GNU_AK_WEAKREF] = "weakref",
1171 [GNU_AK_NONNULL] = "nonnull",
1172 [GNU_AK_TLS_MODEL] = "tls_model",
1173 [GNU_AK_VISIBILITY] = "visibility",
1174 [GNU_AK_REGPARM] = "regparm",
1175 [GNU_AK_MODE] = "mode",
1176 [GNU_AK_MODEL] = "model",
1177 [GNU_AK_TRAP_EXIT] = "trap_exit",
1178 [GNU_AK_SP_SWITCH] = "sp_switch",
1179 [GNU_AK_SENTINEL] = "sentinel"
1183 * compare two string, ignoring double underscores on the second.
1185 static int strcmp_underscore(const char *s1, const char *s2)
1187 if (s2[0] == '_' && s2[1] == '_') {
1188 size_t len2 = strlen(s2);
1189 size_t len1 = strlen(s1);
1190 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1191 return strncmp(s1, s2+2, len2-4);
1195 return strcmp(s1, s2);
1199 * Allocate a new gnu temporal attribute.
1201 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1203 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1204 attribute->kind = kind;
1205 attribute->next = NULL;
1206 attribute->invalid = false;
1207 attribute->have_arguments = false;
1213 * parse one constant expression argument.
1215 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1217 expression_t *expression;
1218 add_anchor_token(')');
1219 expression = parse_constant_expression();
1220 rem_anchor_token(')');
1222 attribute->u.argument = fold_constant(expression);
1225 attribute->invalid = true;
1229 * parse a list of constant expressions arguments.
1231 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1233 argument_list_t **list = &attribute->u.arguments;
1234 argument_list_t *entry;
1235 expression_t *expression;
1236 add_anchor_token(')');
1237 add_anchor_token(',');
1239 expression = parse_constant_expression();
1240 entry = obstack_alloc(&temp_obst, sizeof(entry));
1241 entry->argument = fold_constant(expression);
1244 list = &entry->next;
1245 if (token.type != ',')
1249 rem_anchor_token(',');
1250 rem_anchor_token(')');
1254 attribute->invalid = true;
1258 * parse one string literal argument.
1260 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1263 add_anchor_token('(');
1264 if (token.type != T_STRING_LITERAL) {
1265 parse_error_expected("while parsing attribute directive",
1266 T_STRING_LITERAL, NULL);
1269 *string = parse_string_literals();
1270 rem_anchor_token('(');
1274 attribute->invalid = true;
1278 * parse one tls model.
1280 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1282 static const char *const tls_models[] = {
1288 string_t string = { NULL, 0 };
1289 parse_gnu_attribute_string_arg(attribute, &string);
1290 if (string.begin != NULL) {
1291 for(size_t i = 0; i < 4; ++i) {
1292 if (strcmp(tls_models[i], string.begin) == 0) {
1293 attribute->u.value = i;
1297 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1299 attribute->invalid = true;
1303 * parse one tls model.
1305 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1307 static const char *const visibilities[] = {
1313 string_t string = { NULL, 0 };
1314 parse_gnu_attribute_string_arg(attribute, &string);
1315 if (string.begin != NULL) {
1316 for(size_t i = 0; i < 4; ++i) {
1317 if (strcmp(visibilities[i], string.begin) == 0) {
1318 attribute->u.value = i;
1322 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1324 attribute->invalid = true;
1328 * parse one (code) model.
1330 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1332 static const char *const visibilities[] = {
1337 string_t string = { NULL, 0 };
1338 parse_gnu_attribute_string_arg(attribute, &string);
1339 if (string.begin != NULL) {
1340 for(int i = 0; i < 3; ++i) {
1341 if (strcmp(visibilities[i], string.begin) == 0) {
1342 attribute->u.value = i;
1346 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1348 attribute->invalid = true;
1351 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1353 /* TODO: find out what is allowed here... */
1355 /* at least: byte, word, pointer, list of machine modes
1356 * __XXX___ is interpreted as XXX */
1357 add_anchor_token(')');
1359 if (token.type != T_IDENTIFIER) {
1360 expect(T_IDENTIFIER);
1363 /* This isn't really correct, the backend should provide a list of machine
1364 * specific modes (according to gcc philosophy that is...) */
1365 const char *symbol_str = token.v.symbol->string;
1366 if (strcmp_underscore("QI", symbol_str) == 0 ||
1367 strcmp_underscore("byte", symbol_str) == 0) {
1368 attribute->u.akind = ATOMIC_TYPE_CHAR;
1369 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1370 attribute->u.akind = ATOMIC_TYPE_SHORT;
1371 } else if (strcmp_underscore("SI", symbol_str) == 0
1372 || strcmp_underscore("word", symbol_str) == 0
1373 || strcmp_underscore("pointer", symbol_str) == 0) {
1374 attribute->u.akind = ATOMIC_TYPE_INT;
1375 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1376 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1378 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1379 attribute->invalid = true;
1383 rem_anchor_token(')');
1387 attribute->invalid = true;
1391 * parse one interrupt argument.
1393 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1395 static const char *const interrupts[] = {
1402 string_t string = { NULL, 0 };
1403 parse_gnu_attribute_string_arg(attribute, &string);
1404 if (string.begin != NULL) {
1405 for(size_t i = 0; i < 5; ++i) {
1406 if (strcmp(interrupts[i], string.begin) == 0) {
1407 attribute->u.value = i;
1411 errorf(HERE, "'%s' is not an interrupt", string.begin);
1413 attribute->invalid = true;
1417 * parse ( identifier, const expression, const expression )
1419 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1421 static const char *const format_names[] = {
1429 if (token.type != T_IDENTIFIER) {
1430 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1433 const char *name = token.v.symbol->string;
1434 for(i = 0; i < 4; ++i) {
1435 if (strcmp_underscore(format_names[i], name) == 0)
1439 if (warning.attribute)
1440 warningf(HERE, "'%s' is an unrecognized format function type", name);
1445 add_anchor_token(')');
1446 add_anchor_token(',');
1447 parse_constant_expression();
1448 rem_anchor_token(',');
1449 rem_anchor_token('(');
1452 add_anchor_token(')');
1453 parse_constant_expression();
1454 rem_anchor_token('(');
1458 attribute->u.value = true;
1461 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1463 if (!attribute->have_arguments)
1466 /* should have no arguments */
1467 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1468 eat_until_matching_token('(');
1469 /* we have already consumed '(', so we stop before ')', eat it */
1471 attribute->invalid = true;
1475 * Parse one GNU attribute.
1477 * Note that attribute names can be specified WITH or WITHOUT
1478 * double underscores, ie const or __const__.
1480 * The following attributes are parsed without arguments
1505 * no_instrument_function
1506 * warn_unused_result
1523 * externally_visible
1531 * The following attributes are parsed with arguments
1532 * aligned( const expression )
1533 * alias( string literal )
1534 * section( string literal )
1535 * format( identifier, const expression, const expression )
1536 * format_arg( const expression )
1537 * tls_model( string literal )
1538 * visibility( string literal )
1539 * regparm( const expression )
1540 * model( string leteral )
1541 * trap_exit( const expression )
1542 * sp_switch( string literal )
1544 * The following attributes might have arguments
1545 * weak_ref( string literal )
1546 * non_null( const expression // ',' )
1547 * interrupt( string literal )
1548 * sentinel( constant expression )
1550 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1552 gnu_attribute_t *head = *attributes;
1553 gnu_attribute_t *last = *attributes;
1554 decl_modifiers_t modifiers = 0;
1555 gnu_attribute_t *attribute;
1557 eat(T___attribute__);
1561 if (token.type != ')') {
1562 /* find the end of the list */
1564 while (last->next != NULL)
1568 /* non-empty attribute list */
1571 if (token.type == T_const) {
1573 } else if (token.type == T_volatile) {
1575 } else if (token.type == T_cdecl) {
1576 /* __attribute__((cdecl)), WITH ms mode */
1578 } else if (token.type == T_IDENTIFIER) {
1579 const symbol_t *sym = token.v.symbol;
1582 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1589 for(i = 0; i < GNU_AK_LAST; ++i) {
1590 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1593 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1596 if (kind == GNU_AK_LAST) {
1597 if (warning.attribute)
1598 warningf(HERE, "'%s' attribute directive ignored", name);
1600 /* skip possible arguments */
1601 if (token.type == '(') {
1602 eat_until_matching_token(')');
1605 /* check for arguments */
1606 attribute = allocate_gnu_attribute(kind);
1607 if (token.type == '(') {
1609 if (token.type == ')') {
1610 /* empty args are allowed */
1613 attribute->have_arguments = true;
1618 case GNU_AK_VOLATILE:
1623 case GNU_AK_NOCOMMON:
1625 case GNU_AK_NOTSHARED:
1626 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1627 case GNU_AK_WARN_UNUSED_RESULT:
1628 case GNU_AK_LONGCALL:
1629 case GNU_AK_SHORTCALL:
1630 case GNU_AK_LONG_CALL:
1631 case GNU_AK_SHORT_CALL:
1632 case GNU_AK_FUNCTION_VECTOR:
1633 case GNU_AK_INTERRUPT_HANDLER:
1634 case GNU_AK_NMI_HANDLER:
1635 case GNU_AK_NESTING:
1639 case GNU_AK_EIGTHBIT_DATA:
1640 case GNU_AK_TINY_DATA:
1641 case GNU_AK_SAVEALL:
1642 case GNU_AK_FLATTEN:
1643 case GNU_AK_SSEREGPARM:
1644 case GNU_AK_EXTERNALLY_VISIBLE:
1645 case GNU_AK_RETURN_TWICE:
1646 case GNU_AK_MAY_ALIAS:
1647 case GNU_AK_MS_STRUCT:
1648 case GNU_AK_GCC_STRUCT:
1651 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1652 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1653 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1654 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1655 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1656 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1657 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1658 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1659 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1660 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1661 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1662 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1663 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1664 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1665 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1666 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1667 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1669 case GNU_AK_ALIGNED:
1670 /* __align__ may be used without an argument */
1671 if (attribute->have_arguments) {
1672 parse_gnu_attribute_const_arg(attribute);
1676 case GNU_AK_FORMAT_ARG:
1677 case GNU_AK_REGPARM:
1678 case GNU_AK_TRAP_EXIT:
1679 if (!attribute->have_arguments) {
1680 /* should have arguments */
1681 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1682 attribute->invalid = true;
1684 parse_gnu_attribute_const_arg(attribute);
1687 case GNU_AK_SECTION:
1688 case GNU_AK_SP_SWITCH:
1689 if (!attribute->have_arguments) {
1690 /* should have arguments */
1691 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1692 attribute->invalid = true;
1694 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1697 if (!attribute->have_arguments) {
1698 /* should have arguments */
1699 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1700 attribute->invalid = true;
1702 parse_gnu_attribute_format_args(attribute);
1704 case GNU_AK_WEAKREF:
1705 /* may have one string argument */
1706 if (attribute->have_arguments)
1707 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1709 case GNU_AK_NONNULL:
1710 if (attribute->have_arguments)
1711 parse_gnu_attribute_const_arg_list(attribute);
1713 case GNU_AK_TLS_MODEL:
1714 if (!attribute->have_arguments) {
1715 /* should have arguments */
1716 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1718 parse_gnu_attribute_tls_model_arg(attribute);
1720 case GNU_AK_VISIBILITY:
1721 if (!attribute->have_arguments) {
1722 /* should have arguments */
1723 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1725 parse_gnu_attribute_visibility_arg(attribute);
1728 if (!attribute->have_arguments) {
1729 /* should have arguments */
1730 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1732 parse_gnu_attribute_model_arg(attribute);
1736 if (!attribute->have_arguments) {
1737 /* should have arguments */
1738 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1740 parse_gnu_attribute_mode_arg(attribute);
1743 case GNU_AK_INTERRUPT:
1744 /* may have one string argument */
1745 if (attribute->have_arguments)
1746 parse_gnu_attribute_interrupt_arg(attribute);
1748 case GNU_AK_SENTINEL:
1749 /* may have one string argument */
1750 if (attribute->have_arguments)
1751 parse_gnu_attribute_const_arg(attribute);
1754 /* already handled */
1758 check_no_argument(attribute, name);
1761 if (attribute != NULL) {
1763 last->next = attribute;
1766 head = last = attribute;
1770 if (token.type != ',')
1784 * Parse GNU attributes.
1786 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1788 decl_modifiers_t modifiers = 0;
1791 switch(token.type) {
1792 case T___attribute__:
1793 modifiers |= parse_gnu_attribute(attributes);
1799 if (token.type != T_STRING_LITERAL) {
1800 parse_error_expected("while parsing assembler attribute",
1801 T_STRING_LITERAL, NULL);
1802 eat_until_matching_token('(');
1805 parse_string_literals();
1810 case T_cdecl: modifiers |= DM_CDECL; break;
1811 case T__fastcall: modifiers |= DM_FASTCALL; break;
1812 case T__stdcall: modifiers |= DM_STDCALL; break;
1815 /* TODO record modifier */
1816 warningf(HERE, "Ignoring declaration modifier %K", &token);
1820 default: return modifiers;
1827 static designator_t *parse_designation(void)
1829 designator_t *result = NULL;
1830 designator_t *last = NULL;
1833 designator_t *designator;
1834 switch(token.type) {
1836 designator = allocate_ast_zero(sizeof(designator[0]));
1837 designator->source_position = token.source_position;
1839 add_anchor_token(']');
1840 designator->array_index = parse_constant_expression();
1841 rem_anchor_token(']');
1845 designator = allocate_ast_zero(sizeof(designator[0]));
1846 designator->source_position = token.source_position;
1848 if (token.type != T_IDENTIFIER) {
1849 parse_error_expected("while parsing designator",
1850 T_IDENTIFIER, NULL);
1853 designator->symbol = token.v.symbol;
1861 assert(designator != NULL);
1863 last->next = designator;
1865 result = designator;
1873 static initializer_t *initializer_from_string(array_type_t *type,
1874 const string_t *const string)
1876 /* TODO: check len vs. size of array type */
1879 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1880 initializer->string.string = *string;
1885 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1886 wide_string_t *const string)
1888 /* TODO: check len vs. size of array type */
1891 initializer_t *const initializer =
1892 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1893 initializer->wide_string.string = *string;
1899 * Build an initializer from a given expression.
1901 static initializer_t *initializer_from_expression(type_t *orig_type,
1902 expression_t *expression)
1904 /* TODO check that expression is a constant expression */
1906 /* § 6.7.8.14/15 char array may be initialized by string literals */
1907 type_t *type = skip_typeref(orig_type);
1908 type_t *expr_type_orig = expression->base.type;
1909 type_t *expr_type = skip_typeref(expr_type_orig);
1910 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1911 array_type_t *const array_type = &type->array;
1912 type_t *const element_type = skip_typeref(array_type->element_type);
1914 if (element_type->kind == TYPE_ATOMIC) {
1915 atomic_type_kind_t akind = element_type->atomic.akind;
1916 switch (expression->kind) {
1917 case EXPR_STRING_LITERAL:
1918 if (akind == ATOMIC_TYPE_CHAR
1919 || akind == ATOMIC_TYPE_SCHAR
1920 || akind == ATOMIC_TYPE_UCHAR) {
1921 return initializer_from_string(array_type,
1922 &expression->string.value);
1925 case EXPR_WIDE_STRING_LITERAL: {
1926 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1927 if (get_unqualified_type(element_type) == bare_wchar_type) {
1928 return initializer_from_wide_string(array_type,
1929 &expression->wide_string.value);
1939 assign_error_t error = semantic_assign(type, expression);
1940 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1942 report_assign_error(error, type, expression, "initializer",
1943 &expression->base.source_position);
1945 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1946 result->value.value = create_implicit_cast(expression, type);
1952 * Checks if a given expression can be used as an constant initializer.
1954 static bool is_initializer_constant(const expression_t *expression)
1956 return is_constant_expression(expression)
1957 || is_address_constant(expression);
1961 * Parses an scalar initializer.
1963 * § 6.7.8.11; eat {} without warning
1965 static initializer_t *parse_scalar_initializer(type_t *type,
1966 bool must_be_constant)
1968 /* there might be extra {} hierarchies */
1970 if (token.type == '{') {
1971 warningf(HERE, "extra curly braces around scalar initializer");
1975 } while (token.type == '{');
1978 expression_t *expression = parse_assignment_expression();
1979 if (must_be_constant && !is_initializer_constant(expression)) {
1980 errorf(&expression->base.source_position,
1981 "Initialisation expression '%E' is not constant\n",
1985 initializer_t *initializer = initializer_from_expression(type, expression);
1987 if (initializer == NULL) {
1988 errorf(&expression->base.source_position,
1989 "expression '%E' (type '%T') doesn't match expected type '%T'",
1990 expression, expression->base.type, type);
1995 bool additional_warning_displayed = false;
1996 while (braces > 0) {
1997 if (token.type == ',') {
2000 if (token.type != '}') {
2001 if (!additional_warning_displayed) {
2002 warningf(HERE, "additional elements in scalar initializer");
2003 additional_warning_displayed = true;
2014 * An entry in the type path.
2016 typedef struct type_path_entry_t type_path_entry_t;
2017 struct type_path_entry_t {
2018 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2020 size_t index; /**< For array types: the current index. */
2021 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2026 * A type path expression a position inside compound or array types.
2028 typedef struct type_path_t type_path_t;
2029 struct type_path_t {
2030 type_path_entry_t *path; /**< An flexible array containing the current path. */
2031 type_t *top_type; /**< type of the element the path points */
2032 size_t max_index; /**< largest index in outermost array */
2036 * Prints a type path for debugging.
2038 static __attribute__((unused)) void debug_print_type_path(
2039 const type_path_t *path)
2041 size_t len = ARR_LEN(path->path);
2043 for(size_t i = 0; i < len; ++i) {
2044 const type_path_entry_t *entry = & path->path[i];
2046 type_t *type = skip_typeref(entry->type);
2047 if (is_type_compound(type)) {
2048 /* in gcc mode structs can have no members */
2049 if (entry->v.compound_entry == NULL) {
2053 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2054 } else if (is_type_array(type)) {
2055 fprintf(stderr, "[%zu]", entry->v.index);
2057 fprintf(stderr, "-INVALID-");
2060 if (path->top_type != NULL) {
2061 fprintf(stderr, " (");
2062 print_type(path->top_type);
2063 fprintf(stderr, ")");
2068 * Return the top type path entry, ie. in a path
2069 * (type).a.b returns the b.
2071 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2073 size_t len = ARR_LEN(path->path);
2075 return &path->path[len-1];
2079 * Enlarge the type path by an (empty) element.
2081 static type_path_entry_t *append_to_type_path(type_path_t *path)
2083 size_t len = ARR_LEN(path->path);
2084 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2086 type_path_entry_t *result = & path->path[len];
2087 memset(result, 0, sizeof(result[0]));
2092 * Descending into a sub-type. Enter the scope of the current
2095 static void descend_into_subtype(type_path_t *path)
2097 type_t *orig_top_type = path->top_type;
2098 type_t *top_type = skip_typeref(orig_top_type);
2100 assert(is_type_compound(top_type) || is_type_array(top_type));
2102 type_path_entry_t *top = append_to_type_path(path);
2103 top->type = top_type;
2105 if (is_type_compound(top_type)) {
2106 declaration_t *declaration = top_type->compound.declaration;
2107 declaration_t *entry = declaration->scope.declarations;
2108 top->v.compound_entry = entry;
2110 if (entry != NULL) {
2111 path->top_type = entry->type;
2113 path->top_type = NULL;
2116 assert(is_type_array(top_type));
2119 path->top_type = top_type->array.element_type;
2124 * Pop an entry from the given type path, ie. returning from
2125 * (type).a.b to (type).a
2127 static void ascend_from_subtype(type_path_t *path)
2129 type_path_entry_t *top = get_type_path_top(path);
2131 path->top_type = top->type;
2133 size_t len = ARR_LEN(path->path);
2134 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2138 * Pop entries from the given type path until the given
2139 * path level is reached.
2141 static void ascend_to(type_path_t *path, size_t top_path_level)
2143 size_t len = ARR_LEN(path->path);
2145 while (len > top_path_level) {
2146 ascend_from_subtype(path);
2147 len = ARR_LEN(path->path);
2151 static bool walk_designator(type_path_t *path, const designator_t *designator,
2152 bool used_in_offsetof)
2154 for( ; designator != NULL; designator = designator->next) {
2155 type_path_entry_t *top = get_type_path_top(path);
2156 type_t *orig_type = top->type;
2158 type_t *type = skip_typeref(orig_type);
2160 if (designator->symbol != NULL) {
2161 symbol_t *symbol = designator->symbol;
2162 if (!is_type_compound(type)) {
2163 if (is_type_valid(type)) {
2164 errorf(&designator->source_position,
2165 "'.%Y' designator used for non-compound type '%T'",
2171 declaration_t *declaration = type->compound.declaration;
2172 declaration_t *iter = declaration->scope.declarations;
2173 for( ; iter != NULL; iter = iter->next) {
2174 if (iter->symbol == symbol) {
2179 errorf(&designator->source_position,
2180 "'%T' has no member named '%Y'", orig_type, symbol);
2183 if (used_in_offsetof) {
2184 type_t *real_type = skip_typeref(iter->type);
2185 if (real_type->kind == TYPE_BITFIELD) {
2186 errorf(&designator->source_position,
2187 "offsetof designator '%Y' may not specify bitfield",
2193 top->type = orig_type;
2194 top->v.compound_entry = iter;
2195 orig_type = iter->type;
2197 expression_t *array_index = designator->array_index;
2198 assert(designator->array_index != NULL);
2200 if (!is_type_array(type)) {
2201 if (is_type_valid(type)) {
2202 errorf(&designator->source_position,
2203 "[%E] designator used for non-array type '%T'",
2204 array_index, orig_type);
2208 if (!is_type_valid(array_index->base.type)) {
2212 long index = fold_constant(array_index);
2213 if (!used_in_offsetof) {
2215 errorf(&designator->source_position,
2216 "array index [%E] must be positive", array_index);
2219 if (type->array.size_constant == true) {
2220 long array_size = type->array.size;
2221 if (index >= array_size) {
2222 errorf(&designator->source_position,
2223 "designator [%E] (%d) exceeds array size %d",
2224 array_index, index, array_size);
2230 top->type = orig_type;
2231 top->v.index = (size_t) index;
2232 orig_type = type->array.element_type;
2234 path->top_type = orig_type;
2236 if (designator->next != NULL) {
2237 descend_into_subtype(path);
2246 static void advance_current_object(type_path_t *path, size_t top_path_level)
2248 type_path_entry_t *top = get_type_path_top(path);
2250 type_t *type = skip_typeref(top->type);
2251 if (is_type_union(type)) {
2252 /* in unions only the first element is initialized */
2253 top->v.compound_entry = NULL;
2254 } else if (is_type_struct(type)) {
2255 declaration_t *entry = top->v.compound_entry;
2257 entry = entry->next;
2258 top->v.compound_entry = entry;
2259 if (entry != NULL) {
2260 path->top_type = entry->type;
2264 assert(is_type_array(type));
2268 if (!type->array.size_constant || top->v.index < type->array.size) {
2273 /* we're past the last member of the current sub-aggregate, try if we
2274 * can ascend in the type hierarchy and continue with another subobject */
2275 size_t len = ARR_LEN(path->path);
2277 if (len > top_path_level) {
2278 ascend_from_subtype(path);
2279 advance_current_object(path, top_path_level);
2281 path->top_type = NULL;
2286 * skip until token is found.
2288 static void skip_until(int type)
2290 while (token.type != type) {
2291 if (token.type == T_EOF)
2298 * skip any {...} blocks until a closing bracket is reached.
2300 static void skip_initializers(void)
2302 if (token.type == '{')
2305 while (token.type != '}') {
2306 if (token.type == T_EOF)
2308 if (token.type == '{') {
2316 static initializer_t *create_empty_initializer(void)
2318 static initializer_t empty_initializer
2319 = { .list = { { INITIALIZER_LIST }, 0 } };
2320 return &empty_initializer;
2324 * Parse a part of an initialiser for a struct or union,
2326 static initializer_t *parse_sub_initializer(type_path_t *path,
2327 type_t *outer_type, size_t top_path_level,
2328 parse_initializer_env_t *env)
2330 if (token.type == '}') {
2331 /* empty initializer */
2332 return create_empty_initializer();
2335 type_t *orig_type = path->top_type;
2336 type_t *type = NULL;
2338 if (orig_type == NULL) {
2339 /* We are initializing an empty compound. */
2341 type = skip_typeref(orig_type);
2343 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2344 * initializers in this case. */
2345 if (!is_type_valid(type)) {
2346 skip_initializers();
2347 return create_empty_initializer();
2351 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2354 designator_t *designator = NULL;
2355 if (token.type == '.' || token.type == '[') {
2356 designator = parse_designation();
2357 goto finish_designator;
2358 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2359 /* GNU-style designator ("identifier: value") */
2360 designator = allocate_ast_zero(sizeof(designator[0]));
2361 designator->source_position = token.source_position;
2362 designator->symbol = token.v.symbol;
2367 /* reset path to toplevel, evaluate designator from there */
2368 ascend_to(path, top_path_level);
2369 if (!walk_designator(path, designator, false)) {
2370 /* can't continue after designation error */
2374 initializer_t *designator_initializer
2375 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2376 designator_initializer->designator.designator = designator;
2377 ARR_APP1(initializer_t*, initializers, designator_initializer);
2379 orig_type = path->top_type;
2380 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2385 if (token.type == '{') {
2386 if (type != NULL && is_type_scalar(type)) {
2387 sub = parse_scalar_initializer(type, env->must_be_constant);
2391 if (env->declaration != NULL) {
2392 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2393 env->declaration->symbol);
2395 errorf(HERE, "extra brace group at end of initializer");
2398 descend_into_subtype(path);
2400 add_anchor_token('}');
2401 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2403 rem_anchor_token('}');
2406 ascend_from_subtype(path);
2410 goto error_parse_next;
2414 /* must be an expression */
2415 expression_t *expression = parse_assignment_expression();
2417 if (env->must_be_constant && !is_initializer_constant(expression)) {
2418 errorf(&expression->base.source_position,
2419 "Initialisation expression '%E' is not constant\n",
2424 /* we are already outside, ... */
2428 /* handle { "string" } special case */
2429 if ((expression->kind == EXPR_STRING_LITERAL
2430 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2431 && outer_type != NULL) {
2432 sub = initializer_from_expression(outer_type, expression);
2434 if (token.type == ',') {
2437 if (token.type != '}') {
2438 warningf(HERE, "excessive elements in initializer for type '%T'",
2441 /* TODO: eat , ... */
2446 /* descend into subtypes until expression matches type */
2448 orig_type = path->top_type;
2449 type = skip_typeref(orig_type);
2451 sub = initializer_from_expression(orig_type, expression);
2455 if (!is_type_valid(type)) {
2458 if (is_type_scalar(type)) {
2459 errorf(&expression->base.source_position,
2460 "expression '%E' doesn't match expected type '%T'",
2461 expression, orig_type);
2465 descend_into_subtype(path);
2469 /* update largest index of top array */
2470 const type_path_entry_t *first = &path->path[0];
2471 type_t *first_type = first->type;
2472 first_type = skip_typeref(first_type);
2473 if (is_type_array(first_type)) {
2474 size_t index = first->v.index;
2475 if (index > path->max_index)
2476 path->max_index = index;
2480 /* append to initializers list */
2481 ARR_APP1(initializer_t*, initializers, sub);
2484 if (env->declaration != NULL)
2485 warningf(HERE, "excess elements in struct initializer for '%Y'",
2486 env->declaration->symbol);
2488 warningf(HERE, "excess elements in struct initializer");
2492 if (token.type == '}') {
2496 if (token.type == '}') {
2501 /* advance to the next declaration if we are not at the end */
2502 advance_current_object(path, top_path_level);
2503 orig_type = path->top_type;
2504 if (orig_type != NULL)
2505 type = skip_typeref(orig_type);
2511 size_t len = ARR_LEN(initializers);
2512 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2513 initializer_t *result = allocate_ast_zero(size);
2514 result->kind = INITIALIZER_LIST;
2515 result->list.len = len;
2516 memcpy(&result->list.initializers, initializers,
2517 len * sizeof(initializers[0]));
2519 DEL_ARR_F(initializers);
2520 ascend_to(path, top_path_level+1);
2525 skip_initializers();
2526 DEL_ARR_F(initializers);
2527 ascend_to(path, top_path_level+1);
2532 * Parses an initializer. Parsers either a compound literal
2533 * (env->declaration == NULL) or an initializer of a declaration.
2535 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2537 type_t *type = skip_typeref(env->type);
2538 initializer_t *result = NULL;
2541 if (is_type_scalar(type)) {
2542 result = parse_scalar_initializer(type, env->must_be_constant);
2543 } else if (token.type == '{') {
2547 memset(&path, 0, sizeof(path));
2548 path.top_type = env->type;
2549 path.path = NEW_ARR_F(type_path_entry_t, 0);
2551 descend_into_subtype(&path);
2553 add_anchor_token('}');
2554 result = parse_sub_initializer(&path, env->type, 1, env);
2555 rem_anchor_token('}');
2557 max_index = path.max_index;
2558 DEL_ARR_F(path.path);
2562 /* parse_scalar_initializer() also works in this case: we simply
2563 * have an expression without {} around it */
2564 result = parse_scalar_initializer(type, env->must_be_constant);
2567 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2568 * the array type size */
2569 if (is_type_array(type) && type->array.size_expression == NULL
2570 && result != NULL) {
2572 switch (result->kind) {
2573 case INITIALIZER_LIST:
2574 size = max_index + 1;
2577 case INITIALIZER_STRING:
2578 size = result->string.string.size;
2581 case INITIALIZER_WIDE_STRING:
2582 size = result->wide_string.string.size;
2585 case INITIALIZER_DESIGNATOR:
2586 case INITIALIZER_VALUE:
2587 /* can happen for parse errors */
2592 internal_errorf(HERE, "invalid initializer type");
2595 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2596 cnst->base.type = type_size_t;
2597 cnst->conste.v.int_value = size;
2599 type_t *new_type = duplicate_type(type);
2601 new_type->array.size_expression = cnst;
2602 new_type->array.size_constant = true;
2603 new_type->array.size = size;
2604 env->type = new_type;
2612 static declaration_t *append_declaration(declaration_t *declaration);
2614 static declaration_t *parse_compound_type_specifier(bool is_struct)
2616 gnu_attribute_t *attributes = NULL;
2617 decl_modifiers_t modifiers = 0;
2624 symbol_t *symbol = NULL;
2625 declaration_t *declaration = NULL;
2627 if (token.type == T___attribute__) {
2628 modifiers |= parse_attributes(&attributes);
2631 if (token.type == T_IDENTIFIER) {
2632 symbol = token.v.symbol;
2635 namespace_t const namespc =
2636 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2637 declaration = get_declaration(symbol, namespc);
2638 if (declaration != NULL) {
2639 if (declaration->parent_scope != scope &&
2640 (token.type == '{' || token.type == ';')) {
2642 } else if (declaration->init.complete &&
2643 token.type == '{') {
2644 assert(symbol != NULL);
2645 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2646 is_struct ? "struct" : "union", symbol,
2647 &declaration->source_position);
2648 declaration->scope.declarations = NULL;
2651 } else if (token.type != '{') {
2653 parse_error_expected("while parsing struct type specifier",
2654 T_IDENTIFIER, '{', NULL);
2656 parse_error_expected("while parsing union type specifier",
2657 T_IDENTIFIER, '{', NULL);
2663 if (declaration == NULL) {
2664 declaration = allocate_declaration_zero();
2665 declaration->namespc =
2666 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2667 declaration->source_position = token.source_position;
2668 declaration->symbol = symbol;
2669 declaration->parent_scope = scope;
2670 if (symbol != NULL) {
2671 environment_push(declaration);
2673 append_declaration(declaration);
2676 if (token.type == '{') {
2677 declaration->init.complete = true;
2679 parse_compound_type_entries(declaration);
2680 modifiers |= parse_attributes(&attributes);
2683 declaration->modifiers |= modifiers;
2687 static void parse_enum_entries(type_t *const enum_type)
2691 if (token.type == '}') {
2693 errorf(HERE, "empty enum not allowed");
2697 add_anchor_token('}');
2699 if (token.type != T_IDENTIFIER) {
2700 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2702 rem_anchor_token('}');
2706 declaration_t *const entry = allocate_declaration_zero();
2707 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2708 entry->type = enum_type;
2709 entry->symbol = token.v.symbol;
2710 entry->source_position = token.source_position;
2713 if (token.type == '=') {
2715 expression_t *value = parse_constant_expression();
2717 value = create_implicit_cast(value, enum_type);
2718 entry->init.enum_value = value;
2723 record_declaration(entry);
2725 if (token.type != ',')
2728 } while (token.type != '}');
2729 rem_anchor_token('}');
2737 static type_t *parse_enum_specifier(void)
2739 gnu_attribute_t *attributes = NULL;
2740 declaration_t *declaration;
2744 if (token.type == T_IDENTIFIER) {
2745 symbol = token.v.symbol;
2748 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2749 } else if (token.type != '{') {
2750 parse_error_expected("while parsing enum type specifier",
2751 T_IDENTIFIER, '{', NULL);
2758 if (declaration == NULL) {
2759 declaration = allocate_declaration_zero();
2760 declaration->namespc = NAMESPACE_ENUM;
2761 declaration->source_position = token.source_position;
2762 declaration->symbol = symbol;
2763 declaration->parent_scope = scope;
2766 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2767 type->enumt.declaration = declaration;
2769 if (token.type == '{') {
2770 if (declaration->init.complete) {
2771 errorf(HERE, "multiple definitions of enum %Y", symbol);
2773 if (symbol != NULL) {
2774 environment_push(declaration);
2776 append_declaration(declaration);
2777 declaration->init.complete = true;
2779 parse_enum_entries(type);
2780 parse_attributes(&attributes);
2787 * if a symbol is a typedef to another type, return true
2789 static bool is_typedef_symbol(symbol_t *symbol)
2791 const declaration_t *const declaration =
2792 get_declaration(symbol, NAMESPACE_NORMAL);
2794 declaration != NULL &&
2795 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2798 static type_t *parse_typeof(void)
2805 add_anchor_token(')');
2807 expression_t *expression = NULL;
2810 switch(token.type) {
2811 case T___extension__:
2812 /* This can be a prefix to a typename or an expression. We simply eat
2816 } while (token.type == T___extension__);
2820 if (is_typedef_symbol(token.v.symbol)) {
2821 type = parse_typename();
2823 expression = parse_expression();
2824 type = expression->base.type;
2829 type = parse_typename();
2833 expression = parse_expression();
2834 type = expression->base.type;
2838 rem_anchor_token(')');
2841 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2842 typeof_type->typeoft.expression = expression;
2843 typeof_type->typeoft.typeof_type = type;
2850 typedef enum specifiers_t {
2851 SPECIFIER_SIGNED = 1 << 0,
2852 SPECIFIER_UNSIGNED = 1 << 1,
2853 SPECIFIER_LONG = 1 << 2,
2854 SPECIFIER_INT = 1 << 3,
2855 SPECIFIER_DOUBLE = 1 << 4,
2856 SPECIFIER_CHAR = 1 << 5,
2857 SPECIFIER_SHORT = 1 << 6,
2858 SPECIFIER_LONG_LONG = 1 << 7,
2859 SPECIFIER_FLOAT = 1 << 8,
2860 SPECIFIER_BOOL = 1 << 9,
2861 SPECIFIER_VOID = 1 << 10,
2862 SPECIFIER_INT8 = 1 << 11,
2863 SPECIFIER_INT16 = 1 << 12,
2864 SPECIFIER_INT32 = 1 << 13,
2865 SPECIFIER_INT64 = 1 << 14,
2866 SPECIFIER_INT128 = 1 << 15,
2867 SPECIFIER_COMPLEX = 1 << 16,
2868 SPECIFIER_IMAGINARY = 1 << 17,
2871 static type_t *create_builtin_type(symbol_t *const symbol,
2872 type_t *const real_type)
2874 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2875 type->builtin.symbol = symbol;
2876 type->builtin.real_type = real_type;
2878 type_t *result = typehash_insert(type);
2879 if (type != result) {
2886 static type_t *get_typedef_type(symbol_t *symbol)
2888 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2889 if (declaration == NULL ||
2890 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2893 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2894 type->typedeft.declaration = declaration;
2900 * check for the allowed MS alignment values.
2902 static bool check_alignment_value(long long intvalue)
2904 if (intvalue < 1 || intvalue > 8192) {
2905 errorf(HERE, "illegal alignment value");
2908 unsigned v = (unsigned)intvalue;
2909 for(unsigned i = 1; i <= 8192; i += i) {
2913 errorf(HERE, "alignment must be power of two");
2917 #define DET_MOD(name, tag) do { \
2918 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2919 *modifiers |= tag; \
2922 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2924 decl_modifiers_t *modifiers = &specifiers->modifiers;
2927 if (token.type == T_restrict) {
2929 DET_MOD(restrict, DM_RESTRICT);
2931 } else if (token.type != T_IDENTIFIER)
2933 symbol_t *symbol = token.v.symbol;
2934 if (symbol == sym_align) {
2937 if (token.type != T_INTEGER)
2939 if (check_alignment_value(token.v.intvalue)) {
2940 if (specifiers->alignment != 0)
2941 warningf(HERE, "align used more than once");
2942 specifiers->alignment = (unsigned char)token.v.intvalue;
2946 } else if (symbol == sym_allocate) {
2949 if (token.type != T_IDENTIFIER)
2951 (void)token.v.symbol;
2953 } else if (symbol == sym_dllimport) {
2955 DET_MOD(dllimport, DM_DLLIMPORT);
2956 } else if (symbol == sym_dllexport) {
2958 DET_MOD(dllexport, DM_DLLEXPORT);
2959 } else if (symbol == sym_thread) {
2961 DET_MOD(thread, DM_THREAD);
2962 } else if (symbol == sym_naked) {
2964 DET_MOD(naked, DM_NAKED);
2965 } else if (symbol == sym_noinline) {
2967 DET_MOD(noinline, DM_NOINLINE);
2968 } else if (symbol == sym_noreturn) {
2970 DET_MOD(noreturn, DM_NORETURN);
2971 } else if (symbol == sym_nothrow) {
2973 DET_MOD(nothrow, DM_NOTHROW);
2974 } else if (symbol == sym_novtable) {
2976 DET_MOD(novtable, DM_NOVTABLE);
2977 } else if (symbol == sym_property) {
2981 bool is_get = false;
2982 if (token.type != T_IDENTIFIER)
2984 if (token.v.symbol == sym_get) {
2986 } else if (token.v.symbol == sym_put) {
2988 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2993 if (token.type != T_IDENTIFIER)
2996 if (specifiers->get_property_sym != NULL) {
2997 errorf(HERE, "get property name already specified");
2999 specifiers->get_property_sym = token.v.symbol;
3002 if (specifiers->put_property_sym != NULL) {
3003 errorf(HERE, "put property name already specified");
3005 specifiers->put_property_sym = token.v.symbol;
3009 if (token.type == ',') {
3016 } else if (symbol == sym_selectany) {
3018 DET_MOD(selectany, DM_SELECTANY);
3019 } else if (symbol == sym_uuid) {
3022 if (token.type != T_STRING_LITERAL)
3026 } else if (symbol == sym_deprecated) {
3028 if (specifiers->deprecated != 0)
3029 warningf(HERE, "deprecated used more than once");
3030 specifiers->deprecated = 1;
3031 if (token.type == '(') {
3033 if (token.type == T_STRING_LITERAL) {
3034 specifiers->deprecated_string = token.v.string.begin;
3037 errorf(HERE, "string literal expected");
3041 } else if (symbol == sym_noalias) {
3043 DET_MOD(noalias, DM_NOALIAS);
3045 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3047 if (token.type == '(')
3051 if (token.type == ',')
3058 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3060 type_t *type = NULL;
3061 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3062 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3063 unsigned type_specifiers = 0;
3064 bool newtype = false;
3065 bool saw_error = false;
3067 specifiers->source_position = token.source_position;
3070 specifiers->modifiers
3071 |= parse_attributes(&specifiers->gnu_attributes);
3072 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3073 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3075 switch(token.type) {
3078 #define MATCH_STORAGE_CLASS(token, class) \
3080 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3081 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3083 specifiers->declared_storage_class = class; \
3087 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3088 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3089 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3090 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3091 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3096 add_anchor_token(')');
3097 parse_microsoft_extended_decl_modifier(specifiers);
3098 rem_anchor_token(')');
3103 switch (specifiers->declared_storage_class) {
3104 case STORAGE_CLASS_NONE:
3105 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3108 case STORAGE_CLASS_EXTERN:
3109 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3112 case STORAGE_CLASS_STATIC:
3113 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3117 errorf(HERE, "multiple storage classes in declaration specifiers");
3123 /* type qualifiers */
3124 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3126 qualifiers |= qualifier; \
3130 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3131 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3132 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3133 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3134 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3135 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3136 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3137 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3139 case T___extension__:
3144 /* type specifiers */
3145 #define MATCH_SPECIFIER(token, specifier, name) \
3148 if (type_specifiers & specifier) { \
3149 errorf(HERE, "multiple " name " type specifiers given"); \
3151 type_specifiers |= specifier; \
3155 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3156 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3157 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3158 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3159 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3160 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3161 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3162 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3163 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3164 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3165 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3166 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3167 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3168 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3169 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3170 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3172 case T__forceinline:
3173 /* only in microsoft mode */
3174 specifiers->modifiers |= DM_FORCEINLINE;
3179 specifiers->is_inline = true;
3184 if (type_specifiers & SPECIFIER_LONG_LONG) {
3185 errorf(HERE, "multiple type specifiers given");
3186 } else if (type_specifiers & SPECIFIER_LONG) {
3187 type_specifiers |= SPECIFIER_LONG_LONG;
3189 type_specifiers |= SPECIFIER_LONG;
3194 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3196 type->compound.declaration = parse_compound_type_specifier(true);
3200 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3201 type->compound.declaration = parse_compound_type_specifier(false);
3202 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3203 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3207 type = parse_enum_specifier();
3210 type = parse_typeof();
3212 case T___builtin_va_list:
3213 type = duplicate_type(type_valist);
3217 case T_IDENTIFIER: {
3218 /* only parse identifier if we haven't found a type yet */
3219 if (type != NULL || type_specifiers != 0) {
3220 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3221 * declaration, so it doesn't generate errors about expecting '(' or
3223 switch (look_ahead(1)->type) {
3230 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3233 errorf(HERE, "discarding stray %K in declaration specifer", &token);
3238 goto finish_specifiers;
3242 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3243 if (typedef_type == NULL) {
3244 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3245 * declaration, so it doesn't generate 'implicit int' followed by more
3246 * errors later on. */
3247 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3252 errorf(HERE, "%K does not name a type", &token);
3255 if (la1_type == '*')
3256 goto finish_specifiers;
3260 goto finish_specifiers;
3265 type = typedef_type;
3269 /* function specifier */
3271 goto finish_specifiers;
3278 atomic_type_kind_t atomic_type;
3280 /* match valid basic types */
3281 switch(type_specifiers) {
3282 case SPECIFIER_VOID:
3283 atomic_type = ATOMIC_TYPE_VOID;
3285 case SPECIFIER_CHAR:
3286 atomic_type = ATOMIC_TYPE_CHAR;
3288 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3289 atomic_type = ATOMIC_TYPE_SCHAR;
3291 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3292 atomic_type = ATOMIC_TYPE_UCHAR;
3294 case SPECIFIER_SHORT:
3295 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3296 case SPECIFIER_SHORT | SPECIFIER_INT:
3297 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3298 atomic_type = ATOMIC_TYPE_SHORT;
3300 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3301 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3302 atomic_type = ATOMIC_TYPE_USHORT;
3305 case SPECIFIER_SIGNED:
3306 case SPECIFIER_SIGNED | SPECIFIER_INT:
3307 atomic_type = ATOMIC_TYPE_INT;
3309 case SPECIFIER_UNSIGNED:
3310 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3311 atomic_type = ATOMIC_TYPE_UINT;
3313 case SPECIFIER_LONG:
3314 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3315 case SPECIFIER_LONG | SPECIFIER_INT:
3316 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3317 atomic_type = ATOMIC_TYPE_LONG;
3319 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3320 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3321 atomic_type = ATOMIC_TYPE_ULONG;
3324 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3325 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3326 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3327 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3329 atomic_type = ATOMIC_TYPE_LONGLONG;
3330 goto warn_about_long_long;
3332 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3333 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3335 atomic_type = ATOMIC_TYPE_ULONGLONG;
3336 warn_about_long_long:
3337 if (warning.long_long) {
3338 warningf(&specifiers->source_position,
3339 "ISO C90 does not support 'long long'");
3343 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3344 atomic_type = unsigned_int8_type_kind;
3347 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3348 atomic_type = unsigned_int16_type_kind;
3351 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3352 atomic_type = unsigned_int32_type_kind;
3355 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3356 atomic_type = unsigned_int64_type_kind;
3359 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3360 atomic_type = unsigned_int128_type_kind;
3363 case SPECIFIER_INT8:
3364 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3365 atomic_type = int8_type_kind;
3368 case SPECIFIER_INT16:
3369 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3370 atomic_type = int16_type_kind;
3373 case SPECIFIER_INT32:
3374 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3375 atomic_type = int32_type_kind;
3378 case SPECIFIER_INT64:
3379 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3380 atomic_type = int64_type_kind;
3383 case SPECIFIER_INT128:
3384 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3385 atomic_type = int128_type_kind;
3388 case SPECIFIER_FLOAT:
3389 atomic_type = ATOMIC_TYPE_FLOAT;
3391 case SPECIFIER_DOUBLE:
3392 atomic_type = ATOMIC_TYPE_DOUBLE;
3394 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3395 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3397 case SPECIFIER_BOOL:
3398 atomic_type = ATOMIC_TYPE_BOOL;
3400 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3401 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3402 atomic_type = ATOMIC_TYPE_FLOAT;
3404 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3405 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3406 atomic_type = ATOMIC_TYPE_DOUBLE;
3408 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3409 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3410 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3413 /* invalid specifier combination, give an error message */
3414 if (type_specifiers == 0) {
3416 specifiers->type = type_error_type;
3421 if (warning.implicit_int) {
3422 warningf(HERE, "no type specifiers in declaration, using 'int'");
3424 atomic_type = ATOMIC_TYPE_INT;
3427 errorf(HERE, "no type specifiers given in declaration");
3429 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3430 (type_specifiers & SPECIFIER_UNSIGNED)) {
3431 errorf(HERE, "signed and unsigned specifiers given");
3432 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3433 errorf(HERE, "only integer types can be signed or unsigned");
3435 errorf(HERE, "multiple datatypes in declaration");
3437 atomic_type = ATOMIC_TYPE_INVALID;
3440 if (type_specifiers & SPECIFIER_COMPLEX &&
3441 atomic_type != ATOMIC_TYPE_INVALID) {
3442 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3443 type->complex.akind = atomic_type;
3444 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3445 atomic_type != ATOMIC_TYPE_INVALID) {
3446 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3447 type->imaginary.akind = atomic_type;
3449 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3450 type->atomic.akind = atomic_type;
3453 } else if (type_specifiers != 0) {
3454 errorf(HERE, "multiple datatypes in declaration");
3457 /* FIXME: check type qualifiers here */
3459 type->base.qualifiers = qualifiers;
3460 type->base.modifiers = modifiers;
3462 type_t *result = typehash_insert(type);
3463 if (newtype && result != type) {
3467 specifiers->type = result;
3472 static type_qualifiers_t parse_type_qualifiers(void)
3474 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3477 switch(token.type) {
3478 /* type qualifiers */
3479 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3480 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3481 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3482 /* microsoft extended type modifiers */
3483 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3484 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3485 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3486 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3487 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3495 static declaration_t *parse_identifier_list(void)
3497 declaration_t *declarations = NULL;
3498 declaration_t *last_declaration = NULL;
3500 declaration_t *const declaration = allocate_declaration_zero();
3501 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3502 declaration->source_position = token.source_position;
3503 declaration->symbol = token.v.symbol;
3506 if (last_declaration != NULL) {
3507 last_declaration->next = declaration;
3509 declarations = declaration;
3511 last_declaration = declaration;
3513 if (token.type != ',') {
3517 } while (token.type == T_IDENTIFIER);
3519 return declarations;
3522 static type_t *automatic_type_conversion(type_t *orig_type);
3524 static void semantic_parameter(declaration_t *declaration)
3526 /* TODO: improve error messages */
3527 source_position_t const* const pos = &declaration->source_position;
3529 switch (declaration->declared_storage_class) {
3530 case STORAGE_CLASS_TYPEDEF:
3531 errorf(pos, "typedef not allowed in parameter list");
3534 /* Allowed storage classes */
3535 case STORAGE_CLASS_NONE:
3536 case STORAGE_CLASS_REGISTER:
3540 errorf(pos, "parameter may only have none or register storage class");
3544 type_t *const orig_type = declaration->type;
3545 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3546 * sugar. Turn it into a pointer.
3547 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3548 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3550 type_t *const type = automatic_type_conversion(orig_type);
3551 declaration->type = type;
3553 if (is_type_incomplete(skip_typeref(type))) {
3554 errorf(pos, "incomplete type '%T' not allowed for parameter '%Y'",
3555 orig_type, declaration->symbol);
3559 static declaration_t *parse_parameter(void)
3561 declaration_specifiers_t specifiers;
3562 memset(&specifiers, 0, sizeof(specifiers));
3564 parse_declaration_specifiers(&specifiers);
3566 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3571 static declaration_t *parse_parameters(function_type_t *type)
3573 declaration_t *declarations = NULL;
3576 add_anchor_token(')');
3577 int saved_comma_state = save_and_reset_anchor_state(',');
3579 if (token.type == T_IDENTIFIER) {
3580 symbol_t *symbol = token.v.symbol;
3581 if (!is_typedef_symbol(symbol)) {
3582 type->kr_style_parameters = true;
3583 declarations = parse_identifier_list();
3584 goto parameters_finished;
3588 if (token.type == ')') {
3589 type->unspecified_parameters = 1;
3590 goto parameters_finished;
3593 declaration_t *declaration;
3594 declaration_t *last_declaration = NULL;
3595 function_parameter_t *parameter;
3596 function_parameter_t *last_parameter = NULL;
3599 switch(token.type) {
3603 goto parameters_finished;
3606 case T___extension__:
3608 declaration = parse_parameter();
3610 /* func(void) is not a parameter */
3611 if (last_parameter == NULL
3612 && token.type == ')'
3613 && declaration->symbol == NULL
3614 && skip_typeref(declaration->type) == type_void) {
3615 goto parameters_finished;
3617 semantic_parameter(declaration);
3619 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3620 memset(parameter, 0, sizeof(parameter[0]));
3621 parameter->type = declaration->type;
3623 if (last_parameter != NULL) {
3624 last_declaration->next = declaration;
3625 last_parameter->next = parameter;
3627 type->parameters = parameter;
3628 declarations = declaration;
3630 last_parameter = parameter;
3631 last_declaration = declaration;
3635 goto parameters_finished;
3637 if (token.type != ',') {
3638 goto parameters_finished;
3644 parameters_finished:
3645 rem_anchor_token(')');
3648 restore_anchor_state(',', saved_comma_state);
3649 return declarations;
3652 restore_anchor_state(',', saved_comma_state);
3656 typedef enum construct_type_kind_t {
3661 } construct_type_kind_t;
3663 typedef struct construct_type_t construct_type_t;
3664 struct construct_type_t {
3665 construct_type_kind_t kind;
3666 construct_type_t *next;
3669 typedef struct parsed_pointer_t parsed_pointer_t;
3670 struct parsed_pointer_t {
3671 construct_type_t construct_type;
3672 type_qualifiers_t type_qualifiers;
3675 typedef struct construct_function_type_t construct_function_type_t;
3676 struct construct_function_type_t {
3677 construct_type_t construct_type;
3678 type_t *function_type;
3681 typedef struct parsed_array_t parsed_array_t;
3682 struct parsed_array_t {
3683 construct_type_t construct_type;
3684 type_qualifiers_t type_qualifiers;
3690 typedef struct construct_base_type_t construct_base_type_t;
3691 struct construct_base_type_t {
3692 construct_type_t construct_type;
3696 static construct_type_t *parse_pointer_declarator(void)
3700 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3701 memset(pointer, 0, sizeof(pointer[0]));
3702 pointer->construct_type.kind = CONSTRUCT_POINTER;
3703 pointer->type_qualifiers = parse_type_qualifiers();
3705 return (construct_type_t*) pointer;
3708 static construct_type_t *parse_array_declarator(void)
3711 add_anchor_token(']');
3713 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3714 memset(array, 0, sizeof(array[0]));
3715 array->construct_type.kind = CONSTRUCT_ARRAY;
3717 if (token.type == T_static) {
3718 array->is_static = true;
3722 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3723 if (type_qualifiers != 0) {
3724 if (token.type == T_static) {
3725 array->is_static = true;
3729 array->type_qualifiers = type_qualifiers;
3731 if (token.type == '*' && look_ahead(1)->type == ']') {
3732 array->is_variable = true;
3734 } else if (token.type != ']') {
3735 array->size = parse_assignment_expression();
3738 rem_anchor_token(']');
3741 return (construct_type_t*) array;
3746 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3749 if (declaration != NULL) {
3750 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3752 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3754 if (mask & (mask-1)) {
3755 const char *first = NULL, *second = NULL;
3757 /* more than one calling convention set */
3758 if (declaration->modifiers & DM_CDECL) {
3759 if (first == NULL) first = "cdecl";
3760 else if (second == NULL) second = "cdecl";
3762 if (declaration->modifiers & DM_STDCALL) {
3763 if (first == NULL) first = "stdcall";
3764 else if (second == NULL) second = "stdcall";
3766 if (declaration->modifiers & DM_FASTCALL) {
3767 if (first == NULL) first = "fastcall";
3768 else if (second == NULL) second = "fastcall";
3770 if (declaration->modifiers & DM_THISCALL) {
3771 if (first == NULL) first = "thiscall";
3772 else if (second == NULL) second = "thiscall";
3774 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3777 if (declaration->modifiers & DM_CDECL)
3778 type->function.calling_convention = CC_CDECL;
3779 else if (declaration->modifiers & DM_STDCALL)
3780 type->function.calling_convention = CC_STDCALL;
3781 else if (declaration->modifiers & DM_FASTCALL)
3782 type->function.calling_convention = CC_FASTCALL;
3783 else if (declaration->modifiers & DM_THISCALL)
3784 type->function.calling_convention = CC_THISCALL;
3786 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3789 declaration_t *parameters = parse_parameters(&type->function);
3790 if (declaration != NULL) {
3791 declaration->scope.declarations = parameters;
3794 construct_function_type_t *construct_function_type =
3795 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3796 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3797 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3798 construct_function_type->function_type = type;
3800 return &construct_function_type->construct_type;
3803 static void fix_declaration_type(declaration_t *declaration)
3805 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3806 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3808 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3809 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3811 if (declaration->type->base.modifiers == type_modifiers)
3814 type_t *copy = duplicate_type(declaration->type);
3815 copy->base.modifiers = type_modifiers;
3817 type_t *result = typehash_insert(copy);
3818 if (result != copy) {
3819 obstack_free(type_obst, copy);
3822 declaration->type = result;
3825 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3826 bool may_be_abstract)
3828 /* construct a single linked list of construct_type_t's which describe
3829 * how to construct the final declarator type */
3830 construct_type_t *first = NULL;
3831 construct_type_t *last = NULL;
3832 gnu_attribute_t *attributes = NULL;
3834 decl_modifiers_t modifiers = parse_attributes(&attributes);
3837 while (token.type == '*') {
3838 construct_type_t *type = parse_pointer_declarator();
3848 /* TODO: find out if this is correct */
3849 modifiers |= parse_attributes(&attributes);
3852 if (declaration != NULL)
3853 declaration->modifiers |= modifiers;
3855 construct_type_t *inner_types = NULL;
3857 switch(token.type) {
3859 if (declaration == NULL) {
3860 errorf(HERE, "no identifier expected in typename");
3862 declaration->symbol = token.v.symbol;
3863 declaration->source_position = token.source_position;
3869 add_anchor_token(')');
3870 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3871 /* All later declarators only modify the return type, not declaration */
3873 rem_anchor_token(')');
3877 if (may_be_abstract)
3879 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3880 /* avoid a loop in the outermost scope, because eat_statement doesn't
3882 if (token.type == '}' && current_function == NULL) {
3890 construct_type_t *p = last;
3893 construct_type_t *type;
3894 switch(token.type) {
3896 type = parse_function_declarator(declaration);
3899 type = parse_array_declarator();
3902 goto declarator_finished;
3905 /* insert in the middle of the list (behind p) */
3907 type->next = p->next;
3918 declarator_finished:
3919 /* append inner_types at the end of the list, we don't to set last anymore
3920 * as it's not needed anymore */
3922 assert(first == NULL);
3923 first = inner_types;
3925 last->next = inner_types;
3933 static void parse_declaration_attributes(declaration_t *declaration)
3935 gnu_attribute_t *attributes = NULL;
3936 decl_modifiers_t modifiers = parse_attributes(&attributes);
3938 if (declaration == NULL)
3941 declaration->modifiers |= modifiers;
3942 /* check if we have these stupid mode attributes... */
3943 type_t *old_type = declaration->type;
3944 if (old_type == NULL)
3947 gnu_attribute_t *attribute = attributes;
3948 for ( ; attribute != NULL; attribute = attribute->next) {
3949 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3952 atomic_type_kind_t akind = attribute->u.akind;
3953 if (!is_type_signed(old_type)) {
3955 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3956 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3957 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3958 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3960 panic("invalid akind in mode attribute");
3964 = make_atomic_type(akind, old_type->base.qualifiers);
3968 static type_t *construct_declarator_type(construct_type_t *construct_list,
3971 construct_type_t *iter = construct_list;
3972 for( ; iter != NULL; iter = iter->next) {
3973 switch(iter->kind) {
3974 case CONSTRUCT_INVALID:
3975 internal_errorf(HERE, "invalid type construction found");
3976 case CONSTRUCT_FUNCTION: {
3977 construct_function_type_t *construct_function_type
3978 = (construct_function_type_t*) iter;
3980 type_t *function_type = construct_function_type->function_type;
3982 function_type->function.return_type = type;
3984 type_t *skipped_return_type = skip_typeref(type);
3985 if (is_type_function(skipped_return_type)) {
3986 errorf(HERE, "function returning function is not allowed");
3987 type = type_error_type;
3988 } else if (is_type_array(skipped_return_type)) {
3989 errorf(HERE, "function returning array is not allowed");
3990 type = type_error_type;
3992 type = function_type;
3997 case CONSTRUCT_POINTER: {
3998 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3999 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4000 pointer_type->pointer.points_to = type;
4001 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4003 type = pointer_type;
4007 case CONSTRUCT_ARRAY: {
4008 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4009 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4011 expression_t *size_expression = parsed_array->size;
4012 if (size_expression != NULL) {
4014 = create_implicit_cast(size_expression, type_size_t);
4017 array_type->base.qualifiers = parsed_array->type_qualifiers;
4018 array_type->array.element_type = type;
4019 array_type->array.is_static = parsed_array->is_static;
4020 array_type->array.is_variable = parsed_array->is_variable;
4021 array_type->array.size_expression = size_expression;
4023 if (size_expression != NULL) {
4024 if (is_constant_expression(size_expression)) {
4025 array_type->array.size_constant = true;
4026 array_type->array.size
4027 = fold_constant(size_expression);
4029 array_type->array.is_vla = true;
4033 type_t *skipped_type = skip_typeref(type);
4034 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
4035 errorf(HERE, "array of void is not allowed");
4036 type = type_error_type;
4044 type_t *hashed_type = typehash_insert(type);
4045 if (hashed_type != type) {
4046 /* the function type was constructed earlier freeing it here will
4047 * destroy other types... */
4048 if (iter->kind != CONSTRUCT_FUNCTION) {
4058 static declaration_t *parse_declarator(
4059 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4061 declaration_t *const declaration = allocate_declaration_zero();
4062 declaration->source_position = specifiers->source_position;
4063 declaration->declared_storage_class = specifiers->declared_storage_class;
4064 declaration->modifiers = specifiers->modifiers;
4065 declaration->deprecated_string = specifiers->deprecated_string;
4066 declaration->get_property_sym = specifiers->get_property_sym;
4067 declaration->put_property_sym = specifiers->put_property_sym;
4068 declaration->is_inline = specifiers->is_inline;
4070 declaration->storage_class = specifiers->declared_storage_class;
4071 if (declaration->storage_class == STORAGE_CLASS_NONE
4072 && scope != global_scope) {
4073 declaration->storage_class = STORAGE_CLASS_AUTO;
4076 if (specifiers->alignment != 0) {
4077 /* TODO: add checks here */
4078 declaration->alignment = specifiers->alignment;
4081 construct_type_t *construct_type
4082 = parse_inner_declarator(declaration, may_be_abstract);
4083 type_t *const type = specifiers->type;
4084 declaration->type = construct_declarator_type(construct_type, type);
4086 parse_declaration_attributes(declaration);
4088 fix_declaration_type(declaration);
4090 if (construct_type != NULL) {
4091 obstack_free(&temp_obst, construct_type);
4097 static type_t *parse_abstract_declarator(type_t *base_type)
4099 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4101 type_t *result = construct_declarator_type(construct_type, base_type);
4102 if (construct_type != NULL) {
4103 obstack_free(&temp_obst, construct_type);
4109 static declaration_t *append_declaration(declaration_t* const declaration)
4111 if (last_declaration != NULL) {
4112 last_declaration->next = declaration;
4114 scope->declarations = declaration;
4116 last_declaration = declaration;
4121 * Check if the declaration of main is suspicious. main should be a
4122 * function with external linkage, returning int, taking either zero
4123 * arguments, two, or three arguments of appropriate types, ie.
4125 * int main([ int argc, char **argv [, char **env ] ]).
4127 * @param decl the declaration to check
4128 * @param type the function type of the declaration
4130 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4132 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4133 warningf(&decl->source_position,
4134 "'main' is normally a non-static function");
4136 if (skip_typeref(func_type->return_type) != type_int) {
4137 warningf(&decl->source_position,
4138 "return type of 'main' should be 'int', but is '%T'",
4139 func_type->return_type);
4141 const function_parameter_t *parm = func_type->parameters;
4143 type_t *const first_type = parm->type;
4144 if (!types_compatible(skip_typeref(first_type), type_int)) {
4145 warningf(&decl->source_position,
4146 "first argument of 'main' should be 'int', but is '%T'", first_type);
4150 type_t *const second_type = parm->type;
4151 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4152 warningf(&decl->source_position,
4153 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4157 type_t *const third_type = parm->type;
4158 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4159 warningf(&decl->source_position,
4160 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4164 goto warn_arg_count;
4168 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4174 * Check if a symbol is the equal to "main".
4176 static bool is_sym_main(const symbol_t *const sym)
4178 return strcmp(sym->string, "main") == 0;
4181 static declaration_t *internal_record_declaration(
4182 declaration_t *const declaration,
4183 const bool is_definition)
4185 const symbol_t *const symbol = declaration->symbol;
4186 const namespace_t namespc = (namespace_t)declaration->namespc;
4188 assert(symbol != NULL);
4189 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4191 type_t *const orig_type = declaration->type;
4192 type_t *const type = skip_typeref(orig_type);
4193 if (is_type_function(type) &&
4194 type->function.unspecified_parameters &&
4195 warning.strict_prototypes &&
4196 previous_declaration == NULL) {
4197 warningf(&declaration->source_position,
4198 "function declaration '%#T' is not a prototype",
4199 orig_type, declaration->symbol);
4202 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4203 check_type_of_main(declaration, &type->function);
4206 if (warning.nested_externs &&
4207 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4208 scope != global_scope) {
4209 warningf(&declaration->source_position,
4210 "nested extern declaration of '%#T'", declaration->type, symbol);
4213 assert(declaration != previous_declaration);
4214 if (previous_declaration != NULL
4215 && previous_declaration->parent_scope == scope) {
4216 /* can happen for K&R style declarations */
4217 if (previous_declaration->type == NULL) {
4218 previous_declaration->type = declaration->type;
4221 const type_t *prev_type = skip_typeref(previous_declaration->type);
4222 if (!types_compatible(type, prev_type)) {
4223 errorf(&declaration->source_position,
4224 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4225 orig_type, symbol, previous_declaration->type, symbol,
4226 &previous_declaration->source_position);
4228 unsigned old_storage_class = previous_declaration->storage_class;
4229 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4230 errorf(&declaration->source_position,
4231 "redeclaration of enum entry '%Y' (declared %P)",
4232 symbol, &previous_declaration->source_position);
4233 return previous_declaration;
4236 if (warning.redundant_decls &&
4238 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4239 !(previous_declaration->modifiers & DM_USED) &&
4240 !previous_declaration->used) {
4241 warningf(&previous_declaration->source_position,
4242 "unnecessary static forward declaration for '%#T'",
4243 previous_declaration->type, symbol);
4246 unsigned new_storage_class = declaration->storage_class;
4248 if (is_type_incomplete(prev_type)) {
4249 previous_declaration->type = type;
4253 /* pretend no storage class means extern for function
4254 * declarations (except if the previous declaration is neither
4255 * none nor extern) */
4256 if (is_type_function(type)) {
4257 if (prev_type->function.unspecified_parameters) {
4258 previous_declaration->type = type;
4262 switch (old_storage_class) {
4263 case STORAGE_CLASS_NONE:
4264 old_storage_class = STORAGE_CLASS_EXTERN;
4267 case STORAGE_CLASS_EXTERN:
4268 if (is_definition) {
4269 if (warning.missing_prototypes &&
4270 prev_type->function.unspecified_parameters &&
4271 !is_sym_main(symbol)) {
4272 warningf(&declaration->source_position,
4273 "no previous prototype for '%#T'",
4276 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4277 new_storage_class = STORAGE_CLASS_EXTERN;
4286 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4287 new_storage_class == STORAGE_CLASS_EXTERN) {
4288 warn_redundant_declaration:
4289 if (!is_definition &&
4290 warning.redundant_decls &&
4291 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4292 warningf(&declaration->source_position,
4293 "redundant declaration for '%Y' (declared %P)",
4294 symbol, &previous_declaration->source_position);
4296 } else if (current_function == NULL) {
4297 if (old_storage_class != STORAGE_CLASS_STATIC &&
4298 new_storage_class == STORAGE_CLASS_STATIC) {
4299 errorf(&declaration->source_position,
4300 "static declaration of '%Y' follows non-static declaration (declared %P)",
4301 symbol, &previous_declaration->source_position);
4302 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4303 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4304 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4306 goto warn_redundant_declaration;
4308 } else if (old_storage_class == new_storage_class) {
4309 errorf(&declaration->source_position,
4310 "redeclaration of '%Y' (declared %P)",
4311 symbol, &previous_declaration->source_position);
4313 errorf(&declaration->source_position,
4314 "redeclaration of '%Y' with different linkage (declared %P)",
4315 symbol, &previous_declaration->source_position);
4319 previous_declaration->modifiers |= declaration->modifiers;
4320 previous_declaration->is_inline |= declaration->is_inline;
4321 return previous_declaration;
4322 } else if (is_type_function(type)) {
4323 if (is_definition &&
4324 declaration->storage_class != STORAGE_CLASS_STATIC) {
4325 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4326 warningf(&declaration->source_position,
4327 "no previous prototype for '%#T'", orig_type, symbol);
4328 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4329 warningf(&declaration->source_position,
4330 "no previous declaration for '%#T'", orig_type,
4335 if (warning.missing_declarations &&
4336 scope == global_scope && (
4337 declaration->storage_class == STORAGE_CLASS_NONE ||
4338 declaration->storage_class == STORAGE_CLASS_THREAD
4340 warningf(&declaration->source_position,
4341 "no previous declaration for '%#T'", orig_type, symbol);
4345 assert(declaration->parent_scope == NULL);
4346 assert(scope != NULL);
4348 declaration->parent_scope = scope;
4350 environment_push(declaration);
4351 return append_declaration(declaration);
4354 static declaration_t *record_declaration(declaration_t *declaration)
4356 return internal_record_declaration(declaration, false);
4359 static declaration_t *record_definition(declaration_t *declaration)
4361 return internal_record_declaration(declaration, true);
4364 static void parser_error_multiple_definition(declaration_t *declaration,
4365 const source_position_t *source_position)
4367 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4368 declaration->symbol, &declaration->source_position);
4371 static bool is_declaration_specifier(const token_t *token,
4372 bool only_specifiers_qualifiers)
4374 switch(token->type) {
4379 return is_typedef_symbol(token->v.symbol);
4381 case T___extension__:
4383 return !only_specifiers_qualifiers;
4390 static void parse_init_declarator_rest(declaration_t *declaration)
4394 type_t *orig_type = declaration->type;
4395 type_t *type = skip_typeref(orig_type);
4397 if (declaration->init.initializer != NULL) {
4398 parser_error_multiple_definition(declaration, HERE);
4401 bool must_be_constant = false;
4402 if (declaration->storage_class == STORAGE_CLASS_STATIC
4403 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4404 || declaration->parent_scope == global_scope) {
4405 must_be_constant = true;
4408 parse_initializer_env_t env;
4409 env.type = orig_type;
4410 env.must_be_constant = must_be_constant;
4411 env.declaration = declaration;
4413 initializer_t *initializer = parse_initializer(&env);
4415 if (env.type != orig_type) {
4416 orig_type = env.type;
4417 type = skip_typeref(orig_type);
4418 declaration->type = env.type;
4421 if (is_type_function(type)) {
4422 errorf(&declaration->source_position,
4423 "initializers not allowed for function types at declator '%Y' (type '%T')",
4424 declaration->symbol, orig_type);
4426 declaration->init.initializer = initializer;
4430 /* parse rest of a declaration without any declarator */
4431 static void parse_anonymous_declaration_rest(
4432 const declaration_specifiers_t *specifiers,
4433 parsed_declaration_func finished_declaration)
4437 declaration_t *const declaration = allocate_declaration_zero();
4438 declaration->type = specifiers->type;
4439 declaration->declared_storage_class = specifiers->declared_storage_class;
4440 declaration->source_position = specifiers->source_position;
4441 declaration->modifiers = specifiers->modifiers;
4443 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4444 warningf(&declaration->source_position,
4445 "useless storage class in empty declaration");
4447 declaration->storage_class = STORAGE_CLASS_NONE;
4449 type_t *type = declaration->type;
4450 switch (type->kind) {
4451 case TYPE_COMPOUND_STRUCT:
4452 case TYPE_COMPOUND_UNION: {
4453 if (type->compound.declaration->symbol == NULL) {
4454 warningf(&declaration->source_position,
4455 "unnamed struct/union that defines no instances");
4464 warningf(&declaration->source_position, "empty declaration");
4468 finished_declaration(declaration);
4471 static void parse_declaration_rest(declaration_t *ndeclaration,
4472 const declaration_specifiers_t *specifiers,
4473 parsed_declaration_func finished_declaration)
4475 add_anchor_token(';');
4476 add_anchor_token('=');
4477 add_anchor_token(',');
4479 declaration_t *declaration = finished_declaration(ndeclaration);
4481 type_t *orig_type = declaration->type;
4482 type_t *type = skip_typeref(orig_type);
4484 if (type->kind != TYPE_FUNCTION &&
4485 declaration->is_inline &&
4486 is_type_valid(type)) {
4487 warningf(&declaration->source_position,
4488 "variable '%Y' declared 'inline'\n", declaration->symbol);
4491 if (token.type == '=') {
4492 parse_init_declarator_rest(declaration);
4495 if (token.type != ',')
4499 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4504 rem_anchor_token(';');
4505 rem_anchor_token('=');
4506 rem_anchor_token(',');
4509 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4511 symbol_t *symbol = declaration->symbol;
4512 if (symbol == NULL) {
4513 errorf(HERE, "anonymous declaration not valid as function parameter");
4516 namespace_t namespc = (namespace_t) declaration->namespc;
4517 if (namespc != NAMESPACE_NORMAL) {
4518 return record_declaration(declaration);
4521 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4522 if (previous_declaration == NULL ||
4523 previous_declaration->parent_scope != scope) {
4524 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4529 if (previous_declaration->type == NULL) {
4530 previous_declaration->type = declaration->type;
4531 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4532 previous_declaration->storage_class = declaration->storage_class;
4533 previous_declaration->parent_scope = scope;
4534 return previous_declaration;
4536 return record_declaration(declaration);
4540 static void parse_declaration(parsed_declaration_func finished_declaration)
4542 declaration_specifiers_t specifiers;
4543 memset(&specifiers, 0, sizeof(specifiers));
4544 parse_declaration_specifiers(&specifiers);
4546 if (token.type == ';') {
4547 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4549 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4550 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4554 static type_t *get_default_promoted_type(type_t *orig_type)
4556 type_t *result = orig_type;
4558 type_t *type = skip_typeref(orig_type);
4559 if (is_type_integer(type)) {
4560 result = promote_integer(type);
4561 } else if (type == type_float) {
4562 result = type_double;
4568 static void parse_kr_declaration_list(declaration_t *declaration)
4570 type_t *type = skip_typeref(declaration->type);
4571 if (!is_type_function(type))
4574 if (!type->function.kr_style_parameters)
4577 /* push function parameters */
4578 int top = environment_top();
4579 scope_t *last_scope = scope;
4580 set_scope(&declaration->scope);
4582 declaration_t *parameter = declaration->scope.declarations;
4583 for ( ; parameter != NULL; parameter = parameter->next) {
4584 assert(parameter->parent_scope == NULL);
4585 parameter->parent_scope = scope;
4586 environment_push(parameter);
4589 /* parse declaration list */
4590 while (is_declaration_specifier(&token, false)) {
4591 parse_declaration(finished_kr_declaration);
4594 /* pop function parameters */
4595 assert(scope == &declaration->scope);
4596 set_scope(last_scope);
4597 environment_pop_to(top);
4599 /* update function type */
4600 type_t *new_type = duplicate_type(type);
4602 function_parameter_t *parameters = NULL;
4603 function_parameter_t *last_parameter = NULL;
4605 declaration_t *parameter_declaration = declaration->scope.declarations;
4606 for( ; parameter_declaration != NULL;
4607 parameter_declaration = parameter_declaration->next) {
4608 type_t *parameter_type = parameter_declaration->type;
4609 if (parameter_type == NULL) {
4611 errorf(HERE, "no type specified for function parameter '%Y'",
4612 parameter_declaration->symbol);
4614 if (warning.implicit_int) {
4615 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4616 parameter_declaration->symbol);
4618 parameter_type = type_int;
4619 parameter_declaration->type = parameter_type;
4623 semantic_parameter(parameter_declaration);
4624 parameter_type = parameter_declaration->type;
4627 * we need the default promoted types for the function type
4629 parameter_type = get_default_promoted_type(parameter_type);
4631 function_parameter_t *function_parameter
4632 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4633 memset(function_parameter, 0, sizeof(function_parameter[0]));
4635 function_parameter->type = parameter_type;
4636 if (last_parameter != NULL) {
4637 last_parameter->next = function_parameter;
4639 parameters = function_parameter;
4641 last_parameter = function_parameter;
4644 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4646 new_type->function.parameters = parameters;
4647 new_type->function.unspecified_parameters = true;
4649 type = typehash_insert(new_type);
4650 if (type != new_type) {
4651 obstack_free(type_obst, new_type);
4654 declaration->type = type;
4657 static bool first_err = true;
4660 * When called with first_err set, prints the name of the current function,
4663 static void print_in_function(void)
4667 diagnosticf("%s: In function '%Y':\n",
4668 current_function->source_position.input_name,
4669 current_function->symbol);
4674 * Check if all labels are defined in the current function.
4675 * Check if all labels are used in the current function.
4677 static void check_labels(void)
4679 for (const goto_statement_t *goto_statement = goto_first;
4680 goto_statement != NULL;
4681 goto_statement = goto_statement->next) {
4682 declaration_t *label = goto_statement->label;
4685 if (label->source_position.input_name == NULL) {
4686 print_in_function();
4687 errorf(&goto_statement->base.source_position,
4688 "label '%Y' used but not defined", label->symbol);
4691 goto_first = goto_last = NULL;
4693 if (warning.unused_label) {
4694 for (const label_statement_t *label_statement = label_first;
4695 label_statement != NULL;
4696 label_statement = label_statement->next) {
4697 const declaration_t *label = label_statement->label;
4699 if (! label->used) {
4700 print_in_function();
4701 warningf(&label_statement->base.source_position,
4702 "label '%Y' defined but not used", label->symbol);
4706 label_first = label_last = NULL;
4710 * Check declarations of current_function for unused entities.
4712 static void check_declarations(void)
4714 if (warning.unused_parameter) {
4715 const scope_t *scope = ¤t_function->scope;
4717 if (is_sym_main(current_function->symbol)) {
4718 /* do not issue unused warnings for main */
4721 const declaration_t *parameter = scope->declarations;
4722 for (; parameter != NULL; parameter = parameter->next) {
4723 if (! parameter->used) {
4724 print_in_function();
4725 warningf(¶meter->source_position,
4726 "unused parameter '%Y'", parameter->symbol);
4730 if (warning.unused_variable) {
4734 static int determine_truth(expression_t const* const cond)
4737 !is_constant_expression(cond) ? 0 :
4738 fold_constant(cond) != 0 ? 1 :
4742 static bool noreturn_candidate;
4744 static void check_reachable(statement_t *const stmt)
4746 if (stmt->base.reachable)
4748 if (stmt->kind != STATEMENT_DO_WHILE)
4749 stmt->base.reachable = true;
4751 statement_t *last = stmt;
4753 switch (stmt->kind) {
4754 case STATEMENT_INVALID:
4755 case STATEMENT_EMPTY:
4756 case STATEMENT_DECLARATION:
4758 next = stmt->base.next;
4761 case STATEMENT_COMPOUND:
4762 next = stmt->compound.statements;
4765 case STATEMENT_RETURN:
4766 noreturn_candidate = false;
4769 case STATEMENT_IF: {
4770 if_statement_t const* const ifs = &stmt->ifs;
4771 int const val = determine_truth(ifs->condition);
4774 check_reachable(ifs->true_statement);
4779 if (ifs->false_statement != NULL) {
4780 check_reachable(ifs->false_statement);
4784 next = stmt->base.next;
4788 case STATEMENT_SWITCH: {
4789 switch_statement_t const *const switchs = &stmt->switchs;
4790 expression_t const *const expr = switchs->expression;
4792 if (is_constant_expression(expr)) {
4793 long const val = fold_constant(expr);
4794 case_label_statement_t * defaults = NULL;
4795 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4796 if (i->expression == NULL) {
4801 if (i->first_case <= val && val <= i->last_case) {
4802 check_reachable((statement_t*)i);
4807 if (defaults != NULL) {
4808 check_reachable((statement_t*)defaults);
4812 bool has_default = false;
4813 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4814 if (i->expression == NULL)
4817 check_reachable((statement_t*)i);
4824 next = stmt->base.next;
4828 case STATEMENT_EXPRESSION: {
4829 /* Check for noreturn function call */
4830 expression_t const *const expr = stmt->expression.expression;
4831 if (expr->kind == EXPR_CALL) {
4832 expression_t const *const func = expr->call.function;
4833 if (func->kind == EXPR_REFERENCE) {
4834 declaration_t const *const decl = func->reference.declaration;
4835 if (decl != NULL && decl->modifiers & DM_NORETURN) {
4841 next = stmt->base.next;
4845 case STATEMENT_CONTINUE: {
4846 statement_t *parent = stmt;
4848 parent = parent->base.parent;
4849 if (parent == NULL) /* continue not within loop */
4853 switch (parent->kind) {
4854 case STATEMENT_WHILE: goto continue_while;
4855 case STATEMENT_DO_WHILE: goto continue_do_while;
4856 case STATEMENT_FOR: goto continue_for;
4863 case STATEMENT_BREAK: {
4864 statement_t *parent = stmt;
4866 parent = parent->base.parent;
4867 if (parent == NULL) /* break not within loop/switch */
4870 switch (parent->kind) {
4871 case STATEMENT_SWITCH:
4872 case STATEMENT_WHILE:
4873 case STATEMENT_DO_WHILE:
4876 next = parent->base.next;
4877 goto found_break_parent;
4886 case STATEMENT_GOTO:
4887 next = stmt->gotos.label->init.statement;
4888 if (next == NULL) /* missing label */
4892 case STATEMENT_LABEL:
4893 next = stmt->label.statement;
4896 case STATEMENT_CASE_LABEL:
4897 next = stmt->case_label.statement;
4900 case STATEMENT_WHILE: {
4901 while_statement_t const *const whiles = &stmt->whiles;
4902 int const val = determine_truth(whiles->condition);
4905 check_reachable(whiles->body);
4910 next = stmt->base.next;
4914 case STATEMENT_DO_WHILE:
4915 next = stmt->do_while.body;
4918 case STATEMENT_FOR: {
4919 for_statement_t *const fors = &stmt->fors;
4921 if (fors->condition_reachable)
4923 fors->condition_reachable = true;
4925 expression_t const *const cond = fors->condition;
4927 cond == NULL ? 1 : determine_truth(cond);
4930 check_reachable(fors->body);
4935 next = stmt->base.next;
4939 case STATEMENT_MS_TRY:
4940 case STATEMENT_LEAVE:
4941 panic("unimplemented");
4944 while (next == NULL) {
4945 next = last->base.parent;
4947 noreturn_candidate = false;
4949 type_t *const type = current_function->type;
4950 assert(is_type_function(type));
4951 type_t *const ret = skip_typeref(type->function.return_type);
4952 if (warning.return_type &&
4953 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
4954 is_type_valid(ret) &&
4955 !is_sym_main(current_function->symbol)) {
4956 warningf(&stmt->base.source_position,
4957 "control reaches end of non-void function");
4962 switch (next->kind) {
4963 case STATEMENT_INVALID:
4964 case STATEMENT_EMPTY:
4965 case STATEMENT_DECLARATION:
4966 case STATEMENT_EXPRESSION:
4968 case STATEMENT_RETURN:
4969 case STATEMENT_CONTINUE:
4970 case STATEMENT_BREAK:
4971 case STATEMENT_GOTO:
4972 case STATEMENT_LEAVE:
4973 panic("invalid control flow in function");
4975 case STATEMENT_COMPOUND:
4977 case STATEMENT_SWITCH:
4978 case STATEMENT_LABEL:
4979 case STATEMENT_CASE_LABEL:
4981 next = next->base.next;
4984 case STATEMENT_WHILE: {
4986 if (next->base.reachable)
4988 next->base.reachable = true;
4990 while_statement_t const *const whiles = &next->whiles;
4991 int const val = determine_truth(whiles->condition);
4994 check_reachable(whiles->body);
5000 next = next->base.next;
5004 case STATEMENT_DO_WHILE: {
5006 if (next->base.reachable)
5008 next->base.reachable = true;
5010 do_while_statement_t const *const dw = &next->do_while;
5011 int const val = determine_truth(dw->condition);
5014 check_reachable(dw->body);
5020 next = next->base.next;
5024 case STATEMENT_FOR: {
5026 for_statement_t *const fors = &next->fors;
5028 fors->step_reachable = true;
5030 if (fors->condition_reachable)
5032 fors->condition_reachable = true;
5034 expression_t const *const cond = fors->condition;
5036 cond == NULL ? 1 : determine_truth(cond);
5039 check_reachable(fors->body);
5045 next = next->base.next;
5049 case STATEMENT_MS_TRY:
5050 panic("unimplemented");
5055 next = stmt->base.parent;
5057 warningf(&stmt->base.source_position,
5058 "control reaches end of non-void function");
5062 check_reachable(next);
5065 static void check_unreachable(statement_t const* const stmt)
5067 if (!stmt->base.reachable &&
5068 stmt->kind != STATEMENT_COMPOUND &&
5069 stmt->kind != STATEMENT_DO_WHILE &&
5070 stmt->kind != STATEMENT_FOR) {
5071 warningf(&stmt->base.source_position, "statement is unreachable");
5074 switch (stmt->kind) {
5075 case STATEMENT_INVALID:
5076 case STATEMENT_EMPTY:
5077 case STATEMENT_RETURN:
5078 case STATEMENT_DECLARATION:
5079 case STATEMENT_EXPRESSION:
5080 case STATEMENT_CONTINUE:
5081 case STATEMENT_BREAK:
5082 case STATEMENT_GOTO:
5084 case STATEMENT_LEAVE:
5087 case STATEMENT_COMPOUND:
5088 if (stmt->compound.statements)
5089 check_unreachable(stmt->compound.statements);
5093 check_unreachable(stmt->ifs.true_statement);
5094 if (stmt->ifs.false_statement != NULL)
5095 check_unreachable(stmt->ifs.false_statement);
5098 case STATEMENT_SWITCH:
5099 check_unreachable(stmt->switchs.body);
5102 case STATEMENT_LABEL:
5103 check_unreachable(stmt->label.statement);
5106 case STATEMENT_CASE_LABEL:
5107 check_unreachable(stmt->case_label.statement);
5110 case STATEMENT_WHILE:
5111 check_unreachable(stmt->whiles.body);
5114 case STATEMENT_DO_WHILE:
5115 check_unreachable(stmt->do_while.body);
5116 if (!stmt->base.reachable) {
5117 expression_t const *const cond = stmt->do_while.condition;
5118 if (determine_truth(cond) >= 0) {
5119 warningf(&cond->base.source_position,
5120 "condition of do-while-loop is unreachable");
5125 case STATEMENT_FOR: {
5126 for_statement_t const* const fors = &stmt->fors;
5128 // if init and step are unreachable, cond is unreachable, too
5129 if (!stmt->base.reachable && !fors->step_reachable) {
5130 warningf(&stmt->base.source_position, "statement is unreachable");
5132 if (!stmt->base.reachable && fors->initialisation != NULL) {
5133 warningf(&fors->initialisation->base.source_position,
5134 "initialisation of for-statement is unreachable");
5137 if (!fors->condition_reachable && fors->condition != NULL) {
5138 warningf(&fors->condition->base.source_position,
5139 "condition of for-statement is unreachable");
5142 if (!fors->step_reachable && fors->step != NULL) {
5143 warningf(&fors->step->base.source_position,
5144 "step of for-statement is unreachable");
5148 check_unreachable(stmt->fors.body);
5152 case STATEMENT_MS_TRY:
5153 panic("unimplemented");
5156 if (stmt->base.next)
5157 check_unreachable(stmt->base.next);
5160 static void parse_external_declaration(void)
5162 /* function-definitions and declarations both start with declaration
5164 declaration_specifiers_t specifiers;
5165 memset(&specifiers, 0, sizeof(specifiers));
5167 add_anchor_token(';');
5168 parse_declaration_specifiers(&specifiers);
5169 rem_anchor_token(';');
5171 /* must be a declaration */
5172 if (token.type == ';') {
5173 parse_anonymous_declaration_rest(&specifiers, append_declaration);
5177 add_anchor_token(',');
5178 add_anchor_token('=');
5179 rem_anchor_token(';');
5181 /* declarator is common to both function-definitions and declarations */
5182 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5184 rem_anchor_token(',');
5185 rem_anchor_token('=');
5186 rem_anchor_token(';');
5188 /* must be a declaration */
5189 switch (token.type) {
5192 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5196 parse_declaration_rest(ndeclaration, &specifiers, record_definition);
5200 /* must be a function definition */
5201 parse_kr_declaration_list(ndeclaration);
5203 if (token.type != '{') {
5204 parse_error_expected("while parsing function definition", '{', NULL);
5205 eat_until_matching_token(';');
5209 type_t *type = ndeclaration->type;
5211 /* note that we don't skip typerefs: the standard doesn't allow them here
5212 * (so we can't use is_type_function here) */
5213 if (type->kind != TYPE_FUNCTION) {
5214 if (is_type_valid(type)) {
5215 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5216 type, ndeclaration->symbol);
5222 /* § 6.7.5.3 (14) a function definition with () means no
5223 * parameters (and not unspecified parameters) */
5224 if (type->function.unspecified_parameters
5225 && type->function.parameters == NULL
5226 && !type->function.kr_style_parameters) {
5227 type_t *duplicate = duplicate_type(type);
5228 duplicate->function.unspecified_parameters = false;
5230 type = typehash_insert(duplicate);
5231 if (type != duplicate) {
5232 obstack_free(type_obst, duplicate);
5234 ndeclaration->type = type;
5237 declaration_t *const declaration = record_definition(ndeclaration);
5238 if (ndeclaration != declaration) {
5239 declaration->scope = ndeclaration->scope;
5241 type = skip_typeref(declaration->type);
5243 /* push function parameters and switch scope */
5244 int top = environment_top();
5245 scope_t *last_scope = scope;
5246 set_scope(&declaration->scope);
5248 declaration_t *parameter = declaration->scope.declarations;
5249 for( ; parameter != NULL; parameter = parameter->next) {
5250 if (parameter->parent_scope == &ndeclaration->scope) {
5251 parameter->parent_scope = scope;
5253 assert(parameter->parent_scope == NULL
5254 || parameter->parent_scope == scope);
5255 parameter->parent_scope = scope;
5256 if (parameter->symbol == NULL) {
5257 errorf(¶meter->source_position, "parameter name omitted");
5260 environment_push(parameter);
5263 if (declaration->init.statement != NULL) {
5264 parser_error_multiple_definition(declaration, HERE);
5267 /* parse function body */
5268 int label_stack_top = label_top();
5269 declaration_t *old_current_function = current_function;
5270 current_function = declaration;
5271 current_parent = NULL;
5273 statement_t *const body = parse_compound_statement(false);
5274 declaration->init.statement = body;
5277 check_declarations();
5278 if (warning.return_type ||
5279 warning.unreachable_code ||
5280 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5281 noreturn_candidate = true;
5282 check_reachable(body);
5283 if (warning.unreachable_code)
5284 check_unreachable(body);
5285 if (warning.missing_noreturn &&
5286 noreturn_candidate &&
5287 !(declaration->modifiers & DM_NORETURN)) {
5288 warningf(&body->base.source_position,
5289 "function '%#T' is candidate for attribute 'noreturn'",
5290 type, declaration->symbol);
5294 assert(current_parent == NULL);
5295 assert(current_function == declaration);
5296 current_function = old_current_function;
5297 label_pop_to(label_stack_top);
5300 assert(scope == &declaration->scope);
5301 set_scope(last_scope);
5302 environment_pop_to(top);
5305 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5306 source_position_t *source_position)
5308 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5310 type->bitfield.base_type = base_type;
5311 type->bitfield.size = size;
5316 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5319 declaration_t *iter = compound_declaration->scope.declarations;
5320 for( ; iter != NULL; iter = iter->next) {
5321 if (iter->namespc != NAMESPACE_NORMAL)
5324 if (iter->symbol == NULL) {
5325 type_t *type = skip_typeref(iter->type);
5326 if (is_type_compound(type)) {
5327 declaration_t *result
5328 = find_compound_entry(type->compound.declaration, symbol);
5335 if (iter->symbol == symbol) {
5343 static void parse_compound_declarators(declaration_t *struct_declaration,
5344 const declaration_specifiers_t *specifiers)
5346 declaration_t *last_declaration = struct_declaration->scope.declarations;
5347 if (last_declaration != NULL) {
5348 while(last_declaration->next != NULL) {
5349 last_declaration = last_declaration->next;
5354 declaration_t *declaration;
5356 if (token.type == ':') {
5357 source_position_t source_position = *HERE;
5360 type_t *base_type = specifiers->type;
5361 expression_t *size = parse_constant_expression();
5363 if (!is_type_integer(skip_typeref(base_type))) {
5364 errorf(HERE, "bitfield base type '%T' is not an integer type",
5368 type_t *type = make_bitfield_type(base_type, size, &source_position);
5370 declaration = allocate_declaration_zero();
5371 declaration->namespc = NAMESPACE_NORMAL;
5372 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5373 declaration->storage_class = STORAGE_CLASS_NONE;
5374 declaration->source_position = source_position;
5375 declaration->modifiers = specifiers->modifiers;
5376 declaration->type = type;
5378 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5380 type_t *orig_type = declaration->type;
5381 type_t *type = skip_typeref(orig_type);
5383 if (token.type == ':') {
5384 source_position_t source_position = *HERE;
5386 expression_t *size = parse_constant_expression();
5388 if (!is_type_integer(type)) {
5389 errorf(HERE, "bitfield base type '%T' is not an "
5390 "integer type", orig_type);
5393 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
5394 declaration->type = bitfield_type;
5396 /* TODO we ignore arrays for now... what is missing is a check
5397 * that they're at the end of the struct */
5398 if (is_type_incomplete(type) && !is_type_array(type)) {
5400 "compound member '%Y' has incomplete type '%T'",
5401 declaration->symbol, orig_type);
5402 } else if (is_type_function(type)) {
5403 errorf(HERE, "compound member '%Y' must not have function "
5404 "type '%T'", declaration->symbol, orig_type);
5409 /* make sure we don't define a symbol multiple times */
5410 symbol_t *symbol = declaration->symbol;
5411 if (symbol != NULL) {
5412 declaration_t *prev_decl
5413 = find_compound_entry(struct_declaration, symbol);
5415 if (prev_decl != NULL) {
5416 assert(prev_decl->symbol == symbol);
5417 errorf(&declaration->source_position,
5418 "multiple declarations of symbol '%Y' (declared %P)",
5419 symbol, &prev_decl->source_position);
5423 /* append declaration */
5424 if (last_declaration != NULL) {
5425 last_declaration->next = declaration;
5427 struct_declaration->scope.declarations = declaration;
5429 last_declaration = declaration;
5431 if (token.type != ',')
5441 static void parse_compound_type_entries(declaration_t *compound_declaration)
5444 add_anchor_token('}');
5446 while(token.type != '}' && token.type != T_EOF) {
5447 declaration_specifiers_t specifiers;
5448 memset(&specifiers, 0, sizeof(specifiers));
5449 parse_declaration_specifiers(&specifiers);
5451 parse_compound_declarators(compound_declaration, &specifiers);
5453 rem_anchor_token('}');
5455 if (token.type == T_EOF) {
5456 errorf(HERE, "EOF while parsing struct");
5461 static type_t *parse_typename(void)
5463 declaration_specifiers_t specifiers;
5464 memset(&specifiers, 0, sizeof(specifiers));
5465 parse_declaration_specifiers(&specifiers);
5466 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5467 /* TODO: improve error message, user does probably not know what a
5468 * storage class is...
5470 errorf(HERE, "typename may not have a storage class");
5473 type_t *result = parse_abstract_declarator(specifiers.type);
5481 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5482 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5483 expression_t *left);
5485 typedef struct expression_parser_function_t expression_parser_function_t;
5486 struct expression_parser_function_t {
5487 unsigned precedence;
5488 parse_expression_function parser;
5489 unsigned infix_precedence;
5490 parse_expression_infix_function infix_parser;
5493 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5496 * Prints an error message if an expression was expected but not read
5498 static expression_t *expected_expression_error(void)
5500 /* skip the error message if the error token was read */
5501 if (token.type != T_ERROR) {
5502 errorf(HERE, "expected expression, got token '%K'", &token);
5506 return create_invalid_expression();
5510 * Parse a string constant.
5512 static expression_t *parse_string_const(void)
5515 if (token.type == T_STRING_LITERAL) {
5516 string_t res = token.v.string;
5518 while (token.type == T_STRING_LITERAL) {
5519 res = concat_strings(&res, &token.v.string);
5522 if (token.type != T_WIDE_STRING_LITERAL) {
5523 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5524 /* note: that we use type_char_ptr here, which is already the
5525 * automatic converted type. revert_automatic_type_conversion
5526 * will construct the array type */
5527 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5528 cnst->string.value = res;
5532 wres = concat_string_wide_string(&res, &token.v.wide_string);
5534 wres = token.v.wide_string;
5539 switch (token.type) {
5540 case T_WIDE_STRING_LITERAL:
5541 wres = concat_wide_strings(&wres, &token.v.wide_string);
5544 case T_STRING_LITERAL:
5545 wres = concat_wide_string_string(&wres, &token.v.string);
5549 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5550 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5551 cnst->wide_string.value = wres;
5560 * Parse an integer constant.
5562 static expression_t *parse_int_const(void)
5564 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5565 cnst->base.source_position = *HERE;
5566 cnst->base.type = token.datatype;
5567 cnst->conste.v.int_value = token.v.intvalue;
5575 * Parse a character constant.
5577 static expression_t *parse_character_constant(void)
5579 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5581 cnst->base.source_position = *HERE;
5582 cnst->base.type = token.datatype;
5583 cnst->conste.v.character = token.v.string;
5585 if (cnst->conste.v.character.size != 1) {
5586 if (warning.multichar && (c_mode & _GNUC)) {
5588 warningf(HERE, "multi-character character constant");
5590 errorf(HERE, "more than 1 characters in character constant");
5599 * Parse a wide character constant.
5601 static expression_t *parse_wide_character_constant(void)
5603 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5605 cnst->base.source_position = *HERE;
5606 cnst->base.type = token.datatype;
5607 cnst->conste.v.wide_character = token.v.wide_string;
5609 if (cnst->conste.v.wide_character.size != 1) {
5610 if (warning.multichar && (c_mode & _GNUC)) {
5612 warningf(HERE, "multi-character character constant");
5614 errorf(HERE, "more than 1 characters in character constant");
5623 * Parse a float constant.
5625 static expression_t *parse_float_const(void)
5627 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5628 cnst->base.type = token.datatype;
5629 cnst->conste.v.float_value = token.v.floatvalue;
5636 static declaration_t *create_implicit_function(symbol_t *symbol,
5637 const source_position_t *source_position)
5639 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5640 ntype->function.return_type = type_int;
5641 ntype->function.unspecified_parameters = true;
5643 type_t *type = typehash_insert(ntype);
5644 if (type != ntype) {
5648 declaration_t *const declaration = allocate_declaration_zero();
5649 declaration->storage_class = STORAGE_CLASS_EXTERN;
5650 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5651 declaration->type = type;
5652 declaration->symbol = symbol;
5653 declaration->source_position = *source_position;
5655 bool strict_prototypes_old = warning.strict_prototypes;
5656 warning.strict_prototypes = false;
5657 record_declaration(declaration);
5658 warning.strict_prototypes = strict_prototypes_old;
5664 * Creates a return_type (func)(argument_type) function type if not
5667 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5668 type_t *argument_type2)
5670 function_parameter_t *parameter2
5671 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5672 memset(parameter2, 0, sizeof(parameter2[0]));
5673 parameter2->type = argument_type2;
5675 function_parameter_t *parameter1
5676 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5677 memset(parameter1, 0, sizeof(parameter1[0]));
5678 parameter1->type = argument_type1;
5679 parameter1->next = parameter2;
5681 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5682 type->function.return_type = return_type;
5683 type->function.parameters = parameter1;
5685 type_t *result = typehash_insert(type);
5686 if (result != type) {
5694 * Creates a return_type (func)(argument_type) function type if not
5697 * @param return_type the return type
5698 * @param argument_type the argument type
5700 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5702 function_parameter_t *parameter
5703 = obstack_alloc(type_obst, sizeof(parameter[0]));
5704 memset(parameter, 0, sizeof(parameter[0]));
5705 parameter->type = argument_type;
5707 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5708 type->function.return_type = return_type;
5709 type->function.parameters = parameter;
5711 type_t *result = typehash_insert(type);
5712 if (result != type) {
5719 static type_t *make_function_0_type(type_t *return_type)
5721 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5722 type->function.return_type = return_type;
5723 type->function.parameters = NULL;
5725 type_t *result = typehash_insert(type);
5726 if (result != type) {
5734 * Creates a function type for some function like builtins.
5736 * @param symbol the symbol describing the builtin
5738 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5740 switch(symbol->ID) {
5741 case T___builtin_alloca:
5742 return make_function_1_type(type_void_ptr, type_size_t);
5743 case T___builtin_huge_val:
5744 return make_function_0_type(type_double);
5745 case T___builtin_nan:
5746 return make_function_1_type(type_double, type_char_ptr);
5747 case T___builtin_nanf:
5748 return make_function_1_type(type_float, type_char_ptr);
5749 case T___builtin_nand:
5750 return make_function_1_type(type_long_double, type_char_ptr);
5751 case T___builtin_va_end:
5752 return make_function_1_type(type_void, type_valist);
5753 case T___builtin_expect:
5754 return make_function_2_type(type_long, type_long, type_long);
5756 internal_errorf(HERE, "not implemented builtin symbol found");
5761 * Performs automatic type cast as described in § 6.3.2.1.
5763 * @param orig_type the original type
5765 static type_t *automatic_type_conversion(type_t *orig_type)
5767 type_t *type = skip_typeref(orig_type);
5768 if (is_type_array(type)) {
5769 array_type_t *array_type = &type->array;
5770 type_t *element_type = array_type->element_type;
5771 unsigned qualifiers = array_type->base.qualifiers;
5773 return make_pointer_type(element_type, qualifiers);
5776 if (is_type_function(type)) {
5777 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5784 * reverts the automatic casts of array to pointer types and function
5785 * to function-pointer types as defined § 6.3.2.1
5787 type_t *revert_automatic_type_conversion(const expression_t *expression)
5789 switch (expression->kind) {
5790 case EXPR_REFERENCE: return expression->reference.declaration->type;
5791 case EXPR_SELECT: return expression->select.compound_entry->type;
5793 case EXPR_UNARY_DEREFERENCE: {
5794 const expression_t *const value = expression->unary.value;
5795 type_t *const type = skip_typeref(value->base.type);
5796 assert(is_type_pointer(type));
5797 return type->pointer.points_to;
5800 case EXPR_BUILTIN_SYMBOL:
5801 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5803 case EXPR_ARRAY_ACCESS: {
5804 const expression_t *array_ref = expression->array_access.array_ref;
5805 type_t *type_left = skip_typeref(array_ref->base.type);
5806 if (!is_type_valid(type_left))
5808 assert(is_type_pointer(type_left));
5809 return type_left->pointer.points_to;
5812 case EXPR_STRING_LITERAL: {
5813 size_t size = expression->string.value.size;
5814 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5817 case EXPR_WIDE_STRING_LITERAL: {
5818 size_t size = expression->wide_string.value.size;
5819 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5822 case EXPR_COMPOUND_LITERAL:
5823 return expression->compound_literal.type;
5828 return expression->base.type;
5831 static expression_t *parse_reference(void)
5833 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5835 reference_expression_t *ref = &expression->reference;
5836 symbol_t *const symbol = token.v.symbol;
5838 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5840 source_position_t source_position = token.source_position;
5843 if (declaration == NULL) {
5844 if (! strict_mode && token.type == '(') {
5845 /* an implicitly defined function */
5846 if (warning.implicit_function_declaration) {
5847 warningf(HERE, "implicit declaration of function '%Y'",
5851 declaration = create_implicit_function(symbol,
5854 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5855 return create_invalid_expression();
5859 type_t *type = declaration->type;
5861 /* we always do the auto-type conversions; the & and sizeof parser contains
5862 * code to revert this! */
5863 type = automatic_type_conversion(type);
5865 ref->declaration = declaration;
5866 ref->base.type = type;
5868 /* this declaration is used */
5869 declaration->used = true;
5871 /* check for deprecated functions */
5872 if (warning.deprecated_declarations &&
5873 declaration->modifiers & DM_DEPRECATED) {
5874 char const *const prefix = is_type_function(declaration->type) ?
5875 "function" : "variable";
5877 if (declaration->deprecated_string != NULL) {
5878 warningf(&source_position,
5879 "%s '%Y' is deprecated (declared %P): \"%s\"", prefix,
5880 declaration->symbol, &declaration->source_position,
5881 declaration->deprecated_string);
5883 warningf(&source_position,
5884 "%s '%Y' is deprecated (declared %P)", prefix,
5885 declaration->symbol, &declaration->source_position);
5892 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5896 /* TODO check if explicit cast is allowed and issue warnings/errors */
5899 static expression_t *parse_compound_literal(type_t *type)
5901 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5903 parse_initializer_env_t env;
5905 env.declaration = NULL;
5906 env.must_be_constant = false;
5907 initializer_t *initializer = parse_initializer(&env);
5910 expression->compound_literal.initializer = initializer;
5911 expression->compound_literal.type = type;
5912 expression->base.type = automatic_type_conversion(type);
5918 * Parse a cast expression.
5920 static expression_t *parse_cast(void)
5922 source_position_t source_position = token.source_position;
5924 type_t *type = parse_typename();
5926 /* matching add_anchor_token() is at call site */
5927 rem_anchor_token(')');
5930 if (token.type == '{') {
5931 return parse_compound_literal(type);
5934 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5935 cast->base.source_position = source_position;
5937 expression_t *value = parse_sub_expression(20);
5939 check_cast_allowed(value, type);
5941 cast->base.type = type;
5942 cast->unary.value = value;
5946 return create_invalid_expression();
5950 * Parse a statement expression.
5952 static expression_t *parse_statement_expression(void)
5954 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5956 statement_t *statement = parse_compound_statement(true);
5957 expression->statement.statement = statement;
5958 expression->base.source_position = statement->base.source_position;
5960 /* find last statement and use its type */
5961 type_t *type = type_void;
5962 const statement_t *stmt = statement->compound.statements;
5964 while (stmt->base.next != NULL)
5965 stmt = stmt->base.next;
5967 if (stmt->kind == STATEMENT_EXPRESSION) {
5968 type = stmt->expression.expression->base.type;
5971 warningf(&expression->base.source_position, "empty statement expression ({})");
5973 expression->base.type = type;
5979 return create_invalid_expression();
5983 * Parse a parenthesized expression.
5985 static expression_t *parse_parenthesized_expression(void)
5988 add_anchor_token(')');
5990 switch(token.type) {
5992 /* gcc extension: a statement expression */
5993 return parse_statement_expression();
5997 return parse_cast();
5999 if (is_typedef_symbol(token.v.symbol)) {
6000 return parse_cast();
6004 expression_t *result = parse_expression();
6005 rem_anchor_token(')');
6010 return create_invalid_expression();
6013 static expression_t *parse_function_keyword(void)
6018 if (current_function == NULL) {
6019 errorf(HERE, "'__func__' used outside of a function");
6022 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6023 expression->base.type = type_char_ptr;
6024 expression->funcname.kind = FUNCNAME_FUNCTION;
6029 static expression_t *parse_pretty_function_keyword(void)
6031 eat(T___PRETTY_FUNCTION__);
6033 if (current_function == NULL) {
6034 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6037 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6038 expression->base.type = type_char_ptr;
6039 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6044 static expression_t *parse_funcsig_keyword(void)
6048 if (current_function == NULL) {
6049 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6052 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6053 expression->base.type = type_char_ptr;
6054 expression->funcname.kind = FUNCNAME_FUNCSIG;
6059 static expression_t *parse_funcdname_keyword(void)
6061 eat(T___FUNCDNAME__);
6063 if (current_function == NULL) {
6064 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6067 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6068 expression->base.type = type_char_ptr;
6069 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6074 static designator_t *parse_designator(void)
6076 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6077 result->source_position = *HERE;
6079 if (token.type != T_IDENTIFIER) {
6080 parse_error_expected("while parsing member designator",
6081 T_IDENTIFIER, NULL);
6084 result->symbol = token.v.symbol;
6087 designator_t *last_designator = result;
6089 if (token.type == '.') {
6091 if (token.type != T_IDENTIFIER) {
6092 parse_error_expected("while parsing member designator",
6093 T_IDENTIFIER, NULL);
6096 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6097 designator->source_position = *HERE;
6098 designator->symbol = token.v.symbol;
6101 last_designator->next = designator;
6102 last_designator = designator;
6105 if (token.type == '[') {
6107 add_anchor_token(']');
6108 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6109 designator->source_position = *HERE;
6110 designator->array_index = parse_expression();
6111 rem_anchor_token(']');
6113 if (designator->array_index == NULL) {
6117 last_designator->next = designator;
6118 last_designator = designator;
6130 * Parse the __builtin_offsetof() expression.
6132 static expression_t *parse_offsetof(void)
6134 eat(T___builtin_offsetof);
6136 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6137 expression->base.type = type_size_t;
6140 add_anchor_token(',');
6141 type_t *type = parse_typename();
6142 rem_anchor_token(',');
6144 add_anchor_token(')');
6145 designator_t *designator = parse_designator();
6146 rem_anchor_token(')');
6149 expression->offsetofe.type = type;
6150 expression->offsetofe.designator = designator;
6153 memset(&path, 0, sizeof(path));
6154 path.top_type = type;
6155 path.path = NEW_ARR_F(type_path_entry_t, 0);
6157 descend_into_subtype(&path);
6159 if (!walk_designator(&path, designator, true)) {
6160 return create_invalid_expression();
6163 DEL_ARR_F(path.path);
6167 return create_invalid_expression();
6171 * Parses a _builtin_va_start() expression.
6173 static expression_t *parse_va_start(void)
6175 eat(T___builtin_va_start);
6177 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6180 add_anchor_token(',');
6181 expression->va_starte.ap = parse_assignment_expression();
6182 rem_anchor_token(',');
6184 expression_t *const expr = parse_assignment_expression();
6185 if (expr->kind == EXPR_REFERENCE) {
6186 declaration_t *const decl = expr->reference.declaration;
6188 return create_invalid_expression();
6189 if (decl->parent_scope == ¤t_function->scope &&
6190 decl->next == NULL) {
6191 expression->va_starte.parameter = decl;
6196 errorf(&expr->base.source_position,
6197 "second argument of 'va_start' must be last parameter of the current function");
6199 return create_invalid_expression();
6203 * Parses a _builtin_va_arg() expression.
6205 static expression_t *parse_va_arg(void)
6207 eat(T___builtin_va_arg);
6209 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6212 expression->va_arge.ap = parse_assignment_expression();
6214 expression->base.type = parse_typename();
6219 return create_invalid_expression();
6222 static expression_t *parse_builtin_symbol(void)
6224 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6226 symbol_t *symbol = token.v.symbol;
6228 expression->builtin_symbol.symbol = symbol;
6231 type_t *type = get_builtin_symbol_type(symbol);
6232 type = automatic_type_conversion(type);
6234 expression->base.type = type;
6239 * Parses a __builtin_constant() expression.
6241 static expression_t *parse_builtin_constant(void)
6243 eat(T___builtin_constant_p);
6245 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6248 add_anchor_token(')');
6249 expression->builtin_constant.value = parse_assignment_expression();
6250 rem_anchor_token(')');
6252 expression->base.type = type_int;
6256 return create_invalid_expression();
6260 * Parses a __builtin_prefetch() expression.
6262 static expression_t *parse_builtin_prefetch(void)
6264 eat(T___builtin_prefetch);
6266 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6269 add_anchor_token(')');
6270 expression->builtin_prefetch.adr = parse_assignment_expression();
6271 if (token.type == ',') {
6273 expression->builtin_prefetch.rw = parse_assignment_expression();
6275 if (token.type == ',') {
6277 expression->builtin_prefetch.locality = parse_assignment_expression();
6279 rem_anchor_token(')');
6281 expression->base.type = type_void;
6285 return create_invalid_expression();
6289 * Parses a __builtin_is_*() compare expression.
6291 static expression_t *parse_compare_builtin(void)
6293 expression_t *expression;
6295 switch(token.type) {
6296 case T___builtin_isgreater:
6297 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6299 case T___builtin_isgreaterequal:
6300 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6302 case T___builtin_isless:
6303 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6305 case T___builtin_islessequal:
6306 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6308 case T___builtin_islessgreater:
6309 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6311 case T___builtin_isunordered:
6312 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6315 internal_errorf(HERE, "invalid compare builtin found");
6318 expression->base.source_position = *HERE;
6322 expression->binary.left = parse_assignment_expression();
6324 expression->binary.right = parse_assignment_expression();
6327 type_t *const orig_type_left = expression->binary.left->base.type;
6328 type_t *const orig_type_right = expression->binary.right->base.type;
6330 type_t *const type_left = skip_typeref(orig_type_left);
6331 type_t *const type_right = skip_typeref(orig_type_right);
6332 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6333 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6334 type_error_incompatible("invalid operands in comparison",
6335 &expression->base.source_position, orig_type_left, orig_type_right);
6338 semantic_comparison(&expression->binary);
6343 return create_invalid_expression();
6348 * Parses a __builtin_expect() expression.
6350 static expression_t *parse_builtin_expect(void)
6352 eat(T___builtin_expect);
6354 expression_t *expression
6355 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6358 expression->binary.left = parse_assignment_expression();
6360 expression->binary.right = parse_constant_expression();
6363 expression->base.type = expression->binary.left->base.type;
6367 return create_invalid_expression();
6372 * Parses a MS assume() expression.
6374 static expression_t *parse_assume(void)
6378 expression_t *expression
6379 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6382 add_anchor_token(')');
6383 expression->unary.value = parse_assignment_expression();
6384 rem_anchor_token(')');
6387 expression->base.type = type_void;
6390 return create_invalid_expression();
6394 * Parse a microsoft __noop expression.
6396 static expression_t *parse_noop_expression(void)
6398 source_position_t source_position = *HERE;
6401 if (token.type == '(') {
6402 /* parse arguments */
6404 add_anchor_token(')');
6405 add_anchor_token(',');
6407 if (token.type != ')') {
6409 (void)parse_assignment_expression();
6410 if (token.type != ',')
6416 rem_anchor_token(',');
6417 rem_anchor_token(')');
6420 /* the result is a (int)0 */
6421 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6422 cnst->base.source_position = source_position;
6423 cnst->base.type = type_int;
6424 cnst->conste.v.int_value = 0;
6425 cnst->conste.is_ms_noop = true;
6430 return create_invalid_expression();
6434 * Parses a primary expression.
6436 static expression_t *parse_primary_expression(void)
6438 switch (token.type) {
6439 case T_INTEGER: return parse_int_const();
6440 case T_CHARACTER_CONSTANT: return parse_character_constant();
6441 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6442 case T_FLOATINGPOINT: return parse_float_const();
6443 case T_STRING_LITERAL:
6444 case T_WIDE_STRING_LITERAL: return parse_string_const();
6445 case T_IDENTIFIER: return parse_reference();
6446 case T___FUNCTION__:
6447 case T___func__: return parse_function_keyword();
6448 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6449 case T___FUNCSIG__: return parse_funcsig_keyword();
6450 case T___FUNCDNAME__: return parse_funcdname_keyword();
6451 case T___builtin_offsetof: return parse_offsetof();
6452 case T___builtin_va_start: return parse_va_start();
6453 case T___builtin_va_arg: return parse_va_arg();
6454 case T___builtin_expect:
6455 case T___builtin_alloca:
6456 case T___builtin_nan:
6457 case T___builtin_nand:
6458 case T___builtin_nanf:
6459 case T___builtin_huge_val:
6460 case T___builtin_va_end: return parse_builtin_symbol();
6461 case T___builtin_isgreater:
6462 case T___builtin_isgreaterequal:
6463 case T___builtin_isless:
6464 case T___builtin_islessequal:
6465 case T___builtin_islessgreater:
6466 case T___builtin_isunordered: return parse_compare_builtin();
6467 case T___builtin_constant_p: return parse_builtin_constant();
6468 case T___builtin_prefetch: return parse_builtin_prefetch();
6469 case T__assume: return parse_assume();
6471 case '(': return parse_parenthesized_expression();
6472 case T___noop: return parse_noop_expression();
6475 errorf(HERE, "unexpected token %K, expected an expression", &token);
6476 return create_invalid_expression();
6480 * Check if the expression has the character type and issue a warning then.
6482 static void check_for_char_index_type(const expression_t *expression)
6484 type_t *const type = expression->base.type;
6485 const type_t *const base_type = skip_typeref(type);
6487 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6488 warning.char_subscripts) {
6489 warningf(&expression->base.source_position,
6490 "array subscript has type '%T'", type);
6494 static expression_t *parse_array_expression(unsigned precedence,
6500 add_anchor_token(']');
6502 expression_t *inside = parse_expression();
6504 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6506 array_access_expression_t *array_access = &expression->array_access;
6508 type_t *const orig_type_left = left->base.type;
6509 type_t *const orig_type_inside = inside->base.type;
6511 type_t *const type_left = skip_typeref(orig_type_left);
6512 type_t *const type_inside = skip_typeref(orig_type_inside);
6514 type_t *return_type;
6515 if (is_type_pointer(type_left)) {
6516 return_type = type_left->pointer.points_to;
6517 array_access->array_ref = left;
6518 array_access->index = inside;
6519 check_for_char_index_type(inside);
6520 } else if (is_type_pointer(type_inside)) {
6521 return_type = type_inside->pointer.points_to;
6522 array_access->array_ref = inside;
6523 array_access->index = left;
6524 array_access->flipped = true;
6525 check_for_char_index_type(left);
6527 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6529 "array access on object with non-pointer types '%T', '%T'",
6530 orig_type_left, orig_type_inside);
6532 return_type = type_error_type;
6533 array_access->array_ref = create_invalid_expression();
6536 rem_anchor_token(']');
6537 if (token.type != ']') {
6538 parse_error_expected("Problem while parsing array access", ']', NULL);
6543 return_type = automatic_type_conversion(return_type);
6544 expression->base.type = return_type;
6549 static expression_t *parse_typeprop(expression_kind_t const kind,
6550 source_position_t const pos,
6551 unsigned const precedence)
6553 expression_t *tp_expression = allocate_expression_zero(kind);
6554 tp_expression->base.type = type_size_t;
6555 tp_expression->base.source_position = pos;
6557 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6559 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6561 add_anchor_token(')');
6562 type_t* const orig_type = parse_typename();
6563 tp_expression->typeprop.type = orig_type;
6565 type_t const* const type = skip_typeref(orig_type);
6566 char const* const wrong_type =
6567 is_type_incomplete(type) ? "incomplete" :
6568 type->kind == TYPE_FUNCTION ? "function designator" :
6569 type->kind == TYPE_BITFIELD ? "bitfield" :
6571 if (wrong_type != NULL) {
6572 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6573 what, wrong_type, type);
6576 rem_anchor_token(')');
6579 expression_t *expression = parse_sub_expression(precedence);
6581 type_t* const orig_type = revert_automatic_type_conversion(expression);
6582 expression->base.type = orig_type;
6584 type_t const* const type = skip_typeref(orig_type);
6585 char const* const wrong_type =
6586 is_type_incomplete(type) ? "incomplete" :
6587 type->kind == TYPE_FUNCTION ? "function designator" :
6588 type->kind == TYPE_BITFIELD ? "bitfield" :
6590 if (wrong_type != NULL) {
6591 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6594 tp_expression->typeprop.type = expression->base.type;
6595 tp_expression->typeprop.tp_expression = expression;
6598 return tp_expression;
6600 return create_invalid_expression();
6603 static expression_t *parse_sizeof(unsigned precedence)
6605 source_position_t pos = *HERE;
6607 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6610 static expression_t *parse_alignof(unsigned precedence)
6612 source_position_t pos = *HERE;
6614 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6617 static expression_t *parse_select_expression(unsigned precedence,
6618 expression_t *compound)
6621 assert(token.type == '.' || token.type == T_MINUSGREATER);
6623 bool is_pointer = (token.type == T_MINUSGREATER);
6626 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6627 select->select.compound = compound;
6629 if (token.type != T_IDENTIFIER) {
6630 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6633 symbol_t *symbol = token.v.symbol;
6634 select->select.symbol = symbol;
6637 type_t *const orig_type = compound->base.type;
6638 type_t *const type = skip_typeref(orig_type);
6640 type_t *type_left = type;
6642 if (!is_type_pointer(type)) {
6643 if (is_type_valid(type)) {
6644 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6646 return create_invalid_expression();
6648 type_left = type->pointer.points_to;
6650 type_left = skip_typeref(type_left);
6652 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6653 type_left->kind != TYPE_COMPOUND_UNION) {
6654 if (is_type_valid(type_left)) {
6655 errorf(HERE, "request for member '%Y' in something not a struct or "
6656 "union, but '%T'", symbol, type_left);
6658 return create_invalid_expression();
6661 declaration_t *const declaration = type_left->compound.declaration;
6663 if (!declaration->init.complete) {
6664 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6666 return create_invalid_expression();
6669 declaration_t *iter = find_compound_entry(declaration, symbol);
6671 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6672 return create_invalid_expression();
6675 /* we always do the auto-type conversions; the & and sizeof parser contains
6676 * code to revert this! */
6677 type_t *expression_type = automatic_type_conversion(iter->type);
6679 select->select.compound_entry = iter;
6680 select->base.type = expression_type;
6682 type_t *skipped = skip_typeref(iter->type);
6683 if (skipped->kind == TYPE_BITFIELD) {
6684 select->base.type = skipped->bitfield.base_type;
6690 static void check_call_argument(const function_parameter_t *parameter,
6691 call_argument_t *argument)
6693 type_t *expected_type = parameter->type;
6694 type_t *expected_type_skip = skip_typeref(expected_type);
6695 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6696 expression_t *arg_expr = argument->expression;
6698 /* handle transparent union gnu extension */
6699 if (is_type_union(expected_type_skip)
6700 && (expected_type_skip->base.modifiers
6701 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6702 declaration_t *union_decl = expected_type_skip->compound.declaration;
6704 declaration_t *declaration = union_decl->scope.declarations;
6705 type_t *best_type = NULL;
6706 for ( ; declaration != NULL; declaration = declaration->next) {
6707 type_t *decl_type = declaration->type;
6708 error = semantic_assign(decl_type, arg_expr);
6709 if (error == ASSIGN_ERROR_INCOMPATIBLE
6710 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6713 if (error == ASSIGN_SUCCESS) {
6714 best_type = decl_type;
6715 } else if (best_type == NULL) {
6716 best_type = decl_type;
6720 if (best_type != NULL) {
6721 expected_type = best_type;
6725 error = semantic_assign(expected_type, arg_expr);
6726 argument->expression = create_implicit_cast(argument->expression,
6729 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6730 report_assign_error(error, expected_type, arg_expr, "function call",
6731 &arg_expr->base.source_position);
6735 * Parse a call expression, ie. expression '( ... )'.
6737 * @param expression the function address
6739 static expression_t *parse_call_expression(unsigned precedence,
6740 expression_t *expression)
6743 expression_t *result = allocate_expression_zero(EXPR_CALL);
6744 result->base.source_position = expression->base.source_position;
6746 call_expression_t *call = &result->call;
6747 call->function = expression;
6749 type_t *const orig_type = expression->base.type;
6750 type_t *const type = skip_typeref(orig_type);
6752 function_type_t *function_type = NULL;
6753 if (is_type_pointer(type)) {
6754 type_t *const to_type = skip_typeref(type->pointer.points_to);
6756 if (is_type_function(to_type)) {
6757 function_type = &to_type->function;
6758 call->base.type = function_type->return_type;
6762 if (function_type == NULL && is_type_valid(type)) {
6763 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6766 /* parse arguments */
6768 add_anchor_token(')');
6769 add_anchor_token(',');
6771 if (token.type != ')') {
6772 call_argument_t *last_argument = NULL;
6775 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6777 argument->expression = parse_assignment_expression();
6778 if (last_argument == NULL) {
6779 call->arguments = argument;
6781 last_argument->next = argument;
6783 last_argument = argument;
6785 if (token.type != ',')
6790 rem_anchor_token(',');
6791 rem_anchor_token(')');
6794 if (function_type == NULL)
6797 function_parameter_t *parameter = function_type->parameters;
6798 call_argument_t *argument = call->arguments;
6799 if (!function_type->unspecified_parameters) {
6800 for( ; parameter != NULL && argument != NULL;
6801 parameter = parameter->next, argument = argument->next) {
6802 check_call_argument(parameter, argument);
6805 if (parameter != NULL) {
6806 errorf(HERE, "too few arguments to function '%E'", expression);
6807 } else if (argument != NULL && !function_type->variadic) {
6808 errorf(HERE, "too many arguments to function '%E'", expression);
6812 /* do default promotion */
6813 for( ; argument != NULL; argument = argument->next) {
6814 type_t *type = argument->expression->base.type;
6816 type = get_default_promoted_type(type);
6818 argument->expression
6819 = create_implicit_cast(argument->expression, type);
6822 check_format(&result->call);
6826 return create_invalid_expression();
6829 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6831 static bool same_compound_type(const type_t *type1, const type_t *type2)
6834 is_type_compound(type1) &&
6835 type1->kind == type2->kind &&
6836 type1->compound.declaration == type2->compound.declaration;
6840 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6842 * @param expression the conditional expression
6844 static expression_t *parse_conditional_expression(unsigned precedence,
6845 expression_t *expression)
6847 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6849 conditional_expression_t *conditional = &result->conditional;
6850 conditional->base.source_position = *HERE;
6851 conditional->condition = expression;
6854 add_anchor_token(':');
6857 type_t *const condition_type_orig = expression->base.type;
6858 type_t *const condition_type = skip_typeref(condition_type_orig);
6859 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6860 type_error("expected a scalar type in conditional condition",
6861 &expression->base.source_position, condition_type_orig);
6864 expression_t *true_expression = parse_expression();
6865 rem_anchor_token(':');
6867 expression_t *false_expression = parse_sub_expression(precedence);
6869 type_t *const orig_true_type = true_expression->base.type;
6870 type_t *const orig_false_type = false_expression->base.type;
6871 type_t *const true_type = skip_typeref(orig_true_type);
6872 type_t *const false_type = skip_typeref(orig_false_type);
6875 type_t *result_type;
6876 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6877 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6878 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6879 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6880 warningf(&conditional->base.source_position,
6881 "ISO C forbids conditional expression with only one void side");
6883 result_type = type_void;
6884 } else if (is_type_arithmetic(true_type)
6885 && is_type_arithmetic(false_type)) {
6886 result_type = semantic_arithmetic(true_type, false_type);
6888 true_expression = create_implicit_cast(true_expression, result_type);
6889 false_expression = create_implicit_cast(false_expression, result_type);
6891 conditional->true_expression = true_expression;
6892 conditional->false_expression = false_expression;
6893 conditional->base.type = result_type;
6894 } else if (same_compound_type(true_type, false_type)) {
6895 /* just take 1 of the 2 types */
6896 result_type = true_type;
6897 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6898 type_t *pointer_type;
6900 expression_t *other_expression;
6901 if (is_type_pointer(true_type) &&
6902 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6903 pointer_type = true_type;
6904 other_type = false_type;
6905 other_expression = false_expression;
6907 pointer_type = false_type;
6908 other_type = true_type;
6909 other_expression = true_expression;
6912 if (is_null_pointer_constant(other_expression)) {
6913 result_type = pointer_type;
6914 } else if (is_type_pointer(other_type)) {
6915 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6916 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6919 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6920 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6922 } else if (types_compatible(get_unqualified_type(to1),
6923 get_unqualified_type(to2))) {
6926 warningf(&conditional->base.source_position,
6927 "pointer types '%T' and '%T' in conditional expression are incompatible",
6928 true_type, false_type);
6932 type_t *const copy = duplicate_type(to);
6933 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6935 type_t *const type = typehash_insert(copy);
6939 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6940 } else if (is_type_integer(other_type)) {
6941 warningf(&conditional->base.source_position,
6942 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6943 result_type = pointer_type;
6945 type_error_incompatible("while parsing conditional",
6946 &expression->base.source_position, true_type, false_type);
6947 result_type = type_error_type;
6950 /* TODO: one pointer to void*, other some pointer */
6952 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6953 type_error_incompatible("while parsing conditional",
6954 &conditional->base.source_position, true_type,
6957 result_type = type_error_type;
6960 conditional->true_expression
6961 = create_implicit_cast(true_expression, result_type);
6962 conditional->false_expression
6963 = create_implicit_cast(false_expression, result_type);
6964 conditional->base.type = result_type;
6967 return create_invalid_expression();
6971 * Parse an extension expression.
6973 static expression_t *parse_extension(unsigned precedence)
6975 eat(T___extension__);
6977 /* TODO enable extensions */
6978 expression_t *expression = parse_sub_expression(precedence);
6979 /* TODO disable extensions */
6984 * Parse a __builtin_classify_type() expression.
6986 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6988 eat(T___builtin_classify_type);
6990 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6991 result->base.type = type_int;
6994 add_anchor_token(')');
6995 expression_t *expression = parse_sub_expression(precedence);
6996 rem_anchor_token(')');
6998 result->classify_type.type_expression = expression;
7002 return create_invalid_expression();
7005 static bool check_pointer_arithmetic(const source_position_t *source_position,
7006 type_t *pointer_type,
7007 type_t *orig_pointer_type)
7009 type_t *points_to = pointer_type->pointer.points_to;
7010 points_to = skip_typeref(points_to);
7012 if (is_type_incomplete(points_to)) {
7013 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7014 errorf(source_position,
7015 "arithmetic with pointer to incomplete type '%T' not allowed",
7018 } else if (warning.pointer_arith) {
7019 warningf(source_position,
7020 "pointer of type '%T' used in arithmetic",
7023 } else if (is_type_function(points_to)) {
7024 if (!(c_mode && _GNUC)) {
7025 errorf(source_position,
7026 "arithmetic with pointer to function type '%T' not allowed",
7029 } else if (warning.pointer_arith) {
7030 warningf(source_position,
7031 "pointer to a function '%T' used in arithmetic",
7038 static void semantic_incdec(unary_expression_t *expression)
7040 type_t *const orig_type = expression->value->base.type;
7041 type_t *const type = skip_typeref(orig_type);
7042 if (is_type_pointer(type)) {
7043 if (!check_pointer_arithmetic(&expression->base.source_position,
7047 } else if (!is_type_real(type) && is_type_valid(type)) {
7048 /* TODO: improve error message */
7049 errorf(&expression->base.source_position,
7050 "operation needs an arithmetic or pointer type");
7053 expression->base.type = orig_type;
7056 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7058 type_t *const orig_type = expression->value->base.type;
7059 type_t *const type = skip_typeref(orig_type);
7060 if (!is_type_arithmetic(type)) {
7061 if (is_type_valid(type)) {
7062 /* TODO: improve error message */
7063 errorf(&expression->base.source_position,
7064 "operation needs an arithmetic type");
7069 expression->base.type = orig_type;
7072 static void semantic_not(unary_expression_t *expression)
7074 type_t *const orig_type = expression->value->base.type;
7075 type_t *const type = skip_typeref(orig_type);
7076 if (!is_type_scalar(type) && is_type_valid(type)) {
7077 errorf(&expression->base.source_position,
7078 "operand of ! must be of scalar type");
7081 expression->base.type = type_int;
7084 static void semantic_unexpr_integer(unary_expression_t *expression)
7086 type_t *const orig_type = expression->value->base.type;
7087 type_t *const type = skip_typeref(orig_type);
7088 if (!is_type_integer(type)) {
7089 if (is_type_valid(type)) {
7090 errorf(&expression->base.source_position,
7091 "operand of ~ must be of integer type");
7096 expression->base.type = orig_type;
7099 static void semantic_dereference(unary_expression_t *expression)
7101 type_t *const orig_type = expression->value->base.type;
7102 type_t *const type = skip_typeref(orig_type);
7103 if (!is_type_pointer(type)) {
7104 if (is_type_valid(type)) {
7105 errorf(&expression->base.source_position,
7106 "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
7111 type_t *result_type = type->pointer.points_to;
7112 result_type = automatic_type_conversion(result_type);
7113 expression->base.type = result_type;
7116 static void set_address_taken(expression_t *expression, bool may_be_register)
7118 if (expression->kind != EXPR_REFERENCE)
7121 declaration_t *const declaration = expression->reference.declaration;
7122 /* happens for parse errors */
7123 if (declaration == NULL)
7126 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7127 errorf(&expression->base.source_position,
7128 "address of register variable '%Y' requested",
7129 declaration->symbol);
7131 declaration->address_taken = 1;
7136 * Check the semantic of the address taken expression.
7138 static void semantic_take_addr(unary_expression_t *expression)
7140 expression_t *value = expression->value;
7141 value->base.type = revert_automatic_type_conversion(value);
7143 type_t *orig_type = value->base.type;
7144 if (!is_type_valid(orig_type))
7147 set_address_taken(value, false);
7149 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7152 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7153 static expression_t *parse_##unexpression_type(unsigned precedence) \
7155 expression_t *unary_expression \
7156 = allocate_expression_zero(unexpression_type); \
7157 unary_expression->base.source_position = *HERE; \
7159 unary_expression->unary.value = parse_sub_expression(precedence); \
7161 sfunc(&unary_expression->unary); \
7163 return unary_expression; \
7166 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7167 semantic_unexpr_arithmetic)
7168 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7169 semantic_unexpr_arithmetic)
7170 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7172 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7173 semantic_dereference)
7174 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7176 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7177 semantic_unexpr_integer)
7178 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7180 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7183 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7185 static expression_t *parse_##unexpression_type(unsigned precedence, \
7186 expression_t *left) \
7188 (void) precedence; \
7190 expression_t *unary_expression \
7191 = allocate_expression_zero(unexpression_type); \
7192 unary_expression->base.source_position = *HERE; \
7194 unary_expression->unary.value = left; \
7196 sfunc(&unary_expression->unary); \
7198 return unary_expression; \
7201 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7202 EXPR_UNARY_POSTFIX_INCREMENT,
7204 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7205 EXPR_UNARY_POSTFIX_DECREMENT,
7208 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7210 /* TODO: handle complex + imaginary types */
7212 /* § 6.3.1.8 Usual arithmetic conversions */
7213 if (type_left == type_long_double || type_right == type_long_double) {
7214 return type_long_double;
7215 } else if (type_left == type_double || type_right == type_double) {
7217 } else if (type_left == type_float || type_right == type_float) {
7221 type_left = promote_integer(type_left);
7222 type_right = promote_integer(type_right);
7224 if (type_left == type_right)
7227 bool const signed_left = is_type_signed(type_left);
7228 bool const signed_right = is_type_signed(type_right);
7229 atomic_type_kind_t const rank_left = get_rank(type_left);
7230 atomic_type_kind_t const rank_right = get_rank(type_right);
7232 if (signed_left == signed_right)
7233 return rank_left >= rank_right ? type_left : type_right;
7235 atomic_type_kind_t s_rank;
7236 atomic_type_kind_t u_rank;
7242 u_rank = rank_right;
7243 u_type = type_right;
7245 s_rank = rank_right;
7246 s_type = type_right;
7251 if (u_rank >= s_rank)
7254 if (get_atomic_type_size(s_rank) > get_atomic_type_size(u_rank))
7258 case ATOMIC_TYPE_INT: return type_int;
7259 case ATOMIC_TYPE_LONG: return type_long;
7260 case ATOMIC_TYPE_LONGLONG: return type_long_long;
7262 default: panic("invalid atomic type");
7267 * Check the semantic restrictions for a binary expression.
7269 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7271 expression_t *const left = expression->left;
7272 expression_t *const right = expression->right;
7273 type_t *const orig_type_left = left->base.type;
7274 type_t *const orig_type_right = right->base.type;
7275 type_t *const type_left = skip_typeref(orig_type_left);
7276 type_t *const type_right = skip_typeref(orig_type_right);
7278 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7279 /* TODO: improve error message */
7280 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7281 errorf(&expression->base.source_position,
7282 "operation needs arithmetic types");
7287 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7288 expression->left = create_implicit_cast(left, arithmetic_type);
7289 expression->right = create_implicit_cast(right, arithmetic_type);
7290 expression->base.type = arithmetic_type;
7293 static void semantic_shift_op(binary_expression_t *expression)
7295 expression_t *const left = expression->left;
7296 expression_t *const right = expression->right;
7297 type_t *const orig_type_left = left->base.type;
7298 type_t *const orig_type_right = right->base.type;
7299 type_t * type_left = skip_typeref(orig_type_left);
7300 type_t * type_right = skip_typeref(orig_type_right);
7302 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7303 /* TODO: improve error message */
7304 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7305 errorf(&expression->base.source_position,
7306 "operands of shift operation must have integer types");
7311 type_left = promote_integer(type_left);
7312 type_right = promote_integer(type_right);
7314 expression->left = create_implicit_cast(left, type_left);
7315 expression->right = create_implicit_cast(right, type_right);
7316 expression->base.type = type_left;
7319 static void semantic_add(binary_expression_t *expression)
7321 expression_t *const left = expression->left;
7322 expression_t *const right = expression->right;
7323 type_t *const orig_type_left = left->base.type;
7324 type_t *const orig_type_right = right->base.type;
7325 type_t *const type_left = skip_typeref(orig_type_left);
7326 type_t *const type_right = skip_typeref(orig_type_right);
7329 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7330 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7331 expression->left = create_implicit_cast(left, arithmetic_type);
7332 expression->right = create_implicit_cast(right, arithmetic_type);
7333 expression->base.type = arithmetic_type;
7335 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7336 check_pointer_arithmetic(&expression->base.source_position,
7337 type_left, orig_type_left);
7338 expression->base.type = type_left;
7339 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7340 check_pointer_arithmetic(&expression->base.source_position,
7341 type_right, orig_type_right);
7342 expression->base.type = type_right;
7343 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7344 errorf(&expression->base.source_position,
7345 "invalid operands to binary + ('%T', '%T')",
7346 orig_type_left, orig_type_right);
7350 static void semantic_sub(binary_expression_t *expression)
7352 expression_t *const left = expression->left;
7353 expression_t *const right = expression->right;
7354 type_t *const orig_type_left = left->base.type;
7355 type_t *const orig_type_right = right->base.type;
7356 type_t *const type_left = skip_typeref(orig_type_left);
7357 type_t *const type_right = skip_typeref(orig_type_right);
7358 source_position_t const *const pos = &expression->base.source_position;
7361 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7362 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7363 expression->left = create_implicit_cast(left, arithmetic_type);
7364 expression->right = create_implicit_cast(right, arithmetic_type);
7365 expression->base.type = arithmetic_type;
7367 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7368 check_pointer_arithmetic(&expression->base.source_position,
7369 type_left, orig_type_left);
7370 expression->base.type = type_left;
7371 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7372 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7373 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7374 if (!types_compatible(unqual_left, unqual_right)) {
7376 "subtracting pointers to incompatible types '%T' and '%T'",
7377 orig_type_left, orig_type_right);
7378 } else if (!is_type_object(unqual_left)) {
7379 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7380 warningf(pos, "subtracting pointers to void");
7382 errorf(pos, "subtracting pointers to non-object types '%T'",
7386 expression->base.type = type_ptrdiff_t;
7387 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7388 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7389 orig_type_left, orig_type_right);
7394 * Check the semantics of comparison expressions.
7396 * @param expression The expression to check.
7398 static void semantic_comparison(binary_expression_t *expression)
7400 expression_t *left = expression->left;
7401 expression_t *right = expression->right;
7402 type_t *orig_type_left = left->base.type;
7403 type_t *orig_type_right = right->base.type;
7405 type_t *type_left = skip_typeref(orig_type_left);
7406 type_t *type_right = skip_typeref(orig_type_right);
7408 /* TODO non-arithmetic types */
7409 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7410 /* test for signed vs unsigned compares */
7411 if (warning.sign_compare &&
7412 (expression->base.kind != EXPR_BINARY_EQUAL &&
7413 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7414 (is_type_signed(type_left) != is_type_signed(type_right))) {
7416 /* check if 1 of the operands is a constant, in this case we just
7417 * check wether we can safely represent the resulting constant in
7418 * the type of the other operand. */
7419 expression_t *const_expr = NULL;
7420 expression_t *other_expr = NULL;
7422 if (is_constant_expression(left)) {
7425 } else if (is_constant_expression(right)) {
7430 if (const_expr != NULL) {
7431 type_t *other_type = skip_typeref(other_expr->base.type);
7432 long val = fold_constant(const_expr);
7433 /* TODO: check if val can be represented by other_type */
7437 warningf(&expression->base.source_position,
7438 "comparison between signed and unsigned");
7440 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7441 expression->left = create_implicit_cast(left, arithmetic_type);
7442 expression->right = create_implicit_cast(right, arithmetic_type);
7443 expression->base.type = arithmetic_type;
7444 if (warning.float_equal &&
7445 (expression->base.kind == EXPR_BINARY_EQUAL ||
7446 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7447 is_type_float(arithmetic_type)) {
7448 warningf(&expression->base.source_position,
7449 "comparing floating point with == or != is unsafe");
7451 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7452 /* TODO check compatibility */
7453 } else if (is_type_pointer(type_left)) {
7454 expression->right = create_implicit_cast(right, type_left);
7455 } else if (is_type_pointer(type_right)) {
7456 expression->left = create_implicit_cast(left, type_right);
7457 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7458 type_error_incompatible("invalid operands in comparison",
7459 &expression->base.source_position,
7460 type_left, type_right);
7462 expression->base.type = type_int;
7466 * Checks if a compound type has constant fields.
7468 static bool has_const_fields(const compound_type_t *type)
7470 const scope_t *scope = &type->declaration->scope;
7471 const declaration_t *declaration = scope->declarations;
7473 for (; declaration != NULL; declaration = declaration->next) {
7474 if (declaration->namespc != NAMESPACE_NORMAL)
7477 const type_t *decl_type = skip_typeref(declaration->type);
7478 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7485 static bool is_lvalue(const expression_t *expression)
7487 switch (expression->kind) {
7488 case EXPR_REFERENCE:
7489 case EXPR_ARRAY_ACCESS:
7491 case EXPR_UNARY_DEREFERENCE:
7499 static bool is_valid_assignment_lhs(expression_t const* const left)
7501 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7502 type_t *const type_left = skip_typeref(orig_type_left);
7504 if (!is_lvalue(left)) {
7505 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7510 if (is_type_array(type_left)) {
7511 errorf(HERE, "cannot assign to arrays ('%E')", left);
7514 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7515 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7519 if (is_type_incomplete(type_left)) {
7520 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7521 left, orig_type_left);
7524 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7525 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7526 left, orig_type_left);
7533 static void semantic_arithmetic_assign(binary_expression_t *expression)
7535 expression_t *left = expression->left;
7536 expression_t *right = expression->right;
7537 type_t *orig_type_left = left->base.type;
7538 type_t *orig_type_right = right->base.type;
7540 if (!is_valid_assignment_lhs(left))
7543 type_t *type_left = skip_typeref(orig_type_left);
7544 type_t *type_right = skip_typeref(orig_type_right);
7546 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7547 /* TODO: improve error message */
7548 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7549 errorf(&expression->base.source_position,
7550 "operation needs arithmetic types");
7555 /* combined instructions are tricky. We can't create an implicit cast on
7556 * the left side, because we need the uncasted form for the store.
7557 * The ast2firm pass has to know that left_type must be right_type
7558 * for the arithmetic operation and create a cast by itself */
7559 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7560 expression->right = create_implicit_cast(right, arithmetic_type);
7561 expression->base.type = type_left;
7564 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7566 expression_t *const left = expression->left;
7567 expression_t *const right = expression->right;
7568 type_t *const orig_type_left = left->base.type;
7569 type_t *const orig_type_right = right->base.type;
7570 type_t *const type_left = skip_typeref(orig_type_left);
7571 type_t *const type_right = skip_typeref(orig_type_right);
7573 if (!is_valid_assignment_lhs(left))
7576 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7577 /* combined instructions are tricky. We can't create an implicit cast on
7578 * the left side, because we need the uncasted form for the store.
7579 * The ast2firm pass has to know that left_type must be right_type
7580 * for the arithmetic operation and create a cast by itself */
7581 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7582 expression->right = create_implicit_cast(right, arithmetic_type);
7583 expression->base.type = type_left;
7584 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7585 check_pointer_arithmetic(&expression->base.source_position,
7586 type_left, orig_type_left);
7587 expression->base.type = type_left;
7588 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7589 errorf(&expression->base.source_position,
7590 "incompatible types '%T' and '%T' in assignment",
7591 orig_type_left, orig_type_right);
7596 * Check the semantic restrictions of a logical expression.
7598 static void semantic_logical_op(binary_expression_t *expression)
7600 expression_t *const left = expression->left;
7601 expression_t *const right = expression->right;
7602 type_t *const orig_type_left = left->base.type;
7603 type_t *const orig_type_right = right->base.type;
7604 type_t *const type_left = skip_typeref(orig_type_left);
7605 type_t *const type_right = skip_typeref(orig_type_right);
7607 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
7608 /* TODO: improve error message */
7609 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7610 errorf(&expression->base.source_position,
7611 "operation needs scalar types");
7616 expression->base.type = type_int;
7620 * Check the semantic restrictions of a binary assign expression.
7622 static void semantic_binexpr_assign(binary_expression_t *expression)
7624 expression_t *left = expression->left;
7625 type_t *orig_type_left = left->base.type;
7627 type_t *type_left = revert_automatic_type_conversion(left);
7628 type_left = skip_typeref(orig_type_left);
7630 if (!is_valid_assignment_lhs(left))
7633 assign_error_t error = semantic_assign(orig_type_left, expression->right);
7634 report_assign_error(error, orig_type_left, expression->right,
7635 "assignment", &left->base.source_position);
7636 expression->right = create_implicit_cast(expression->right, orig_type_left);
7637 expression->base.type = orig_type_left;
7641 * Determine if the outermost operation (or parts thereof) of the given
7642 * expression has no effect in order to generate a warning about this fact.
7643 * Therefore in some cases this only examines some of the operands of the
7644 * expression (see comments in the function and examples below).
7646 * f() + 23; // warning, because + has no effect
7647 * x || f(); // no warning, because x controls execution of f()
7648 * x ? y : f(); // warning, because y has no effect
7649 * (void)x; // no warning to be able to suppress the warning
7650 * This function can NOT be used for an "expression has definitely no effect"-
7652 static bool expression_has_effect(const expression_t *const expr)
7654 switch (expr->kind) {
7655 case EXPR_UNKNOWN: break;
7656 case EXPR_INVALID: return true; /* do NOT warn */
7657 case EXPR_REFERENCE: return false;
7658 /* suppress the warning for microsoft __noop operations */
7659 case EXPR_CONST: return expr->conste.is_ms_noop;
7660 case EXPR_CHARACTER_CONSTANT: return false;
7661 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
7662 case EXPR_STRING_LITERAL: return false;
7663 case EXPR_WIDE_STRING_LITERAL: return false;
7666 const call_expression_t *const call = &expr->call;
7667 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7670 switch (call->function->builtin_symbol.symbol->ID) {
7671 case T___builtin_va_end: return true;
7672 default: return false;
7676 /* Generate the warning if either the left or right hand side of a
7677 * conditional expression has no effect */
7678 case EXPR_CONDITIONAL: {
7679 const conditional_expression_t *const cond = &expr->conditional;
7681 expression_has_effect(cond->true_expression) &&
7682 expression_has_effect(cond->false_expression);
7685 case EXPR_SELECT: return false;
7686 case EXPR_ARRAY_ACCESS: return false;
7687 case EXPR_SIZEOF: return false;
7688 case EXPR_CLASSIFY_TYPE: return false;
7689 case EXPR_ALIGNOF: return false;
7691 case EXPR_FUNCNAME: return false;
7692 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
7693 case EXPR_BUILTIN_CONSTANT_P: return false;
7694 case EXPR_BUILTIN_PREFETCH: return true;
7695 case EXPR_OFFSETOF: return false;
7696 case EXPR_VA_START: return true;
7697 case EXPR_VA_ARG: return true;
7698 case EXPR_STATEMENT: return true; // TODO
7699 case EXPR_COMPOUND_LITERAL: return false;
7701 case EXPR_UNARY_NEGATE: return false;
7702 case EXPR_UNARY_PLUS: return false;
7703 case EXPR_UNARY_BITWISE_NEGATE: return false;
7704 case EXPR_UNARY_NOT: return false;
7705 case EXPR_UNARY_DEREFERENCE: return false;
7706 case EXPR_UNARY_TAKE_ADDRESS: return false;
7707 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7708 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7709 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7710 case EXPR_UNARY_PREFIX_DECREMENT: return true;
7712 /* Treat void casts as if they have an effect in order to being able to
7713 * suppress the warning */
7714 case EXPR_UNARY_CAST: {
7715 type_t *const type = skip_typeref(expr->base.type);
7716 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7719 case EXPR_UNARY_CAST_IMPLICIT: return true;
7720 case EXPR_UNARY_ASSUME: return true;
7722 case EXPR_BINARY_ADD: return false;
7723 case EXPR_BINARY_SUB: return false;
7724 case EXPR_BINARY_MUL: return false;
7725 case EXPR_BINARY_DIV: return false;
7726 case EXPR_BINARY_MOD: return false;
7727 case EXPR_BINARY_EQUAL: return false;
7728 case EXPR_BINARY_NOTEQUAL: return false;
7729 case EXPR_BINARY_LESS: return false;
7730 case EXPR_BINARY_LESSEQUAL: return false;
7731 case EXPR_BINARY_GREATER: return false;
7732 case EXPR_BINARY_GREATEREQUAL: return false;
7733 case EXPR_BINARY_BITWISE_AND: return false;
7734 case EXPR_BINARY_BITWISE_OR: return false;
7735 case EXPR_BINARY_BITWISE_XOR: return false;
7736 case EXPR_BINARY_SHIFTLEFT: return false;
7737 case EXPR_BINARY_SHIFTRIGHT: return false;
7738 case EXPR_BINARY_ASSIGN: return true;
7739 case EXPR_BINARY_MUL_ASSIGN: return true;
7740 case EXPR_BINARY_DIV_ASSIGN: return true;
7741 case EXPR_BINARY_MOD_ASSIGN: return true;
7742 case EXPR_BINARY_ADD_ASSIGN: return true;
7743 case EXPR_BINARY_SUB_ASSIGN: return true;
7744 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7745 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7746 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7747 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7748 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7750 /* Only examine the right hand side of && and ||, because the left hand
7751 * side already has the effect of controlling the execution of the right
7753 case EXPR_BINARY_LOGICAL_AND:
7754 case EXPR_BINARY_LOGICAL_OR:
7755 /* Only examine the right hand side of a comma expression, because the left
7756 * hand side has a separate warning */
7757 case EXPR_BINARY_COMMA:
7758 return expression_has_effect(expr->binary.right);
7760 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7761 case EXPR_BINARY_ISGREATER: return false;
7762 case EXPR_BINARY_ISGREATEREQUAL: return false;
7763 case EXPR_BINARY_ISLESS: return false;
7764 case EXPR_BINARY_ISLESSEQUAL: return false;
7765 case EXPR_BINARY_ISLESSGREATER: return false;
7766 case EXPR_BINARY_ISUNORDERED: return false;
7769 internal_errorf(HERE, "unexpected expression");
7772 static void semantic_comma(binary_expression_t *expression)
7774 if (warning.unused_value) {
7775 const expression_t *const left = expression->left;
7776 if (!expression_has_effect(left)) {
7777 warningf(&left->base.source_position,
7778 "left-hand operand of comma expression has no effect");
7781 expression->base.type = expression->right->base.type;
7784 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7785 static expression_t *parse_##binexpression_type(unsigned precedence, \
7786 expression_t *left) \
7788 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7789 binexpr->base.source_position = *HERE; \
7790 binexpr->binary.left = left; \
7793 expression_t *right = parse_sub_expression(precedence + lr); \
7795 binexpr->binary.right = right; \
7796 sfunc(&binexpr->binary); \
7801 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7802 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7803 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7804 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7805 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7806 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7807 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7808 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7809 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7811 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7812 semantic_comparison, 1)
7813 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7814 semantic_comparison, 1)
7815 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7816 semantic_comparison, 1)
7817 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7818 semantic_comparison, 1)
7820 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7821 semantic_binexpr_arithmetic, 1)
7822 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7823 semantic_binexpr_arithmetic, 1)
7824 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7825 semantic_binexpr_arithmetic, 1)
7826 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7827 semantic_logical_op, 1)
7828 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7829 semantic_logical_op, 1)
7830 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7831 semantic_shift_op, 1)
7832 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7833 semantic_shift_op, 1)
7834 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7835 semantic_arithmetic_addsubb_assign, 0)
7836 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7837 semantic_arithmetic_addsubb_assign, 0)
7838 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7839 semantic_arithmetic_assign, 0)
7840 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7841 semantic_arithmetic_assign, 0)
7842 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7843 semantic_arithmetic_assign, 0)
7844 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7845 semantic_arithmetic_assign, 0)
7846 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7847 semantic_arithmetic_assign, 0)
7848 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7849 semantic_arithmetic_assign, 0)
7850 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7851 semantic_arithmetic_assign, 0)
7852 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7853 semantic_arithmetic_assign, 0)
7855 static expression_t *parse_sub_expression(unsigned precedence)
7857 if (token.type < 0) {
7858 return expected_expression_error();
7861 expression_parser_function_t *parser
7862 = &expression_parsers[token.type];
7863 source_position_t source_position = token.source_position;
7866 if (parser->parser != NULL) {
7867 left = parser->parser(parser->precedence);
7869 left = parse_primary_expression();
7871 assert(left != NULL);
7872 left->base.source_position = source_position;
7875 if (token.type < 0) {
7876 return expected_expression_error();
7879 parser = &expression_parsers[token.type];
7880 if (parser->infix_parser == NULL)
7882 if (parser->infix_precedence < precedence)
7885 left = parser->infix_parser(parser->infix_precedence, left);
7887 assert(left != NULL);
7888 assert(left->kind != EXPR_UNKNOWN);
7889 left->base.source_position = source_position;
7896 * Parse an expression.
7898 static expression_t *parse_expression(void)
7900 return parse_sub_expression(1);
7904 * Register a parser for a prefix-like operator with given precedence.
7906 * @param parser the parser function
7907 * @param token_type the token type of the prefix token
7908 * @param precedence the precedence of the operator
7910 static void register_expression_parser(parse_expression_function parser,
7911 int token_type, unsigned precedence)
7913 expression_parser_function_t *entry = &expression_parsers[token_type];
7915 if (entry->parser != NULL) {
7916 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7917 panic("trying to register multiple expression parsers for a token");
7919 entry->parser = parser;
7920 entry->precedence = precedence;
7924 * Register a parser for an infix operator with given precedence.
7926 * @param parser the parser function
7927 * @param token_type the token type of the infix operator
7928 * @param precedence the precedence of the operator
7930 static void register_infix_parser(parse_expression_infix_function parser,
7931 int token_type, unsigned precedence)
7933 expression_parser_function_t *entry = &expression_parsers[token_type];
7935 if (entry->infix_parser != NULL) {
7936 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7937 panic("trying to register multiple infix expression parsers for a "
7940 entry->infix_parser = parser;
7941 entry->infix_precedence = precedence;
7945 * Initialize the expression parsers.
7947 static void init_expression_parsers(void)
7949 memset(&expression_parsers, 0, sizeof(expression_parsers));
7951 register_infix_parser(parse_array_expression, '[', 30);
7952 register_infix_parser(parse_call_expression, '(', 30);
7953 register_infix_parser(parse_select_expression, '.', 30);
7954 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7955 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7957 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7960 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7961 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7962 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7963 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7964 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7965 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7966 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7967 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7968 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7969 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7970 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7971 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7972 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7973 T_EXCLAMATIONMARKEQUAL, 13);
7974 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7975 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7976 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7977 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7978 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7979 register_infix_parser(parse_conditional_expression, '?', 7);
7980 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7981 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7982 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7983 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7984 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7985 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7986 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7987 T_LESSLESSEQUAL, 2);
7988 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7989 T_GREATERGREATEREQUAL, 2);
7990 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7992 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7994 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7997 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7999 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8000 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8001 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8002 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8003 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8004 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8005 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8007 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8009 register_expression_parser(parse_sizeof, T_sizeof, 25);
8010 register_expression_parser(parse_alignof, T___alignof__, 25);
8011 register_expression_parser(parse_extension, T___extension__, 25);
8012 register_expression_parser(parse_builtin_classify_type,
8013 T___builtin_classify_type, 25);
8017 * Parse a asm statement arguments specification.
8019 static asm_argument_t *parse_asm_arguments(bool is_out)
8021 asm_argument_t *result = NULL;
8022 asm_argument_t *last = NULL;
8024 while (token.type == T_STRING_LITERAL || token.type == '[') {
8025 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8026 memset(argument, 0, sizeof(argument[0]));
8028 if (token.type == '[') {
8030 if (token.type != T_IDENTIFIER) {
8031 parse_error_expected("while parsing asm argument",
8032 T_IDENTIFIER, NULL);
8035 argument->symbol = token.v.symbol;
8040 argument->constraints = parse_string_literals();
8042 add_anchor_token(')');
8043 expression_t *expression = parse_expression();
8044 rem_anchor_token(')');
8046 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8047 * change size or type representation (e.g. int -> long is ok, but
8048 * int -> float is not) */
8049 if (expression->kind == EXPR_UNARY_CAST) {
8050 type_t *const type = expression->base.type;
8051 type_kind_t const kind = type->kind;
8052 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8055 if (kind == TYPE_ATOMIC) {
8056 atomic_type_kind_t const akind = type->atomic.akind;
8057 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8058 size = get_atomic_type_size(akind);
8060 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8061 size = get_atomic_type_size(get_intptr_kind());
8065 expression_t *const value = expression->unary.value;
8066 type_t *const value_type = value->base.type;
8067 type_kind_t const value_kind = value_type->kind;
8069 unsigned value_flags;
8070 unsigned value_size;
8071 if (value_kind == TYPE_ATOMIC) {
8072 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8073 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8074 value_size = get_atomic_type_size(value_akind);
8075 } else if (value_kind == TYPE_POINTER) {
8076 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8077 value_size = get_atomic_type_size(get_intptr_kind());
8082 if (value_flags != flags || value_size != size)
8086 } while (expression->kind == EXPR_UNARY_CAST);
8090 if (!is_lvalue(expression)) {
8091 errorf(&expression->base.source_position,
8092 "asm output argument is not an lvalue");
8095 argument->expression = expression;
8098 set_address_taken(expression, true);
8101 last->next = argument;
8107 if (token.type != ',')
8118 * Parse a asm statement clobber specification.
8120 static asm_clobber_t *parse_asm_clobbers(void)
8122 asm_clobber_t *result = NULL;
8123 asm_clobber_t *last = NULL;
8125 while(token.type == T_STRING_LITERAL) {
8126 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8127 clobber->clobber = parse_string_literals();
8130 last->next = clobber;
8136 if (token.type != ',')
8145 * Parse an asm statement.
8147 static statement_t *parse_asm_statement(void)
8151 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8152 statement->base.source_position = token.source_position;
8154 asm_statement_t *asm_statement = &statement->asms;
8156 if (token.type == T_volatile) {
8158 asm_statement->is_volatile = true;
8162 add_anchor_token(')');
8163 add_anchor_token(':');
8164 asm_statement->asm_text = parse_string_literals();
8166 if (token.type != ':') {
8167 rem_anchor_token(':');
8172 asm_statement->outputs = parse_asm_arguments(true);
8173 if (token.type != ':') {
8174 rem_anchor_token(':');
8179 asm_statement->inputs = parse_asm_arguments(false);
8180 if (token.type != ':') {
8181 rem_anchor_token(':');
8184 rem_anchor_token(':');
8187 asm_statement->clobbers = parse_asm_clobbers();
8190 rem_anchor_token(')');
8194 if (asm_statement->outputs == NULL) {
8195 /* GCC: An 'asm' instruction without any output operands will be treated
8196 * identically to a volatile 'asm' instruction. */
8197 asm_statement->is_volatile = true;
8202 return create_invalid_statement();
8206 * Parse a case statement.
8208 static statement_t *parse_case_statement(void)
8212 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8213 source_position_t *const pos = &statement->base.source_position;
8215 *pos = token.source_position;
8216 statement->case_label.expression = parse_expression();
8217 if (! is_constant_expression(statement->case_label.expression)) {
8218 errorf(pos, "case label does not reduce to an integer constant");
8219 statement->case_label.is_bad = true;
8221 long const val = fold_constant(statement->case_label.expression);
8222 statement->case_label.first_case = val;
8223 statement->case_label.last_case = val;
8226 if (c_mode & _GNUC) {
8227 if (token.type == T_DOTDOTDOT) {
8229 statement->case_label.end_range = parse_expression();
8230 if (! is_constant_expression(statement->case_label.end_range)) {
8231 errorf(pos, "case range does not reduce to an integer constant");
8232 statement->case_label.is_bad = true;
8234 long const val = fold_constant(statement->case_label.end_range);
8235 statement->case_label.last_case = val;
8237 if (val < statement->case_label.first_case) {
8238 statement->case_label.is_empty = true;
8239 warningf(pos, "empty range specified");
8245 PUSH_PARENT(statement);
8249 if (current_switch != NULL) {
8250 if (! statement->case_label.is_bad) {
8251 /* Check for duplicate case values */
8252 case_label_statement_t *c = &statement->case_label;
8253 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8254 if (l->is_bad || l->is_empty)
8257 if (c->last_case < l->first_case || c->first_case > l->last_case)
8260 errorf(pos, "duplicate case value (previously used %P)",
8261 &l->base.source_position);
8265 /* link all cases into the switch statement */
8266 if (current_switch->last_case == NULL) {
8267 current_switch->first_case = &statement->case_label;
8269 current_switch->last_case->next = &statement->case_label;
8271 current_switch->last_case = &statement->case_label;
8273 errorf(pos, "case label not within a switch statement");
8276 statement_t *const inner_stmt = parse_statement();
8277 statement->case_label.statement = inner_stmt;
8278 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8279 errorf(&inner_stmt->base.source_position, "declaration after case label");
8286 return create_invalid_statement();
8290 * Parse a default statement.
8292 static statement_t *parse_default_statement(void)
8296 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8297 statement->base.source_position = token.source_position;
8299 PUSH_PARENT(statement);
8302 if (current_switch != NULL) {
8303 const case_label_statement_t *def_label = current_switch->default_label;
8304 if (def_label != NULL) {
8305 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8306 &def_label->base.source_position);
8308 current_switch->default_label = &statement->case_label;
8310 /* link all cases into the switch statement */
8311 if (current_switch->last_case == NULL) {
8312 current_switch->first_case = &statement->case_label;
8314 current_switch->last_case->next = &statement->case_label;
8316 current_switch->last_case = &statement->case_label;
8319 errorf(&statement->base.source_position,
8320 "'default' label not within a switch statement");
8323 statement_t *const inner_stmt = parse_statement();
8324 statement->case_label.statement = inner_stmt;
8325 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8326 errorf(&inner_stmt->base.source_position, "declaration after default label");
8333 return create_invalid_statement();
8337 * Return the declaration for a given label symbol or create a new one.
8339 * @param symbol the symbol of the label
8341 static declaration_t *get_label(symbol_t *symbol)
8343 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
8344 assert(current_function != NULL);
8345 /* if we found a label in the same function, then we already created the
8347 if (candidate != NULL
8348 && candidate->parent_scope == ¤t_function->scope) {
8352 /* otherwise we need to create a new one */
8353 declaration_t *const declaration = allocate_declaration_zero();
8354 declaration->namespc = NAMESPACE_LABEL;
8355 declaration->symbol = symbol;
8357 label_push(declaration);
8363 * Parse a label statement.
8365 static statement_t *parse_label_statement(void)
8367 assert(token.type == T_IDENTIFIER);
8368 symbol_t *symbol = token.v.symbol;
8371 declaration_t *label = get_label(symbol);
8373 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8374 statement->base.source_position = token.source_position;
8375 statement->label.label = label;
8377 PUSH_PARENT(statement);
8379 /* if source position is already set then the label is defined twice,
8380 * otherwise it was just mentioned in a goto so far */
8381 if (label->source_position.input_name != NULL) {
8382 errorf(HERE, "duplicate label '%Y' (declared %P)",
8383 symbol, &label->source_position);
8385 label->source_position = token.source_position;
8386 label->init.statement = statement;
8391 if (token.type == '}') {
8392 /* TODO only warn? */
8394 warningf(HERE, "label at end of compound statement");
8395 statement->label.statement = create_empty_statement();
8397 errorf(HERE, "label at end of compound statement");
8398 statement->label.statement = create_invalid_statement();
8400 } else if (token.type == ';') {
8401 /* Eat an empty statement here, to avoid the warning about an empty
8402 * statement after a label. label:; is commonly used to have a label
8403 * before a closing brace. */
8404 statement->label.statement = create_empty_statement();
8407 statement_t *const inner_stmt = parse_statement();
8408 statement->label.statement = inner_stmt;
8409 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8410 errorf(&inner_stmt->base.source_position, "declaration after label");
8414 /* remember the labels in a list for later checking */
8415 if (label_last == NULL) {
8416 label_first = &statement->label;
8418 label_last->next = &statement->label;
8420 label_last = &statement->label;
8427 * Parse an if statement.
8429 static statement_t *parse_if(void)
8433 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8434 statement->base.source_position = token.source_position;
8436 PUSH_PARENT(statement);
8439 add_anchor_token(')');
8440 statement->ifs.condition = parse_expression();
8441 rem_anchor_token(')');
8444 add_anchor_token(T_else);
8445 statement->ifs.true_statement = parse_statement();
8446 rem_anchor_token(T_else);
8448 if (token.type == T_else) {
8450 statement->ifs.false_statement = parse_statement();
8457 return create_invalid_statement();
8461 * Check that all enums are handled in a switch.
8463 * @param statement the switch statement to check
8465 static void check_enum_cases(const switch_statement_t *statement) {
8466 const type_t *type = skip_typeref(statement->expression->base.type);
8467 if (! is_type_enum(type))
8469 const enum_type_t *enumt = &type->enumt;
8471 /* if we have a default, no warnings */
8472 if (statement->default_label != NULL)
8475 /* FIXME: calculation of value should be done while parsing */
8476 const declaration_t *declaration;
8477 long last_value = -1;
8478 for (declaration = enumt->declaration->next;
8479 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8480 declaration = declaration->next) {
8481 const expression_t *expression = declaration->init.enum_value;
8482 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8484 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8485 if (l->expression == NULL)
8487 if (l->first_case <= value && value <= l->last_case) {
8493 warningf(&statement->base.source_position,
8494 "enumeration value '%Y' not handled in switch", declaration->symbol);
8501 * Parse a switch statement.
8503 static statement_t *parse_switch(void)
8507 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8508 statement->base.source_position = token.source_position;
8510 PUSH_PARENT(statement);
8513 add_anchor_token(')');
8514 expression_t *const expr = parse_expression();
8515 type_t * type = skip_typeref(expr->base.type);
8516 if (is_type_integer(type)) {
8517 type = promote_integer(type);
8518 } else if (is_type_valid(type)) {
8519 errorf(&expr->base.source_position,
8520 "switch quantity is not an integer, but '%T'", type);
8521 type = type_error_type;
8523 statement->switchs.expression = create_implicit_cast(expr, type);
8525 rem_anchor_token(')');
8527 switch_statement_t *rem = current_switch;
8528 current_switch = &statement->switchs;
8529 statement->switchs.body = parse_statement();
8530 current_switch = rem;
8532 if (warning.switch_default &&
8533 statement->switchs.default_label == NULL) {
8534 warningf(&statement->base.source_position, "switch has no default case");
8536 if (warning.switch_enum)
8537 check_enum_cases(&statement->switchs);
8543 return create_invalid_statement();
8546 static statement_t *parse_loop_body(statement_t *const loop)
8548 statement_t *const rem = current_loop;
8549 current_loop = loop;
8551 statement_t *const body = parse_statement();
8558 * Parse a while statement.
8560 static statement_t *parse_while(void)
8564 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8565 statement->base.source_position = token.source_position;
8567 PUSH_PARENT(statement);
8570 add_anchor_token(')');
8571 statement->whiles.condition = parse_expression();
8572 rem_anchor_token(')');
8575 statement->whiles.body = parse_loop_body(statement);
8581 return create_invalid_statement();
8585 * Parse a do statement.
8587 static statement_t *parse_do(void)
8591 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
8592 statement->base.source_position = token.source_position;
8594 PUSH_PARENT(statement)
8596 add_anchor_token(T_while);
8597 statement->do_while.body = parse_loop_body(statement);
8598 rem_anchor_token(T_while);
8602 add_anchor_token(')');
8603 statement->do_while.condition = parse_expression();
8604 rem_anchor_token(')');
8612 return create_invalid_statement();
8616 * Parse a for statement.
8618 static statement_t *parse_for(void)
8622 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
8623 statement->base.source_position = token.source_position;
8625 PUSH_PARENT(statement);
8627 int top = environment_top();
8628 scope_t *last_scope = scope;
8629 set_scope(&statement->fors.scope);
8632 add_anchor_token(')');
8634 if (token.type != ';') {
8635 if (is_declaration_specifier(&token, false)) {
8636 parse_declaration(record_declaration);
8638 add_anchor_token(';');
8639 expression_t *const init = parse_expression();
8640 statement->fors.initialisation = init;
8641 if (warning.unused_value && !expression_has_effect(init)) {
8642 warningf(&init->base.source_position,
8643 "initialisation of 'for'-statement has no effect");
8645 rem_anchor_token(';');
8652 if (token.type != ';') {
8653 add_anchor_token(';');
8654 statement->fors.condition = parse_expression();
8655 rem_anchor_token(';');
8658 if (token.type != ')') {
8659 expression_t *const step = parse_expression();
8660 statement->fors.step = step;
8661 if (warning.unused_value && !expression_has_effect(step)) {
8662 warningf(&step->base.source_position,
8663 "step of 'for'-statement has no effect");
8666 rem_anchor_token(')');
8668 statement->fors.body = parse_loop_body(statement);
8670 assert(scope == &statement->fors.scope);
8671 set_scope(last_scope);
8672 environment_pop_to(top);
8679 rem_anchor_token(')');
8680 assert(scope == &statement->fors.scope);
8681 set_scope(last_scope);
8682 environment_pop_to(top);
8684 return create_invalid_statement();
8688 * Parse a goto statement.
8690 static statement_t *parse_goto(void)
8694 if (token.type != T_IDENTIFIER) {
8695 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
8699 symbol_t *symbol = token.v.symbol;
8702 declaration_t *label = get_label(symbol);
8704 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
8705 statement->base.source_position = token.source_position;
8707 statement->gotos.label = label;
8709 /* remember the goto's in a list for later checking */
8710 if (goto_last == NULL) {
8711 goto_first = &statement->gotos;
8713 goto_last->next = &statement->gotos;
8715 goto_last = &statement->gotos;
8721 return create_invalid_statement();
8725 * Parse a continue statement.
8727 static statement_t *parse_continue(void)
8729 statement_t *statement;
8730 if (current_loop == NULL) {
8731 errorf(HERE, "continue statement not within loop");
8732 statement = create_invalid_statement();
8734 statement = allocate_statement_zero(STATEMENT_CONTINUE);
8736 statement->base.source_position = token.source_position;
8744 return create_invalid_statement();
8748 * Parse a break statement.
8750 static statement_t *parse_break(void)
8752 statement_t *statement;
8753 if (current_switch == NULL && current_loop == NULL) {
8754 errorf(HERE, "break statement not within loop or switch");
8755 statement = create_invalid_statement();
8757 statement = allocate_statement_zero(STATEMENT_BREAK);
8759 statement->base.source_position = token.source_position;
8767 return create_invalid_statement();
8771 * Parse a __leave statement.
8773 static statement_t *parse_leave(void)
8775 statement_t *statement;
8776 if (current_try == NULL) {
8777 errorf(HERE, "__leave statement not within __try");
8778 statement = create_invalid_statement();
8780 statement = allocate_statement_zero(STATEMENT_LEAVE);
8782 statement->base.source_position = token.source_position;
8790 return create_invalid_statement();
8794 * Check if a given declaration represents a local variable.
8796 static bool is_local_var_declaration(const declaration_t *declaration)
8798 switch ((storage_class_tag_t) declaration->storage_class) {
8799 case STORAGE_CLASS_AUTO:
8800 case STORAGE_CLASS_REGISTER: {
8801 const type_t *type = skip_typeref(declaration->type);
8802 if (is_type_function(type)) {
8814 * Check if a given declaration represents a variable.
8816 static bool is_var_declaration(const declaration_t *declaration)
8818 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
8821 const type_t *type = skip_typeref(declaration->type);
8822 return !is_type_function(type);
8826 * Check if a given expression represents a local variable.
8828 static bool is_local_variable(const expression_t *expression)
8830 if (expression->base.kind != EXPR_REFERENCE) {
8833 const declaration_t *declaration = expression->reference.declaration;
8834 return is_local_var_declaration(declaration);
8838 * Check if a given expression represents a local variable and
8839 * return its declaration then, else return NULL.
8841 declaration_t *expr_is_variable(const expression_t *expression)
8843 if (expression->base.kind != EXPR_REFERENCE) {
8846 declaration_t *declaration = expression->reference.declaration;
8847 if (is_var_declaration(declaration))
8853 * Parse a return statement.
8855 static statement_t *parse_return(void)
8857 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
8858 statement->base.source_position = token.source_position;
8862 expression_t *return_value = NULL;
8863 if (token.type != ';') {
8864 return_value = parse_expression();
8868 const type_t *const func_type = current_function->type;
8869 assert(is_type_function(func_type));
8870 type_t *const return_type = skip_typeref(func_type->function.return_type);
8872 if (return_value != NULL) {
8873 type_t *return_value_type = skip_typeref(return_value->base.type);
8875 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8876 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8877 warningf(&statement->base.source_position,
8878 "'return' with a value, in function returning void");
8879 return_value = NULL;
8881 assign_error_t error = semantic_assign(return_type, return_value);
8882 report_assign_error(error, return_type, return_value, "'return'",
8883 &statement->base.source_position);
8884 return_value = create_implicit_cast(return_value, return_type);
8886 /* check for returning address of a local var */
8887 if (return_value != NULL &&
8888 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8889 const expression_t *expression = return_value->unary.value;
8890 if (is_local_variable(expression)) {
8891 warningf(&statement->base.source_position,
8892 "function returns address of local variable");
8896 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8897 warningf(&statement->base.source_position,
8898 "'return' without value, in function returning non-void");
8901 statement->returns.value = return_value;
8905 return create_invalid_statement();
8909 * Parse a declaration statement.
8911 static statement_t *parse_declaration_statement(void)
8913 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8915 statement->base.source_position = token.source_position;
8917 declaration_t *before = last_declaration;
8918 parse_declaration(record_declaration);
8920 if (before == NULL) {
8921 statement->declaration.declarations_begin = scope->declarations;
8923 statement->declaration.declarations_begin = before->next;
8925 statement->declaration.declarations_end = last_declaration;
8931 * Parse an expression statement, ie. expr ';'.
8933 static statement_t *parse_expression_statement(void)
8935 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8937 statement->base.source_position = token.source_position;
8938 expression_t *const expr = parse_expression();
8939 statement->expression.expression = expr;
8945 return create_invalid_statement();
8949 * Parse a microsoft __try { } __finally { } or
8950 * __try{ } __except() { }
8952 static statement_t *parse_ms_try_statment(void)
8954 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8956 statement->base.source_position = token.source_position;
8959 ms_try_statement_t *rem = current_try;
8960 current_try = &statement->ms_try;
8961 statement->ms_try.try_statement = parse_compound_statement(false);
8964 if (token.type == T___except) {
8967 add_anchor_token(')');
8968 expression_t *const expr = parse_expression();
8969 type_t * type = skip_typeref(expr->base.type);
8970 if (is_type_integer(type)) {
8971 type = promote_integer(type);
8972 } else if (is_type_valid(type)) {
8973 errorf(&expr->base.source_position,
8974 "__expect expression is not an integer, but '%T'", type);
8975 type = type_error_type;
8977 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8978 rem_anchor_token(')');
8980 statement->ms_try.final_statement = parse_compound_statement(false);
8981 } else if (token.type == T__finally) {
8983 statement->ms_try.final_statement = parse_compound_statement(false);
8985 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8986 return create_invalid_statement();
8990 return create_invalid_statement();
8993 static statement_t *parse_empty_statement(void)
8995 if (warning.empty_statement) {
8996 warningf(HERE, "statement is empty");
8998 statement_t *const statement = create_empty_statement();
9004 * Parse a statement.
9005 * There's also parse_statement() which additionally checks for
9006 * "statement has no effect" warnings
9008 static statement_t *intern_parse_statement(void)
9010 statement_t *statement = NULL;
9012 /* declaration or statement */
9013 add_anchor_token(';');
9014 switch (token.type) {
9016 if (look_ahead(1)->type == ':') {
9017 statement = parse_label_statement();
9018 } else if (is_typedef_symbol(token.v.symbol)) {
9019 statement = parse_declaration_statement();
9021 statement = parse_expression_statement();
9025 case T___extension__:
9026 /* This can be a prefix to a declaration or an expression statement.
9027 * We simply eat it now and parse the rest with tail recursion. */
9030 } while (token.type == T___extension__);
9031 statement = parse_statement();
9035 statement = parse_declaration_statement();
9038 case ';': statement = parse_empty_statement(); break;
9039 case '{': statement = parse_compound_statement(false); break;
9040 case T___leave: statement = parse_leave(); break;
9041 case T___try: statement = parse_ms_try_statment(); break;
9042 case T_asm: statement = parse_asm_statement(); break;
9043 case T_break: statement = parse_break(); break;
9044 case T_case: statement = parse_case_statement(); break;
9045 case T_continue: statement = parse_continue(); break;
9046 case T_default: statement = parse_default_statement(); break;
9047 case T_do: statement = parse_do(); break;
9048 case T_for: statement = parse_for(); break;
9049 case T_goto: statement = parse_goto(); break;
9050 case T_if: statement = parse_if (); break;
9051 case T_return: statement = parse_return(); break;
9052 case T_switch: statement = parse_switch(); break;
9053 case T_while: statement = parse_while(); break;
9054 default: statement = parse_expression_statement(); break;
9056 rem_anchor_token(';');
9058 assert(statement != NULL
9059 && statement->base.source_position.input_name != NULL);
9065 * parse a statement and emits "statement has no effect" warning if needed
9066 * (This is really a wrapper around intern_parse_statement with check for 1
9067 * single warning. It is needed, because for statement expressions we have
9068 * to avoid the warning on the last statement)
9070 static statement_t *parse_statement(void)
9072 statement_t *statement = intern_parse_statement();
9074 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9075 expression_t *expression = statement->expression.expression;
9076 if (!expression_has_effect(expression)) {
9077 warningf(&expression->base.source_position,
9078 "statement has no effect");
9086 * Parse a compound statement.
9088 static statement_t *parse_compound_statement(bool inside_expression_statement)
9090 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9091 statement->base.source_position = token.source_position;
9093 PUSH_PARENT(statement);
9096 add_anchor_token('}');
9098 int top = environment_top();
9099 scope_t *last_scope = scope;
9100 set_scope(&statement->compound.scope);
9102 statement_t **anchor = &statement->compound.statements;
9103 bool only_decls_so_far = true;
9104 while (token.type != '}' && token.type != T_EOF) {
9105 statement_t *sub_statement = intern_parse_statement();
9106 if (is_invalid_statement(sub_statement)) {
9107 /* an error occurred. if we are at an anchor, return */
9113 if (warning.declaration_after_statement) {
9114 if (sub_statement->kind != STATEMENT_DECLARATION) {
9115 only_decls_so_far = false;
9116 } else if (!only_decls_so_far) {
9117 warningf(&sub_statement->base.source_position,
9118 "ISO C90 forbids mixed declarations and code");
9122 *anchor = sub_statement;
9124 while (sub_statement->base.next != NULL)
9125 sub_statement = sub_statement->base.next;
9127 anchor = &sub_statement->base.next;
9130 if (token.type == '}') {
9133 errorf(&statement->base.source_position,
9134 "end of file while looking for closing '}'");
9137 /* look over all statements again to produce no effect warnings */
9138 if (warning.unused_value) {
9139 statement_t *sub_statement = statement->compound.statements;
9140 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9141 if (sub_statement->kind != STATEMENT_EXPRESSION)
9143 /* don't emit a warning for the last expression in an expression
9144 * statement as it has always an effect */
9145 if (inside_expression_statement && sub_statement->base.next == NULL)
9148 expression_t *expression = sub_statement->expression.expression;
9149 if (!expression_has_effect(expression)) {
9150 warningf(&expression->base.source_position,
9151 "statement has no effect");
9157 rem_anchor_token('}');
9158 assert(scope == &statement->compound.scope);
9159 set_scope(last_scope);
9160 environment_pop_to(top);
9167 * Initialize builtin types.
9169 static void initialize_builtin_types(void)
9171 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9172 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9173 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9174 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9175 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9176 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9177 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9178 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9180 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9181 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9182 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9183 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9185 /* const version of wchar_t */
9186 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9187 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9188 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9190 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9194 * Check for unused global static functions and variables
9196 static void check_unused_globals(void)
9198 if (!warning.unused_function && !warning.unused_variable)
9201 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9203 decl->modifiers & DM_UNUSED ||
9204 decl->modifiers & DM_USED ||
9205 decl->storage_class != STORAGE_CLASS_STATIC)
9208 type_t *const type = decl->type;
9210 if (is_type_function(skip_typeref(type))) {
9211 if (!warning.unused_function || decl->is_inline)
9214 s = (decl->init.statement != NULL ? "defined" : "declared");
9216 if (!warning.unused_variable)
9222 warningf(&decl->source_position, "'%#T' %s but not used",
9223 type, decl->symbol, s);
9227 static void parse_global_asm(void)
9232 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9233 statement->base.source_position = token.source_position;
9234 statement->asms.asm_text = parse_string_literals();
9235 statement->base.next = unit->global_asm;
9236 unit->global_asm = statement;
9245 * Parse a translation unit.
9247 static void parse_translation_unit(void)
9249 for (;;) switch (token.type) {
9252 case T___extension__:
9253 parse_external_declaration();
9264 /* TODO error in strict mode */
9265 warningf(HERE, "stray ';' outside of function");
9270 errorf(HERE, "stray %K outside of function", &token);
9271 if (token.type == '(' || token.type == '{' || token.type == '[')
9272 eat_until_matching_token(token.type);
9281 * @return the translation unit or NULL if errors occurred.
9283 void start_parsing(void)
9285 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9286 label_stack = NEW_ARR_F(stack_entry_t, 0);
9287 diagnostic_count = 0;
9291 type_set_output(stderr);
9292 ast_set_output(stderr);
9294 assert(unit == NULL);
9295 unit = allocate_ast_zero(sizeof(unit[0]));
9297 assert(global_scope == NULL);
9298 global_scope = &unit->scope;
9300 assert(scope == NULL);
9301 set_scope(&unit->scope);
9303 initialize_builtin_types();
9306 translation_unit_t *finish_parsing(void)
9308 assert(scope == &unit->scope);
9310 last_declaration = NULL;
9312 assert(global_scope == &unit->scope);
9313 check_unused_globals();
9314 global_scope = NULL;
9316 DEL_ARR_F(environment_stack);
9317 DEL_ARR_F(label_stack);
9319 translation_unit_t *result = unit;
9326 lookahead_bufpos = 0;
9327 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9330 parse_translation_unit();
9334 * Initialize the parser.
9336 void init_parser(void)
9339 /* add predefined symbols for extended-decl-modifier */
9340 sym_align = symbol_table_insert("align");
9341 sym_allocate = symbol_table_insert("allocate");
9342 sym_dllimport = symbol_table_insert("dllimport");
9343 sym_dllexport = symbol_table_insert("dllexport");
9344 sym_naked = symbol_table_insert("naked");
9345 sym_noinline = symbol_table_insert("noinline");
9346 sym_noreturn = symbol_table_insert("noreturn");
9347 sym_nothrow = symbol_table_insert("nothrow");
9348 sym_novtable = symbol_table_insert("novtable");
9349 sym_property = symbol_table_insert("property");
9350 sym_get = symbol_table_insert("get");
9351 sym_put = symbol_table_insert("put");
9352 sym_selectany = symbol_table_insert("selectany");
9353 sym_thread = symbol_table_insert("thread");
9354 sym_uuid = symbol_table_insert("uuid");
9355 sym_deprecated = symbol_table_insert("deprecated");
9356 sym_restrict = symbol_table_insert("restrict");
9357 sym_noalias = symbol_table_insert("noalias");
9359 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9361 init_expression_parsers();
9362 obstack_init(&temp_obst);
9364 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9365 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9369 * Terminate the parser.
9371 void exit_parser(void)
9373 obstack_free(&temp_obst, NULL);