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);
850 static int get_akind_rank(atomic_type_kind_t akind)
855 static int get_rank(const type_t *type)
857 assert(!is_typeref(type));
858 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
859 * and esp. footnote 108). However we can't fold constants (yet), so we
860 * can't decide whether unsigned int is possible, while int always works.
861 * (unsigned int would be preferable when possible... for stuff like
862 * struct { enum { ... } bla : 4; } ) */
863 if (type->kind == TYPE_ENUM)
864 return get_akind_rank(ATOMIC_TYPE_INT);
866 assert(type->kind == TYPE_ATOMIC);
867 return get_akind_rank(type->atomic.akind);
870 static type_t *promote_integer(type_t *type)
872 if (type->kind == TYPE_BITFIELD)
873 type = type->bitfield.base_type;
875 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
882 * Create a cast expression.
884 * @param expression the expression to cast
885 * @param dest_type the destination type
887 static expression_t *create_cast_expression(expression_t *expression,
890 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
892 cast->unary.value = expression;
893 cast->base.type = dest_type;
899 * Check if a given expression represents the 0 pointer constant.
901 static bool is_null_pointer_constant(const expression_t *expression)
903 /* skip void* cast */
904 if (expression->kind == EXPR_UNARY_CAST
905 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
906 expression = expression->unary.value;
909 /* TODO: not correct yet, should be any constant integer expression
910 * which evaluates to 0 */
911 if (expression->kind != EXPR_CONST)
914 type_t *const type = skip_typeref(expression->base.type);
915 if (!is_type_integer(type))
918 return expression->conste.v.int_value == 0;
922 * Create an implicit cast expression.
924 * @param expression the expression to cast
925 * @param dest_type the destination type
927 static expression_t *create_implicit_cast(expression_t *expression,
930 type_t *const source_type = expression->base.type;
932 if (source_type == dest_type)
935 return create_cast_expression(expression, dest_type);
938 typedef enum assign_error_t {
940 ASSIGN_ERROR_INCOMPATIBLE,
941 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
942 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
943 ASSIGN_WARNING_POINTER_FROM_INT,
944 ASSIGN_WARNING_INT_FROM_POINTER
947 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
948 const expression_t *const right,
950 const source_position_t *source_position)
952 type_t *const orig_type_right = right->base.type;
953 type_t *const type_left = skip_typeref(orig_type_left);
954 type_t *const type_right = skip_typeref(orig_type_right);
959 case ASSIGN_ERROR_INCOMPATIBLE:
960 errorf(source_position,
961 "destination type '%T' in %s is incompatible with type '%T'",
962 orig_type_left, context, orig_type_right);
965 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
966 type_t *points_to_left
967 = skip_typeref(type_left->pointer.points_to);
968 type_t *points_to_right
969 = skip_typeref(type_right->pointer.points_to);
971 /* the left type has all qualifiers from the right type */
972 unsigned missing_qualifiers
973 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
974 warningf(source_position,
975 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type",
976 orig_type_left, context, orig_type_right, missing_qualifiers);
980 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
981 warningf(source_position,
982 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
983 orig_type_left, context, right, orig_type_right);
986 case ASSIGN_WARNING_POINTER_FROM_INT:
987 warningf(source_position,
988 "%s makes integer '%T' from pointer '%T' without a cast",
989 context, orig_type_left, orig_type_right);
992 case ASSIGN_WARNING_INT_FROM_POINTER:
993 warningf(source_position,
994 "%s makes integer '%T' from pointer '%T' without a cast",
995 context, orig_type_left, orig_type_right);
999 panic("invalid error value");
1003 /** Implements the rules from § 6.5.16.1 */
1004 static assign_error_t semantic_assign(type_t *orig_type_left,
1005 const expression_t *const right)
1007 type_t *const orig_type_right = right->base.type;
1008 type_t *const type_left = skip_typeref(orig_type_left);
1009 type_t *const type_right = skip_typeref(orig_type_right);
1011 if (is_type_pointer(type_left)) {
1012 if (is_null_pointer_constant(right)) {
1013 return ASSIGN_SUCCESS;
1014 } else if (is_type_pointer(type_right)) {
1015 type_t *points_to_left
1016 = skip_typeref(type_left->pointer.points_to);
1017 type_t *points_to_right
1018 = skip_typeref(type_right->pointer.points_to);
1020 /* the left type has all qualifiers from the right type */
1021 unsigned missing_qualifiers
1022 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1023 if (missing_qualifiers != 0) {
1024 return ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1027 points_to_left = get_unqualified_type(points_to_left);
1028 points_to_right = get_unqualified_type(points_to_right);
1030 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1031 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1032 return ASSIGN_SUCCESS;
1035 if (!types_compatible(points_to_left, points_to_right)) {
1036 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1039 return ASSIGN_SUCCESS;
1040 } else if (is_type_integer(type_right)) {
1041 return ASSIGN_WARNING_POINTER_FROM_INT;
1043 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1044 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1045 && is_type_pointer(type_right))) {
1046 return ASSIGN_SUCCESS;
1047 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1048 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1049 type_t *const unqual_type_left = get_unqualified_type(type_left);
1050 type_t *const unqual_type_right = get_unqualified_type(type_right);
1051 if (types_compatible(unqual_type_left, unqual_type_right)) {
1052 return ASSIGN_SUCCESS;
1054 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1055 return ASSIGN_WARNING_INT_FROM_POINTER;
1058 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1059 return ASSIGN_SUCCESS;
1061 return ASSIGN_ERROR_INCOMPATIBLE;
1064 static expression_t *parse_constant_expression(void)
1066 /* start parsing at precedence 7 (conditional expression) */
1067 expression_t *result = parse_sub_expression(7);
1069 if (!is_constant_expression(result)) {
1070 errorf(&result->base.source_position,
1071 "expression '%E' is not constant\n", result);
1077 static expression_t *parse_assignment_expression(void)
1079 /* start parsing at precedence 2 (assignment expression) */
1080 return parse_sub_expression(2);
1083 static type_t *make_global_typedef(const char *name, type_t *type)
1085 symbol_t *const symbol = symbol_table_insert(name);
1087 declaration_t *const declaration = allocate_declaration_zero();
1088 declaration->namespc = NAMESPACE_NORMAL;
1089 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1090 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1091 declaration->type = type;
1092 declaration->symbol = symbol;
1093 declaration->source_position = builtin_source_position;
1095 record_declaration(declaration);
1097 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1098 typedef_type->typedeft.declaration = declaration;
1100 return typedef_type;
1103 static string_t parse_string_literals(void)
1105 assert(token.type == T_STRING_LITERAL);
1106 string_t result = token.v.string;
1110 while (token.type == T_STRING_LITERAL) {
1111 result = concat_strings(&result, &token.v.string);
1118 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1119 [GNU_AK_CONST] = "const",
1120 [GNU_AK_VOLATILE] = "volatile",
1121 [GNU_AK_CDECL] = "cdecl",
1122 [GNU_AK_STDCALL] = "stdcall",
1123 [GNU_AK_FASTCALL] = "fastcall",
1124 [GNU_AK_DEPRECATED] = "deprecated",
1125 [GNU_AK_NOINLINE] = "noinline",
1126 [GNU_AK_NORETURN] = "noreturn",
1127 [GNU_AK_NAKED] = "naked",
1128 [GNU_AK_PURE] = "pure",
1129 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1130 [GNU_AK_MALLOC] = "malloc",
1131 [GNU_AK_WEAK] = "weak",
1132 [GNU_AK_CONSTRUCTOR] = "constructor",
1133 [GNU_AK_DESTRUCTOR] = "destructor",
1134 [GNU_AK_NOTHROW] = "nothrow",
1135 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1136 [GNU_AK_COMMON] = "common",
1137 [GNU_AK_NOCOMMON] = "nocommon",
1138 [GNU_AK_PACKED] = "packed",
1139 [GNU_AK_SHARED] = "shared",
1140 [GNU_AK_NOTSHARED] = "notshared",
1141 [GNU_AK_USED] = "used",
1142 [GNU_AK_UNUSED] = "unused",
1143 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1144 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1145 [GNU_AK_LONGCALL] = "longcall",
1146 [GNU_AK_SHORTCALL] = "shortcall",
1147 [GNU_AK_LONG_CALL] = "long_call",
1148 [GNU_AK_SHORT_CALL] = "short_call",
1149 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1150 [GNU_AK_INTERRUPT] = "interrupt",
1151 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1152 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1153 [GNU_AK_NESTING] = "nesting",
1154 [GNU_AK_NEAR] = "near",
1155 [GNU_AK_FAR] = "far",
1156 [GNU_AK_SIGNAL] = "signal",
1157 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1158 [GNU_AK_TINY_DATA] = "tiny_data",
1159 [GNU_AK_SAVEALL] = "saveall",
1160 [GNU_AK_FLATTEN] = "flatten",
1161 [GNU_AK_SSEREGPARM] = "sseregparm",
1162 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1163 [GNU_AK_RETURN_TWICE] = "return_twice",
1164 [GNU_AK_MAY_ALIAS] = "may_alias",
1165 [GNU_AK_MS_STRUCT] = "ms_struct",
1166 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1167 [GNU_AK_DLLIMPORT] = "dllimport",
1168 [GNU_AK_DLLEXPORT] = "dllexport",
1169 [GNU_AK_ALIGNED] = "aligned",
1170 [GNU_AK_ALIAS] = "alias",
1171 [GNU_AK_SECTION] = "section",
1172 [GNU_AK_FORMAT] = "format",
1173 [GNU_AK_FORMAT_ARG] = "format_arg",
1174 [GNU_AK_WEAKREF] = "weakref",
1175 [GNU_AK_NONNULL] = "nonnull",
1176 [GNU_AK_TLS_MODEL] = "tls_model",
1177 [GNU_AK_VISIBILITY] = "visibility",
1178 [GNU_AK_REGPARM] = "regparm",
1179 [GNU_AK_MODE] = "mode",
1180 [GNU_AK_MODEL] = "model",
1181 [GNU_AK_TRAP_EXIT] = "trap_exit",
1182 [GNU_AK_SP_SWITCH] = "sp_switch",
1183 [GNU_AK_SENTINEL] = "sentinel"
1187 * compare two string, ignoring double underscores on the second.
1189 static int strcmp_underscore(const char *s1, const char *s2)
1191 if (s2[0] == '_' && s2[1] == '_') {
1192 size_t len2 = strlen(s2);
1193 size_t len1 = strlen(s1);
1194 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1195 return strncmp(s1, s2+2, len2-4);
1199 return strcmp(s1, s2);
1203 * Allocate a new gnu temporal attribute.
1205 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1207 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1208 attribute->kind = kind;
1209 attribute->next = NULL;
1210 attribute->invalid = false;
1211 attribute->have_arguments = false;
1217 * parse one constant expression argument.
1219 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1221 expression_t *expression;
1222 add_anchor_token(')');
1223 expression = parse_constant_expression();
1224 rem_anchor_token(')');
1226 attribute->u.argument = fold_constant(expression);
1229 attribute->invalid = true;
1233 * parse a list of constant expressions arguments.
1235 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1237 argument_list_t **list = &attribute->u.arguments;
1238 argument_list_t *entry;
1239 expression_t *expression;
1240 add_anchor_token(')');
1241 add_anchor_token(',');
1243 expression = parse_constant_expression();
1244 entry = obstack_alloc(&temp_obst, sizeof(entry));
1245 entry->argument = fold_constant(expression);
1248 list = &entry->next;
1249 if (token.type != ',')
1253 rem_anchor_token(',');
1254 rem_anchor_token(')');
1258 attribute->invalid = true;
1262 * parse one string literal argument.
1264 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1267 add_anchor_token('(');
1268 if (token.type != T_STRING_LITERAL) {
1269 parse_error_expected("while parsing attribute directive",
1270 T_STRING_LITERAL, NULL);
1273 *string = parse_string_literals();
1274 rem_anchor_token('(');
1278 attribute->invalid = true;
1282 * parse one tls model.
1284 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1286 static const char *const tls_models[] = {
1292 string_t string = { NULL, 0 };
1293 parse_gnu_attribute_string_arg(attribute, &string);
1294 if (string.begin != NULL) {
1295 for(size_t i = 0; i < 4; ++i) {
1296 if (strcmp(tls_models[i], string.begin) == 0) {
1297 attribute->u.value = i;
1301 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1303 attribute->invalid = true;
1307 * parse one tls model.
1309 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1311 static const char *const visibilities[] = {
1317 string_t string = { NULL, 0 };
1318 parse_gnu_attribute_string_arg(attribute, &string);
1319 if (string.begin != NULL) {
1320 for(size_t i = 0; i < 4; ++i) {
1321 if (strcmp(visibilities[i], string.begin) == 0) {
1322 attribute->u.value = i;
1326 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1328 attribute->invalid = true;
1332 * parse one (code) model.
1334 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1336 static const char *const visibilities[] = {
1341 string_t string = { NULL, 0 };
1342 parse_gnu_attribute_string_arg(attribute, &string);
1343 if (string.begin != NULL) {
1344 for(int i = 0; i < 3; ++i) {
1345 if (strcmp(visibilities[i], string.begin) == 0) {
1346 attribute->u.value = i;
1350 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1352 attribute->invalid = true;
1355 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1357 /* TODO: find out what is allowed here... */
1359 /* at least: byte, word, pointer, list of machine modes
1360 * __XXX___ is interpreted as XXX */
1361 add_anchor_token(')');
1363 if (token.type != T_IDENTIFIER) {
1364 expect(T_IDENTIFIER);
1367 /* This isn't really correct, the backend should provide a list of machine
1368 * specific modes (according to gcc philosophy that is...) */
1369 const char *symbol_str = token.v.symbol->string;
1370 if (strcmp_underscore("QI", symbol_str) == 0 ||
1371 strcmp_underscore("byte", symbol_str) == 0) {
1372 attribute->u.akind = ATOMIC_TYPE_CHAR;
1373 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1374 attribute->u.akind = ATOMIC_TYPE_SHORT;
1375 } else if (strcmp_underscore("SI", symbol_str) == 0
1376 || strcmp_underscore("word", symbol_str) == 0
1377 || strcmp_underscore("pointer", symbol_str) == 0) {
1378 attribute->u.akind = ATOMIC_TYPE_INT;
1379 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1380 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1382 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1383 attribute->invalid = true;
1387 rem_anchor_token(')');
1391 attribute->invalid = true;
1395 * parse one interrupt argument.
1397 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1399 static const char *const interrupts[] = {
1406 string_t string = { NULL, 0 };
1407 parse_gnu_attribute_string_arg(attribute, &string);
1408 if (string.begin != NULL) {
1409 for(size_t i = 0; i < 5; ++i) {
1410 if (strcmp(interrupts[i], string.begin) == 0) {
1411 attribute->u.value = i;
1415 errorf(HERE, "'%s' is not an interrupt", string.begin);
1417 attribute->invalid = true;
1421 * parse ( identifier, const expression, const expression )
1423 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1425 static const char *const format_names[] = {
1433 if (token.type != T_IDENTIFIER) {
1434 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1437 const char *name = token.v.symbol->string;
1438 for(i = 0; i < 4; ++i) {
1439 if (strcmp_underscore(format_names[i], name) == 0)
1443 if (warning.attribute)
1444 warningf(HERE, "'%s' is an unrecognized format function type", name);
1449 add_anchor_token(')');
1450 add_anchor_token(',');
1451 parse_constant_expression();
1452 rem_anchor_token(',');
1453 rem_anchor_token('(');
1456 add_anchor_token(')');
1457 parse_constant_expression();
1458 rem_anchor_token('(');
1462 attribute->u.value = true;
1465 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1467 if (!attribute->have_arguments)
1470 /* should have no arguments */
1471 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1472 eat_until_matching_token('(');
1473 /* we have already consumed '(', so we stop before ')', eat it */
1475 attribute->invalid = true;
1479 * Parse one GNU attribute.
1481 * Note that attribute names can be specified WITH or WITHOUT
1482 * double underscores, ie const or __const__.
1484 * The following attributes are parsed without arguments
1509 * no_instrument_function
1510 * warn_unused_result
1527 * externally_visible
1535 * The following attributes are parsed with arguments
1536 * aligned( const expression )
1537 * alias( string literal )
1538 * section( string literal )
1539 * format( identifier, const expression, const expression )
1540 * format_arg( const expression )
1541 * tls_model( string literal )
1542 * visibility( string literal )
1543 * regparm( const expression )
1544 * model( string leteral )
1545 * trap_exit( const expression )
1546 * sp_switch( string literal )
1548 * The following attributes might have arguments
1549 * weak_ref( string literal )
1550 * non_null( const expression // ',' )
1551 * interrupt( string literal )
1552 * sentinel( constant expression )
1554 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1556 gnu_attribute_t *head = *attributes;
1557 gnu_attribute_t *last = *attributes;
1558 decl_modifiers_t modifiers = 0;
1559 gnu_attribute_t *attribute;
1561 eat(T___attribute__);
1565 if (token.type != ')') {
1566 /* find the end of the list */
1568 while (last->next != NULL)
1572 /* non-empty attribute list */
1575 if (token.type == T_const) {
1577 } else if (token.type == T_volatile) {
1579 } else if (token.type == T_cdecl) {
1580 /* __attribute__((cdecl)), WITH ms mode */
1582 } else if (token.type == T_IDENTIFIER) {
1583 const symbol_t *sym = token.v.symbol;
1586 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1593 for(i = 0; i < GNU_AK_LAST; ++i) {
1594 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1597 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1600 if (kind == GNU_AK_LAST) {
1601 if (warning.attribute)
1602 warningf(HERE, "'%s' attribute directive ignored", name);
1604 /* skip possible arguments */
1605 if (token.type == '(') {
1606 eat_until_matching_token(')');
1609 /* check for arguments */
1610 attribute = allocate_gnu_attribute(kind);
1611 if (token.type == '(') {
1613 if (token.type == ')') {
1614 /* empty args are allowed */
1617 attribute->have_arguments = true;
1622 case GNU_AK_VOLATILE:
1627 case GNU_AK_NOCOMMON:
1629 case GNU_AK_NOTSHARED:
1630 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1631 case GNU_AK_WARN_UNUSED_RESULT:
1632 case GNU_AK_LONGCALL:
1633 case GNU_AK_SHORTCALL:
1634 case GNU_AK_LONG_CALL:
1635 case GNU_AK_SHORT_CALL:
1636 case GNU_AK_FUNCTION_VECTOR:
1637 case GNU_AK_INTERRUPT_HANDLER:
1638 case GNU_AK_NMI_HANDLER:
1639 case GNU_AK_NESTING:
1643 case GNU_AK_EIGTHBIT_DATA:
1644 case GNU_AK_TINY_DATA:
1645 case GNU_AK_SAVEALL:
1646 case GNU_AK_FLATTEN:
1647 case GNU_AK_SSEREGPARM:
1648 case GNU_AK_EXTERNALLY_VISIBLE:
1649 case GNU_AK_RETURN_TWICE:
1650 case GNU_AK_MAY_ALIAS:
1651 case GNU_AK_MS_STRUCT:
1652 case GNU_AK_GCC_STRUCT:
1655 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1656 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1657 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1658 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1659 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1660 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1661 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1662 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1663 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1664 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1665 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1666 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1667 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1668 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1669 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1670 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1671 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1673 case GNU_AK_ALIGNED:
1674 /* __align__ may be used without an argument */
1675 if (attribute->have_arguments) {
1676 parse_gnu_attribute_const_arg(attribute);
1680 case GNU_AK_FORMAT_ARG:
1681 case GNU_AK_REGPARM:
1682 case GNU_AK_TRAP_EXIT:
1683 if (!attribute->have_arguments) {
1684 /* should have arguments */
1685 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1686 attribute->invalid = true;
1688 parse_gnu_attribute_const_arg(attribute);
1691 case GNU_AK_SECTION:
1692 case GNU_AK_SP_SWITCH:
1693 if (!attribute->have_arguments) {
1694 /* should have arguments */
1695 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1696 attribute->invalid = true;
1698 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1701 if (!attribute->have_arguments) {
1702 /* should have arguments */
1703 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1704 attribute->invalid = true;
1706 parse_gnu_attribute_format_args(attribute);
1708 case GNU_AK_WEAKREF:
1709 /* may have one string argument */
1710 if (attribute->have_arguments)
1711 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1713 case GNU_AK_NONNULL:
1714 if (attribute->have_arguments)
1715 parse_gnu_attribute_const_arg_list(attribute);
1717 case GNU_AK_TLS_MODEL:
1718 if (!attribute->have_arguments) {
1719 /* should have arguments */
1720 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1722 parse_gnu_attribute_tls_model_arg(attribute);
1724 case GNU_AK_VISIBILITY:
1725 if (!attribute->have_arguments) {
1726 /* should have arguments */
1727 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1729 parse_gnu_attribute_visibility_arg(attribute);
1732 if (!attribute->have_arguments) {
1733 /* should have arguments */
1734 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1736 parse_gnu_attribute_model_arg(attribute);
1740 if (!attribute->have_arguments) {
1741 /* should have arguments */
1742 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1744 parse_gnu_attribute_mode_arg(attribute);
1747 case GNU_AK_INTERRUPT:
1748 /* may have one string argument */
1749 if (attribute->have_arguments)
1750 parse_gnu_attribute_interrupt_arg(attribute);
1752 case GNU_AK_SENTINEL:
1753 /* may have one string argument */
1754 if (attribute->have_arguments)
1755 parse_gnu_attribute_const_arg(attribute);
1758 /* already handled */
1762 check_no_argument(attribute, name);
1765 if (attribute != NULL) {
1767 last->next = attribute;
1770 head = last = attribute;
1774 if (token.type != ',')
1788 * Parse GNU attributes.
1790 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1792 decl_modifiers_t modifiers = 0;
1795 switch(token.type) {
1796 case T___attribute__:
1797 modifiers |= parse_gnu_attribute(attributes);
1803 if (token.type != T_STRING_LITERAL) {
1804 parse_error_expected("while parsing assembler attribute",
1805 T_STRING_LITERAL, NULL);
1806 eat_until_matching_token('(');
1809 parse_string_literals();
1814 case T_cdecl: modifiers |= DM_CDECL; break;
1815 case T__fastcall: modifiers |= DM_FASTCALL; break;
1816 case T__stdcall: modifiers |= DM_STDCALL; break;
1819 /* TODO record modifier */
1820 warningf(HERE, "Ignoring declaration modifier %K", &token);
1824 default: return modifiers;
1831 static designator_t *parse_designation(void)
1833 designator_t *result = NULL;
1834 designator_t *last = NULL;
1837 designator_t *designator;
1838 switch(token.type) {
1840 designator = allocate_ast_zero(sizeof(designator[0]));
1841 designator->source_position = token.source_position;
1843 add_anchor_token(']');
1844 designator->array_index = parse_constant_expression();
1845 rem_anchor_token(']');
1849 designator = allocate_ast_zero(sizeof(designator[0]));
1850 designator->source_position = token.source_position;
1852 if (token.type != T_IDENTIFIER) {
1853 parse_error_expected("while parsing designator",
1854 T_IDENTIFIER, NULL);
1857 designator->symbol = token.v.symbol;
1865 assert(designator != NULL);
1867 last->next = designator;
1869 result = designator;
1877 static initializer_t *initializer_from_string(array_type_t *type,
1878 const string_t *const string)
1880 /* TODO: check len vs. size of array type */
1883 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1884 initializer->string.string = *string;
1889 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1890 wide_string_t *const string)
1892 /* TODO: check len vs. size of array type */
1895 initializer_t *const initializer =
1896 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1897 initializer->wide_string.string = *string;
1903 * Build an initializer from a given expression.
1905 static initializer_t *initializer_from_expression(type_t *orig_type,
1906 expression_t *expression)
1908 /* TODO check that expression is a constant expression */
1910 /* § 6.7.8.14/15 char array may be initialized by string literals */
1911 type_t *type = skip_typeref(orig_type);
1912 type_t *expr_type_orig = expression->base.type;
1913 type_t *expr_type = skip_typeref(expr_type_orig);
1914 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1915 array_type_t *const array_type = &type->array;
1916 type_t *const element_type = skip_typeref(array_type->element_type);
1918 if (element_type->kind == TYPE_ATOMIC) {
1919 atomic_type_kind_t akind = element_type->atomic.akind;
1920 switch (expression->kind) {
1921 case EXPR_STRING_LITERAL:
1922 if (akind == ATOMIC_TYPE_CHAR
1923 || akind == ATOMIC_TYPE_SCHAR
1924 || akind == ATOMIC_TYPE_UCHAR) {
1925 return initializer_from_string(array_type,
1926 &expression->string.value);
1929 case EXPR_WIDE_STRING_LITERAL: {
1930 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1931 if (get_unqualified_type(element_type) == bare_wchar_type) {
1932 return initializer_from_wide_string(array_type,
1933 &expression->wide_string.value);
1943 assign_error_t error = semantic_assign(type, expression);
1944 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1946 report_assign_error(error, type, expression, "initializer",
1947 &expression->base.source_position);
1949 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1950 result->value.value = create_implicit_cast(expression, type);
1956 * Checks if a given expression can be used as an constant initializer.
1958 static bool is_initializer_constant(const expression_t *expression)
1960 return is_constant_expression(expression)
1961 || is_address_constant(expression);
1965 * Parses an scalar initializer.
1967 * § 6.7.8.11; eat {} without warning
1969 static initializer_t *parse_scalar_initializer(type_t *type,
1970 bool must_be_constant)
1972 /* there might be extra {} hierarchies */
1974 if (token.type == '{') {
1975 warningf(HERE, "extra curly braces around scalar initializer");
1979 } while (token.type == '{');
1982 expression_t *expression = parse_assignment_expression();
1983 if (must_be_constant && !is_initializer_constant(expression)) {
1984 errorf(&expression->base.source_position,
1985 "Initialisation expression '%E' is not constant\n",
1989 initializer_t *initializer = initializer_from_expression(type, expression);
1991 if (initializer == NULL) {
1992 errorf(&expression->base.source_position,
1993 "expression '%E' (type '%T') doesn't match expected type '%T'",
1994 expression, expression->base.type, type);
1999 bool additional_warning_displayed = false;
2000 while (braces > 0) {
2001 if (token.type == ',') {
2004 if (token.type != '}') {
2005 if (!additional_warning_displayed) {
2006 warningf(HERE, "additional elements in scalar initializer");
2007 additional_warning_displayed = true;
2018 * An entry in the type path.
2020 typedef struct type_path_entry_t type_path_entry_t;
2021 struct type_path_entry_t {
2022 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2024 size_t index; /**< For array types: the current index. */
2025 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2030 * A type path expression a position inside compound or array types.
2032 typedef struct type_path_t type_path_t;
2033 struct type_path_t {
2034 type_path_entry_t *path; /**< An flexible array containing the current path. */
2035 type_t *top_type; /**< type of the element the path points */
2036 size_t max_index; /**< largest index in outermost array */
2040 * Prints a type path for debugging.
2042 static __attribute__((unused)) void debug_print_type_path(
2043 const type_path_t *path)
2045 size_t len = ARR_LEN(path->path);
2047 for(size_t i = 0; i < len; ++i) {
2048 const type_path_entry_t *entry = & path->path[i];
2050 type_t *type = skip_typeref(entry->type);
2051 if (is_type_compound(type)) {
2052 /* in gcc mode structs can have no members */
2053 if (entry->v.compound_entry == NULL) {
2057 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2058 } else if (is_type_array(type)) {
2059 fprintf(stderr, "[%zu]", entry->v.index);
2061 fprintf(stderr, "-INVALID-");
2064 if (path->top_type != NULL) {
2065 fprintf(stderr, " (");
2066 print_type(path->top_type);
2067 fprintf(stderr, ")");
2072 * Return the top type path entry, ie. in a path
2073 * (type).a.b returns the b.
2075 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2077 size_t len = ARR_LEN(path->path);
2079 return &path->path[len-1];
2083 * Enlarge the type path by an (empty) element.
2085 static type_path_entry_t *append_to_type_path(type_path_t *path)
2087 size_t len = ARR_LEN(path->path);
2088 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2090 type_path_entry_t *result = & path->path[len];
2091 memset(result, 0, sizeof(result[0]));
2096 * Descending into a sub-type. Enter the scope of the current
2099 static void descend_into_subtype(type_path_t *path)
2101 type_t *orig_top_type = path->top_type;
2102 type_t *top_type = skip_typeref(orig_top_type);
2104 assert(is_type_compound(top_type) || is_type_array(top_type));
2106 type_path_entry_t *top = append_to_type_path(path);
2107 top->type = top_type;
2109 if (is_type_compound(top_type)) {
2110 declaration_t *declaration = top_type->compound.declaration;
2111 declaration_t *entry = declaration->scope.declarations;
2112 top->v.compound_entry = entry;
2114 if (entry != NULL) {
2115 path->top_type = entry->type;
2117 path->top_type = NULL;
2120 assert(is_type_array(top_type));
2123 path->top_type = top_type->array.element_type;
2128 * Pop an entry from the given type path, ie. returning from
2129 * (type).a.b to (type).a
2131 static void ascend_from_subtype(type_path_t *path)
2133 type_path_entry_t *top = get_type_path_top(path);
2135 path->top_type = top->type;
2137 size_t len = ARR_LEN(path->path);
2138 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2142 * Pop entries from the given type path until the given
2143 * path level is reached.
2145 static void ascend_to(type_path_t *path, size_t top_path_level)
2147 size_t len = ARR_LEN(path->path);
2149 while (len > top_path_level) {
2150 ascend_from_subtype(path);
2151 len = ARR_LEN(path->path);
2155 static bool walk_designator(type_path_t *path, const designator_t *designator,
2156 bool used_in_offsetof)
2158 for( ; designator != NULL; designator = designator->next) {
2159 type_path_entry_t *top = get_type_path_top(path);
2160 type_t *orig_type = top->type;
2162 type_t *type = skip_typeref(orig_type);
2164 if (designator->symbol != NULL) {
2165 symbol_t *symbol = designator->symbol;
2166 if (!is_type_compound(type)) {
2167 if (is_type_valid(type)) {
2168 errorf(&designator->source_position,
2169 "'.%Y' designator used for non-compound type '%T'",
2175 declaration_t *declaration = type->compound.declaration;
2176 declaration_t *iter = declaration->scope.declarations;
2177 for( ; iter != NULL; iter = iter->next) {
2178 if (iter->symbol == symbol) {
2183 errorf(&designator->source_position,
2184 "'%T' has no member named '%Y'", orig_type, symbol);
2187 if (used_in_offsetof) {
2188 type_t *real_type = skip_typeref(iter->type);
2189 if (real_type->kind == TYPE_BITFIELD) {
2190 errorf(&designator->source_position,
2191 "offsetof designator '%Y' may not specify bitfield",
2197 top->type = orig_type;
2198 top->v.compound_entry = iter;
2199 orig_type = iter->type;
2201 expression_t *array_index = designator->array_index;
2202 assert(designator->array_index != NULL);
2204 if (!is_type_array(type)) {
2205 if (is_type_valid(type)) {
2206 errorf(&designator->source_position,
2207 "[%E] designator used for non-array type '%T'",
2208 array_index, orig_type);
2212 if (!is_type_valid(array_index->base.type)) {
2216 long index = fold_constant(array_index);
2217 if (!used_in_offsetof) {
2219 errorf(&designator->source_position,
2220 "array index [%E] must be positive", array_index);
2223 if (type->array.size_constant == true) {
2224 long array_size = type->array.size;
2225 if (index >= array_size) {
2226 errorf(&designator->source_position,
2227 "designator [%E] (%d) exceeds array size %d",
2228 array_index, index, array_size);
2234 top->type = orig_type;
2235 top->v.index = (size_t) index;
2236 orig_type = type->array.element_type;
2238 path->top_type = orig_type;
2240 if (designator->next != NULL) {
2241 descend_into_subtype(path);
2250 static void advance_current_object(type_path_t *path, size_t top_path_level)
2252 type_path_entry_t *top = get_type_path_top(path);
2254 type_t *type = skip_typeref(top->type);
2255 if (is_type_union(type)) {
2256 /* in unions only the first element is initialized */
2257 top->v.compound_entry = NULL;
2258 } else if (is_type_struct(type)) {
2259 declaration_t *entry = top->v.compound_entry;
2261 entry = entry->next;
2262 top->v.compound_entry = entry;
2263 if (entry != NULL) {
2264 path->top_type = entry->type;
2268 assert(is_type_array(type));
2272 if (!type->array.size_constant || top->v.index < type->array.size) {
2277 /* we're past the last member of the current sub-aggregate, try if we
2278 * can ascend in the type hierarchy and continue with another subobject */
2279 size_t len = ARR_LEN(path->path);
2281 if (len > top_path_level) {
2282 ascend_from_subtype(path);
2283 advance_current_object(path, top_path_level);
2285 path->top_type = NULL;
2290 * skip until token is found.
2292 static void skip_until(int type)
2294 while (token.type != type) {
2295 if (token.type == T_EOF)
2302 * skip any {...} blocks until a closing bracket is reached.
2304 static void skip_initializers(void)
2306 if (token.type == '{')
2309 while (token.type != '}') {
2310 if (token.type == T_EOF)
2312 if (token.type == '{') {
2320 static initializer_t *create_empty_initializer(void)
2322 static initializer_t empty_initializer
2323 = { .list = { { INITIALIZER_LIST }, 0 } };
2324 return &empty_initializer;
2328 * Parse a part of an initialiser for a struct or union,
2330 static initializer_t *parse_sub_initializer(type_path_t *path,
2331 type_t *outer_type, size_t top_path_level,
2332 parse_initializer_env_t *env)
2334 if (token.type == '}') {
2335 /* empty initializer */
2336 return create_empty_initializer();
2339 type_t *orig_type = path->top_type;
2340 type_t *type = NULL;
2342 if (orig_type == NULL) {
2343 /* We are initializing an empty compound. */
2345 type = skip_typeref(orig_type);
2347 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2348 * initializers in this case. */
2349 if (!is_type_valid(type)) {
2350 skip_initializers();
2351 return create_empty_initializer();
2355 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2358 designator_t *designator = NULL;
2359 if (token.type == '.' || token.type == '[') {
2360 designator = parse_designation();
2361 goto finish_designator;
2362 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2363 /* GNU-style designator ("identifier: value") */
2364 designator = allocate_ast_zero(sizeof(designator[0]));
2365 designator->source_position = token.source_position;
2366 designator->symbol = token.v.symbol;
2371 /* reset path to toplevel, evaluate designator from there */
2372 ascend_to(path, top_path_level);
2373 if (!walk_designator(path, designator, false)) {
2374 /* can't continue after designation error */
2378 initializer_t *designator_initializer
2379 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2380 designator_initializer->designator.designator = designator;
2381 ARR_APP1(initializer_t*, initializers, designator_initializer);
2383 orig_type = path->top_type;
2384 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2389 if (token.type == '{') {
2390 if (type != NULL && is_type_scalar(type)) {
2391 sub = parse_scalar_initializer(type, env->must_be_constant);
2395 if (env->declaration != NULL) {
2396 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2397 env->declaration->symbol);
2399 errorf(HERE, "extra brace group at end of initializer");
2402 descend_into_subtype(path);
2404 add_anchor_token('}');
2405 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2407 rem_anchor_token('}');
2410 ascend_from_subtype(path);
2414 goto error_parse_next;
2418 /* must be an expression */
2419 expression_t *expression = parse_assignment_expression();
2421 if (env->must_be_constant && !is_initializer_constant(expression)) {
2422 errorf(&expression->base.source_position,
2423 "Initialisation expression '%E' is not constant\n",
2428 /* we are already outside, ... */
2432 /* handle { "string" } special case */
2433 if ((expression->kind == EXPR_STRING_LITERAL
2434 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2435 && outer_type != NULL) {
2436 sub = initializer_from_expression(outer_type, expression);
2438 if (token.type == ',') {
2441 if (token.type != '}') {
2442 warningf(HERE, "excessive elements in initializer for type '%T'",
2445 /* TODO: eat , ... */
2450 /* descend into subtypes until expression matches type */
2452 orig_type = path->top_type;
2453 type = skip_typeref(orig_type);
2455 sub = initializer_from_expression(orig_type, expression);
2459 if (!is_type_valid(type)) {
2462 if (is_type_scalar(type)) {
2463 errorf(&expression->base.source_position,
2464 "expression '%E' doesn't match expected type '%T'",
2465 expression, orig_type);
2469 descend_into_subtype(path);
2473 /* update largest index of top array */
2474 const type_path_entry_t *first = &path->path[0];
2475 type_t *first_type = first->type;
2476 first_type = skip_typeref(first_type);
2477 if (is_type_array(first_type)) {
2478 size_t index = first->v.index;
2479 if (index > path->max_index)
2480 path->max_index = index;
2484 /* append to initializers list */
2485 ARR_APP1(initializer_t*, initializers, sub);
2488 if (env->declaration != NULL)
2489 warningf(HERE, "excess elements in struct initializer for '%Y'",
2490 env->declaration->symbol);
2492 warningf(HERE, "excess elements in struct initializer");
2496 if (token.type == '}') {
2500 if (token.type == '}') {
2505 /* advance to the next declaration if we are not at the end */
2506 advance_current_object(path, top_path_level);
2507 orig_type = path->top_type;
2508 if (orig_type != NULL)
2509 type = skip_typeref(orig_type);
2515 size_t len = ARR_LEN(initializers);
2516 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2517 initializer_t *result = allocate_ast_zero(size);
2518 result->kind = INITIALIZER_LIST;
2519 result->list.len = len;
2520 memcpy(&result->list.initializers, initializers,
2521 len * sizeof(initializers[0]));
2523 DEL_ARR_F(initializers);
2524 ascend_to(path, top_path_level+1);
2529 skip_initializers();
2530 DEL_ARR_F(initializers);
2531 ascend_to(path, top_path_level+1);
2536 * Parses an initializer. Parsers either a compound literal
2537 * (env->declaration == NULL) or an initializer of a declaration.
2539 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2541 type_t *type = skip_typeref(env->type);
2542 initializer_t *result = NULL;
2545 if (is_type_scalar(type)) {
2546 result = parse_scalar_initializer(type, env->must_be_constant);
2547 } else if (token.type == '{') {
2551 memset(&path, 0, sizeof(path));
2552 path.top_type = env->type;
2553 path.path = NEW_ARR_F(type_path_entry_t, 0);
2555 descend_into_subtype(&path);
2557 add_anchor_token('}');
2558 result = parse_sub_initializer(&path, env->type, 1, env);
2559 rem_anchor_token('}');
2561 max_index = path.max_index;
2562 DEL_ARR_F(path.path);
2566 /* parse_scalar_initializer() also works in this case: we simply
2567 * have an expression without {} around it */
2568 result = parse_scalar_initializer(type, env->must_be_constant);
2571 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2572 * the array type size */
2573 if (is_type_array(type) && type->array.size_expression == NULL
2574 && result != NULL) {
2576 switch (result->kind) {
2577 case INITIALIZER_LIST:
2578 size = max_index + 1;
2581 case INITIALIZER_STRING:
2582 size = result->string.string.size;
2585 case INITIALIZER_WIDE_STRING:
2586 size = result->wide_string.string.size;
2589 case INITIALIZER_DESIGNATOR:
2590 case INITIALIZER_VALUE:
2591 /* can happen for parse errors */
2596 internal_errorf(HERE, "invalid initializer type");
2599 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2600 cnst->base.type = type_size_t;
2601 cnst->conste.v.int_value = size;
2603 type_t *new_type = duplicate_type(type);
2605 new_type->array.size_expression = cnst;
2606 new_type->array.size_constant = true;
2607 new_type->array.size = size;
2608 env->type = new_type;
2616 static declaration_t *append_declaration(declaration_t *declaration);
2618 static declaration_t *parse_compound_type_specifier(bool is_struct)
2620 gnu_attribute_t *attributes = NULL;
2621 decl_modifiers_t modifiers = 0;
2628 symbol_t *symbol = NULL;
2629 declaration_t *declaration = NULL;
2631 if (token.type == T___attribute__) {
2632 modifiers |= parse_attributes(&attributes);
2635 if (token.type == T_IDENTIFIER) {
2636 symbol = token.v.symbol;
2639 namespace_t const namespc =
2640 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2641 declaration = get_declaration(symbol, namespc);
2642 if (declaration != NULL) {
2643 if (declaration->parent_scope != scope &&
2644 (token.type == '{' || token.type == ';')) {
2646 } else if (declaration->init.complete &&
2647 token.type == '{') {
2648 assert(symbol != NULL);
2649 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2650 is_struct ? "struct" : "union", symbol,
2651 &declaration->source_position);
2652 declaration->scope.declarations = NULL;
2655 } else if (token.type != '{') {
2657 parse_error_expected("while parsing struct type specifier",
2658 T_IDENTIFIER, '{', NULL);
2660 parse_error_expected("while parsing union type specifier",
2661 T_IDENTIFIER, '{', NULL);
2667 if (declaration == NULL) {
2668 declaration = allocate_declaration_zero();
2669 declaration->namespc =
2670 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2671 declaration->source_position = token.source_position;
2672 declaration->symbol = symbol;
2673 declaration->parent_scope = scope;
2674 if (symbol != NULL) {
2675 environment_push(declaration);
2677 append_declaration(declaration);
2680 if (token.type == '{') {
2681 declaration->init.complete = true;
2683 parse_compound_type_entries(declaration);
2684 modifiers |= parse_attributes(&attributes);
2687 declaration->modifiers |= modifiers;
2691 static void parse_enum_entries(type_t *const enum_type)
2695 if (token.type == '}') {
2697 errorf(HERE, "empty enum not allowed");
2701 add_anchor_token('}');
2703 if (token.type != T_IDENTIFIER) {
2704 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2706 rem_anchor_token('}');
2710 declaration_t *const entry = allocate_declaration_zero();
2711 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2712 entry->type = enum_type;
2713 entry->symbol = token.v.symbol;
2714 entry->source_position = token.source_position;
2717 if (token.type == '=') {
2719 expression_t *value = parse_constant_expression();
2721 value = create_implicit_cast(value, enum_type);
2722 entry->init.enum_value = value;
2727 record_declaration(entry);
2729 if (token.type != ',')
2732 } while (token.type != '}');
2733 rem_anchor_token('}');
2741 static type_t *parse_enum_specifier(void)
2743 gnu_attribute_t *attributes = NULL;
2744 declaration_t *declaration;
2748 if (token.type == T_IDENTIFIER) {
2749 symbol = token.v.symbol;
2752 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2753 } else if (token.type != '{') {
2754 parse_error_expected("while parsing enum type specifier",
2755 T_IDENTIFIER, '{', NULL);
2762 if (declaration == NULL) {
2763 declaration = allocate_declaration_zero();
2764 declaration->namespc = NAMESPACE_ENUM;
2765 declaration->source_position = token.source_position;
2766 declaration->symbol = symbol;
2767 declaration->parent_scope = scope;
2770 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2771 type->enumt.declaration = declaration;
2773 if (token.type == '{') {
2774 if (declaration->init.complete) {
2775 errorf(HERE, "multiple definitions of enum %Y", symbol);
2777 if (symbol != NULL) {
2778 environment_push(declaration);
2780 append_declaration(declaration);
2781 declaration->init.complete = true;
2783 parse_enum_entries(type);
2784 parse_attributes(&attributes);
2791 * if a symbol is a typedef to another type, return true
2793 static bool is_typedef_symbol(symbol_t *symbol)
2795 const declaration_t *const declaration =
2796 get_declaration(symbol, NAMESPACE_NORMAL);
2798 declaration != NULL &&
2799 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2802 static type_t *parse_typeof(void)
2809 add_anchor_token(')');
2811 expression_t *expression = NULL;
2814 switch(token.type) {
2815 case T___extension__:
2816 /* This can be a prefix to a typename or an expression. We simply eat
2820 } while (token.type == T___extension__);
2824 if (is_typedef_symbol(token.v.symbol)) {
2825 type = parse_typename();
2827 expression = parse_expression();
2828 type = expression->base.type;
2833 type = parse_typename();
2837 expression = parse_expression();
2838 type = expression->base.type;
2842 rem_anchor_token(')');
2845 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2846 typeof_type->typeoft.expression = expression;
2847 typeof_type->typeoft.typeof_type = type;
2854 typedef enum specifiers_t {
2855 SPECIFIER_SIGNED = 1 << 0,
2856 SPECIFIER_UNSIGNED = 1 << 1,
2857 SPECIFIER_LONG = 1 << 2,
2858 SPECIFIER_INT = 1 << 3,
2859 SPECIFIER_DOUBLE = 1 << 4,
2860 SPECIFIER_CHAR = 1 << 5,
2861 SPECIFIER_SHORT = 1 << 6,
2862 SPECIFIER_LONG_LONG = 1 << 7,
2863 SPECIFIER_FLOAT = 1 << 8,
2864 SPECIFIER_BOOL = 1 << 9,
2865 SPECIFIER_VOID = 1 << 10,
2866 SPECIFIER_INT8 = 1 << 11,
2867 SPECIFIER_INT16 = 1 << 12,
2868 SPECIFIER_INT32 = 1 << 13,
2869 SPECIFIER_INT64 = 1 << 14,
2870 SPECIFIER_INT128 = 1 << 15,
2871 SPECIFIER_COMPLEX = 1 << 16,
2872 SPECIFIER_IMAGINARY = 1 << 17,
2875 static type_t *create_builtin_type(symbol_t *const symbol,
2876 type_t *const real_type)
2878 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2879 type->builtin.symbol = symbol;
2880 type->builtin.real_type = real_type;
2882 type_t *result = typehash_insert(type);
2883 if (type != result) {
2890 static type_t *get_typedef_type(symbol_t *symbol)
2892 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2893 if (declaration == NULL ||
2894 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2897 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2898 type->typedeft.declaration = declaration;
2904 * check for the allowed MS alignment values.
2906 static bool check_alignment_value(long long intvalue)
2908 if (intvalue < 1 || intvalue > 8192) {
2909 errorf(HERE, "illegal alignment value");
2912 unsigned v = (unsigned)intvalue;
2913 for(unsigned i = 1; i <= 8192; i += i) {
2917 errorf(HERE, "alignment must be power of two");
2921 #define DET_MOD(name, tag) do { \
2922 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2923 *modifiers |= tag; \
2926 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2928 decl_modifiers_t *modifiers = &specifiers->modifiers;
2931 if (token.type == T_restrict) {
2933 DET_MOD(restrict, DM_RESTRICT);
2935 } else if (token.type != T_IDENTIFIER)
2937 symbol_t *symbol = token.v.symbol;
2938 if (symbol == sym_align) {
2941 if (token.type != T_INTEGER)
2943 if (check_alignment_value(token.v.intvalue)) {
2944 if (specifiers->alignment != 0)
2945 warningf(HERE, "align used more than once");
2946 specifiers->alignment = (unsigned char)token.v.intvalue;
2950 } else if (symbol == sym_allocate) {
2953 if (token.type != T_IDENTIFIER)
2955 (void)token.v.symbol;
2957 } else if (symbol == sym_dllimport) {
2959 DET_MOD(dllimport, DM_DLLIMPORT);
2960 } else if (symbol == sym_dllexport) {
2962 DET_MOD(dllexport, DM_DLLEXPORT);
2963 } else if (symbol == sym_thread) {
2965 DET_MOD(thread, DM_THREAD);
2966 } else if (symbol == sym_naked) {
2968 DET_MOD(naked, DM_NAKED);
2969 } else if (symbol == sym_noinline) {
2971 DET_MOD(noinline, DM_NOINLINE);
2972 } else if (symbol == sym_noreturn) {
2974 DET_MOD(noreturn, DM_NORETURN);
2975 } else if (symbol == sym_nothrow) {
2977 DET_MOD(nothrow, DM_NOTHROW);
2978 } else if (symbol == sym_novtable) {
2980 DET_MOD(novtable, DM_NOVTABLE);
2981 } else if (symbol == sym_property) {
2985 bool is_get = false;
2986 if (token.type != T_IDENTIFIER)
2988 if (token.v.symbol == sym_get) {
2990 } else if (token.v.symbol == sym_put) {
2992 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2997 if (token.type != T_IDENTIFIER)
3000 if (specifiers->get_property_sym != NULL) {
3001 errorf(HERE, "get property name already specified");
3003 specifiers->get_property_sym = token.v.symbol;
3006 if (specifiers->put_property_sym != NULL) {
3007 errorf(HERE, "put property name already specified");
3009 specifiers->put_property_sym = token.v.symbol;
3013 if (token.type == ',') {
3020 } else if (symbol == sym_selectany) {
3022 DET_MOD(selectany, DM_SELECTANY);
3023 } else if (symbol == sym_uuid) {
3026 if (token.type != T_STRING_LITERAL)
3030 } else if (symbol == sym_deprecated) {
3032 if (specifiers->deprecated != 0)
3033 warningf(HERE, "deprecated used more than once");
3034 specifiers->deprecated = 1;
3035 if (token.type == '(') {
3037 if (token.type == T_STRING_LITERAL) {
3038 specifiers->deprecated_string = token.v.string.begin;
3041 errorf(HERE, "string literal expected");
3045 } else if (symbol == sym_noalias) {
3047 DET_MOD(noalias, DM_NOALIAS);
3049 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3051 if (token.type == '(')
3055 if (token.type == ',')
3062 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3064 type_t *type = NULL;
3065 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3066 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3067 unsigned type_specifiers = 0;
3068 bool newtype = false;
3069 bool saw_error = false;
3071 specifiers->source_position = token.source_position;
3074 specifiers->modifiers
3075 |= parse_attributes(&specifiers->gnu_attributes);
3076 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3077 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3079 switch(token.type) {
3082 #define MATCH_STORAGE_CLASS(token, class) \
3084 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3085 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3087 specifiers->declared_storage_class = class; \
3091 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3092 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3093 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3094 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3095 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3100 add_anchor_token(')');
3101 parse_microsoft_extended_decl_modifier(specifiers);
3102 rem_anchor_token(')');
3107 switch (specifiers->declared_storage_class) {
3108 case STORAGE_CLASS_NONE:
3109 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3112 case STORAGE_CLASS_EXTERN:
3113 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3116 case STORAGE_CLASS_STATIC:
3117 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3121 errorf(HERE, "multiple storage classes in declaration specifiers");
3127 /* type qualifiers */
3128 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3130 qualifiers |= qualifier; \
3134 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3135 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3136 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3137 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3138 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3139 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3140 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3141 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3143 case T___extension__:
3148 /* type specifiers */
3149 #define MATCH_SPECIFIER(token, specifier, name) \
3152 if (type_specifiers & specifier) { \
3153 errorf(HERE, "multiple " name " type specifiers given"); \
3155 type_specifiers |= specifier; \
3159 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3160 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3161 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3162 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3163 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3164 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3165 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3166 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3167 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3168 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3169 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3170 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3171 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3172 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3173 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3174 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3176 case T__forceinline:
3177 /* only in microsoft mode */
3178 specifiers->modifiers |= DM_FORCEINLINE;
3183 specifiers->is_inline = true;
3188 if (type_specifiers & SPECIFIER_LONG_LONG) {
3189 errorf(HERE, "multiple type specifiers given");
3190 } else if (type_specifiers & SPECIFIER_LONG) {
3191 type_specifiers |= SPECIFIER_LONG_LONG;
3193 type_specifiers |= SPECIFIER_LONG;
3198 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3200 type->compound.declaration = parse_compound_type_specifier(true);
3204 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3205 type->compound.declaration = parse_compound_type_specifier(false);
3206 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3207 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3211 type = parse_enum_specifier();
3214 type = parse_typeof();
3216 case T___builtin_va_list:
3217 type = duplicate_type(type_valist);
3221 case T_IDENTIFIER: {
3222 /* only parse identifier if we haven't found a type yet */
3223 if (type != NULL || type_specifiers != 0) {
3224 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3225 * declaration, so it doesn't generate errors about expecting '(' or
3227 switch (look_ahead(1)->type) {
3234 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3237 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3242 goto finish_specifiers;
3246 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3247 if (typedef_type == NULL) {
3248 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3249 * declaration, so it doesn't generate 'implicit int' followed by more
3250 * errors later on. */
3251 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3256 errorf(HERE, "%K does not name a type", &token);
3259 if (la1_type == '*')
3260 goto finish_specifiers;
3264 goto finish_specifiers;
3269 type = typedef_type;
3273 /* function specifier */
3275 goto finish_specifiers;
3282 atomic_type_kind_t atomic_type;
3284 /* match valid basic types */
3285 switch(type_specifiers) {
3286 case SPECIFIER_VOID:
3287 atomic_type = ATOMIC_TYPE_VOID;
3289 case SPECIFIER_CHAR:
3290 atomic_type = ATOMIC_TYPE_CHAR;
3292 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3293 atomic_type = ATOMIC_TYPE_SCHAR;
3295 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3296 atomic_type = ATOMIC_TYPE_UCHAR;
3298 case SPECIFIER_SHORT:
3299 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3300 case SPECIFIER_SHORT | SPECIFIER_INT:
3301 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3302 atomic_type = ATOMIC_TYPE_SHORT;
3304 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3305 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3306 atomic_type = ATOMIC_TYPE_USHORT;
3309 case SPECIFIER_SIGNED:
3310 case SPECIFIER_SIGNED | SPECIFIER_INT:
3311 atomic_type = ATOMIC_TYPE_INT;
3313 case SPECIFIER_UNSIGNED:
3314 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3315 atomic_type = ATOMIC_TYPE_UINT;
3317 case SPECIFIER_LONG:
3318 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3319 case SPECIFIER_LONG | SPECIFIER_INT:
3320 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3321 atomic_type = ATOMIC_TYPE_LONG;
3323 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3324 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3325 atomic_type = ATOMIC_TYPE_ULONG;
3328 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3329 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3330 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3331 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3333 atomic_type = ATOMIC_TYPE_LONGLONG;
3334 goto warn_about_long_long;
3336 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3337 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3339 atomic_type = ATOMIC_TYPE_ULONGLONG;
3340 warn_about_long_long:
3341 if (warning.long_long) {
3342 warningf(&specifiers->source_position,
3343 "ISO C90 does not support 'long long'");
3347 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3348 atomic_type = unsigned_int8_type_kind;
3351 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3352 atomic_type = unsigned_int16_type_kind;
3355 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3356 atomic_type = unsigned_int32_type_kind;
3359 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3360 atomic_type = unsigned_int64_type_kind;
3363 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3364 atomic_type = unsigned_int128_type_kind;
3367 case SPECIFIER_INT8:
3368 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3369 atomic_type = int8_type_kind;
3372 case SPECIFIER_INT16:
3373 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3374 atomic_type = int16_type_kind;
3377 case SPECIFIER_INT32:
3378 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3379 atomic_type = int32_type_kind;
3382 case SPECIFIER_INT64:
3383 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3384 atomic_type = int64_type_kind;
3387 case SPECIFIER_INT128:
3388 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3389 atomic_type = int128_type_kind;
3392 case SPECIFIER_FLOAT:
3393 atomic_type = ATOMIC_TYPE_FLOAT;
3395 case SPECIFIER_DOUBLE:
3396 atomic_type = ATOMIC_TYPE_DOUBLE;
3398 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3399 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3401 case SPECIFIER_BOOL:
3402 atomic_type = ATOMIC_TYPE_BOOL;
3404 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3405 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3406 atomic_type = ATOMIC_TYPE_FLOAT;
3408 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3409 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3410 atomic_type = ATOMIC_TYPE_DOUBLE;
3412 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3413 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3414 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3417 /* invalid specifier combination, give an error message */
3418 if (type_specifiers == 0) {
3420 specifiers->type = type_error_type;
3425 if (warning.implicit_int) {
3426 warningf(HERE, "no type specifiers in declaration, using 'int'");
3428 atomic_type = ATOMIC_TYPE_INT;
3431 errorf(HERE, "no type specifiers given in declaration");
3433 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3434 (type_specifiers & SPECIFIER_UNSIGNED)) {
3435 errorf(HERE, "signed and unsigned specifiers given");
3436 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3437 errorf(HERE, "only integer types can be signed or unsigned");
3439 errorf(HERE, "multiple datatypes in declaration");
3441 atomic_type = ATOMIC_TYPE_INVALID;
3444 if (type_specifiers & SPECIFIER_COMPLEX &&
3445 atomic_type != ATOMIC_TYPE_INVALID) {
3446 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3447 type->complex.akind = atomic_type;
3448 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3449 atomic_type != ATOMIC_TYPE_INVALID) {
3450 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3451 type->imaginary.akind = atomic_type;
3453 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3454 type->atomic.akind = atomic_type;
3457 } else if (type_specifiers != 0) {
3458 errorf(HERE, "multiple datatypes in declaration");
3461 /* FIXME: check type qualifiers here */
3463 type->base.qualifiers = qualifiers;
3464 type->base.modifiers = modifiers;
3466 type_t *result = typehash_insert(type);
3467 if (newtype && result != type) {
3471 specifiers->type = result;
3476 static type_qualifiers_t parse_type_qualifiers(void)
3478 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3481 switch(token.type) {
3482 /* type qualifiers */
3483 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3484 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3485 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3486 /* microsoft extended type modifiers */
3487 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3488 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3489 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3490 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3491 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3499 static declaration_t *parse_identifier_list(void)
3501 declaration_t *declarations = NULL;
3502 declaration_t *last_declaration = NULL;
3504 declaration_t *const declaration = allocate_declaration_zero();
3505 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3506 declaration->source_position = token.source_position;
3507 declaration->symbol = token.v.symbol;
3510 if (last_declaration != NULL) {
3511 last_declaration->next = declaration;
3513 declarations = declaration;
3515 last_declaration = declaration;
3517 if (token.type != ',') {
3521 } while (token.type == T_IDENTIFIER);
3523 return declarations;
3526 static type_t *automatic_type_conversion(type_t *orig_type);
3528 static void semantic_parameter(declaration_t *declaration)
3530 /* TODO: improve error messages */
3531 source_position_t const* const pos = &declaration->source_position;
3533 switch (declaration->declared_storage_class) {
3534 case STORAGE_CLASS_TYPEDEF:
3535 errorf(pos, "typedef not allowed in parameter list");
3538 /* Allowed storage classes */
3539 case STORAGE_CLASS_NONE:
3540 case STORAGE_CLASS_REGISTER:
3544 errorf(pos, "parameter may only have none or register storage class");
3548 type_t *const orig_type = declaration->type;
3549 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3550 * sugar. Turn it into a pointer.
3551 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3552 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3554 type_t *const type = automatic_type_conversion(orig_type);
3555 declaration->type = type;
3557 if (is_type_incomplete(skip_typeref(type))) {
3558 errorf(pos, "incomplete type '%T' not allowed for parameter '%Y'",
3559 orig_type, declaration->symbol);
3563 static declaration_t *parse_parameter(void)
3565 declaration_specifiers_t specifiers;
3566 memset(&specifiers, 0, sizeof(specifiers));
3568 parse_declaration_specifiers(&specifiers);
3570 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3575 static declaration_t *parse_parameters(function_type_t *type)
3577 declaration_t *declarations = NULL;
3580 add_anchor_token(')');
3581 int saved_comma_state = save_and_reset_anchor_state(',');
3583 if (token.type == T_IDENTIFIER) {
3584 symbol_t *symbol = token.v.symbol;
3585 if (!is_typedef_symbol(symbol)) {
3586 type->kr_style_parameters = true;
3587 declarations = parse_identifier_list();
3588 goto parameters_finished;
3592 if (token.type == ')') {
3593 type->unspecified_parameters = 1;
3594 goto parameters_finished;
3597 declaration_t *declaration;
3598 declaration_t *last_declaration = NULL;
3599 function_parameter_t *parameter;
3600 function_parameter_t *last_parameter = NULL;
3603 switch(token.type) {
3607 goto parameters_finished;
3610 case T___extension__:
3612 declaration = parse_parameter();
3614 /* func(void) is not a parameter */
3615 if (last_parameter == NULL
3616 && token.type == ')'
3617 && declaration->symbol == NULL
3618 && skip_typeref(declaration->type) == type_void) {
3619 goto parameters_finished;
3621 semantic_parameter(declaration);
3623 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3624 memset(parameter, 0, sizeof(parameter[0]));
3625 parameter->type = declaration->type;
3627 if (last_parameter != NULL) {
3628 last_declaration->next = declaration;
3629 last_parameter->next = parameter;
3631 type->parameters = parameter;
3632 declarations = declaration;
3634 last_parameter = parameter;
3635 last_declaration = declaration;
3639 goto parameters_finished;
3641 if (token.type != ',') {
3642 goto parameters_finished;
3648 parameters_finished:
3649 rem_anchor_token(')');
3652 restore_anchor_state(',', saved_comma_state);
3653 return declarations;
3656 restore_anchor_state(',', saved_comma_state);
3660 typedef enum construct_type_kind_t {
3665 } construct_type_kind_t;
3667 typedef struct construct_type_t construct_type_t;
3668 struct construct_type_t {
3669 construct_type_kind_t kind;
3670 construct_type_t *next;
3673 typedef struct parsed_pointer_t parsed_pointer_t;
3674 struct parsed_pointer_t {
3675 construct_type_t construct_type;
3676 type_qualifiers_t type_qualifiers;
3679 typedef struct construct_function_type_t construct_function_type_t;
3680 struct construct_function_type_t {
3681 construct_type_t construct_type;
3682 type_t *function_type;
3685 typedef struct parsed_array_t parsed_array_t;
3686 struct parsed_array_t {
3687 construct_type_t construct_type;
3688 type_qualifiers_t type_qualifiers;
3694 typedef struct construct_base_type_t construct_base_type_t;
3695 struct construct_base_type_t {
3696 construct_type_t construct_type;
3700 static construct_type_t *parse_pointer_declarator(void)
3704 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3705 memset(pointer, 0, sizeof(pointer[0]));
3706 pointer->construct_type.kind = CONSTRUCT_POINTER;
3707 pointer->type_qualifiers = parse_type_qualifiers();
3709 return (construct_type_t*) pointer;
3712 static construct_type_t *parse_array_declarator(void)
3715 add_anchor_token(']');
3717 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3718 memset(array, 0, sizeof(array[0]));
3719 array->construct_type.kind = CONSTRUCT_ARRAY;
3721 if (token.type == T_static) {
3722 array->is_static = true;
3726 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3727 if (type_qualifiers != 0) {
3728 if (token.type == T_static) {
3729 array->is_static = true;
3733 array->type_qualifiers = type_qualifiers;
3735 if (token.type == '*' && look_ahead(1)->type == ']') {
3736 array->is_variable = true;
3738 } else if (token.type != ']') {
3739 array->size = parse_assignment_expression();
3742 rem_anchor_token(']');
3745 return (construct_type_t*) array;
3750 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3753 if (declaration != NULL) {
3754 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3756 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3758 if (mask & (mask-1)) {
3759 const char *first = NULL, *second = NULL;
3761 /* more than one calling convention set */
3762 if (declaration->modifiers & DM_CDECL) {
3763 if (first == NULL) first = "cdecl";
3764 else if (second == NULL) second = "cdecl";
3766 if (declaration->modifiers & DM_STDCALL) {
3767 if (first == NULL) first = "stdcall";
3768 else if (second == NULL) second = "stdcall";
3770 if (declaration->modifiers & DM_FASTCALL) {
3771 if (first == NULL) first = "fastcall";
3772 else if (second == NULL) second = "fastcall";
3774 if (declaration->modifiers & DM_THISCALL) {
3775 if (first == NULL) first = "thiscall";
3776 else if (second == NULL) second = "thiscall";
3778 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3781 if (declaration->modifiers & DM_CDECL)
3782 type->function.calling_convention = CC_CDECL;
3783 else if (declaration->modifiers & DM_STDCALL)
3784 type->function.calling_convention = CC_STDCALL;
3785 else if (declaration->modifiers & DM_FASTCALL)
3786 type->function.calling_convention = CC_FASTCALL;
3787 else if (declaration->modifiers & DM_THISCALL)
3788 type->function.calling_convention = CC_THISCALL;
3790 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3793 declaration_t *parameters = parse_parameters(&type->function);
3794 if (declaration != NULL) {
3795 declaration->scope.declarations = parameters;
3798 construct_function_type_t *construct_function_type =
3799 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3800 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3801 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3802 construct_function_type->function_type = type;
3804 return &construct_function_type->construct_type;
3807 static void fix_declaration_type(declaration_t *declaration)
3809 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3810 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3812 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3813 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3815 if (declaration->type->base.modifiers == type_modifiers)
3818 type_t *copy = duplicate_type(declaration->type);
3819 copy->base.modifiers = type_modifiers;
3821 type_t *result = typehash_insert(copy);
3822 if (result != copy) {
3823 obstack_free(type_obst, copy);
3826 declaration->type = result;
3829 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3830 bool may_be_abstract)
3832 /* construct a single linked list of construct_type_t's which describe
3833 * how to construct the final declarator type */
3834 construct_type_t *first = NULL;
3835 construct_type_t *last = NULL;
3836 gnu_attribute_t *attributes = NULL;
3838 decl_modifiers_t modifiers = parse_attributes(&attributes);
3841 while (token.type == '*') {
3842 construct_type_t *type = parse_pointer_declarator();
3852 /* TODO: find out if this is correct */
3853 modifiers |= parse_attributes(&attributes);
3856 if (declaration != NULL)
3857 declaration->modifiers |= modifiers;
3859 construct_type_t *inner_types = NULL;
3861 switch(token.type) {
3863 if (declaration == NULL) {
3864 errorf(HERE, "no identifier expected in typename");
3866 declaration->symbol = token.v.symbol;
3867 declaration->source_position = token.source_position;
3873 add_anchor_token(')');
3874 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3875 /* All later declarators only modify the return type, not declaration */
3877 rem_anchor_token(')');
3881 if (may_be_abstract)
3883 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3884 /* avoid a loop in the outermost scope, because eat_statement doesn't
3886 if (token.type == '}' && current_function == NULL) {
3894 construct_type_t *p = last;
3897 construct_type_t *type;
3898 switch(token.type) {
3900 type = parse_function_declarator(declaration);
3903 type = parse_array_declarator();
3906 goto declarator_finished;
3909 /* insert in the middle of the list (behind p) */
3911 type->next = p->next;
3922 declarator_finished:
3923 /* append inner_types at the end of the list, we don't to set last anymore
3924 * as it's not needed anymore */
3926 assert(first == NULL);
3927 first = inner_types;
3929 last->next = inner_types;
3937 static void parse_declaration_attributes(declaration_t *declaration)
3939 gnu_attribute_t *attributes = NULL;
3940 decl_modifiers_t modifiers = parse_attributes(&attributes);
3942 if (declaration == NULL)
3945 declaration->modifiers |= modifiers;
3946 /* check if we have these stupid mode attributes... */
3947 type_t *old_type = declaration->type;
3948 if (old_type == NULL)
3951 gnu_attribute_t *attribute = attributes;
3952 for ( ; attribute != NULL; attribute = attribute->next) {
3953 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3956 atomic_type_kind_t akind = attribute->u.akind;
3957 if (!is_type_signed(old_type)) {
3959 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3960 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3961 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3962 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3964 panic("invalid akind in mode attribute");
3968 = make_atomic_type(akind, old_type->base.qualifiers);
3972 static type_t *construct_declarator_type(construct_type_t *construct_list,
3975 construct_type_t *iter = construct_list;
3976 for( ; iter != NULL; iter = iter->next) {
3977 switch(iter->kind) {
3978 case CONSTRUCT_INVALID:
3979 internal_errorf(HERE, "invalid type construction found");
3980 case CONSTRUCT_FUNCTION: {
3981 construct_function_type_t *construct_function_type
3982 = (construct_function_type_t*) iter;
3984 type_t *function_type = construct_function_type->function_type;
3986 function_type->function.return_type = type;
3988 type_t *skipped_return_type = skip_typeref(type);
3989 if (is_type_function(skipped_return_type)) {
3990 errorf(HERE, "function returning function is not allowed");
3991 type = type_error_type;
3992 } else if (is_type_array(skipped_return_type)) {
3993 errorf(HERE, "function returning array is not allowed");
3994 type = type_error_type;
3996 type = function_type;
4001 case CONSTRUCT_POINTER: {
4002 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4003 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4004 pointer_type->pointer.points_to = type;
4005 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4007 type = pointer_type;
4011 case CONSTRUCT_ARRAY: {
4012 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4013 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4015 expression_t *size_expression = parsed_array->size;
4016 if (size_expression != NULL) {
4018 = create_implicit_cast(size_expression, type_size_t);
4021 array_type->base.qualifiers = parsed_array->type_qualifiers;
4022 array_type->array.element_type = type;
4023 array_type->array.is_static = parsed_array->is_static;
4024 array_type->array.is_variable = parsed_array->is_variable;
4025 array_type->array.size_expression = size_expression;
4027 if (size_expression != NULL) {
4028 if (is_constant_expression(size_expression)) {
4029 array_type->array.size_constant = true;
4030 array_type->array.size
4031 = fold_constant(size_expression);
4033 array_type->array.is_vla = true;
4037 type_t *skipped_type = skip_typeref(type);
4038 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
4039 errorf(HERE, "array of void is not allowed");
4040 type = type_error_type;
4048 type_t *hashed_type = typehash_insert(type);
4049 if (hashed_type != type) {
4050 /* the function type was constructed earlier freeing it here will
4051 * destroy other types... */
4052 if (iter->kind != CONSTRUCT_FUNCTION) {
4062 static declaration_t *parse_declarator(
4063 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4065 declaration_t *const declaration = allocate_declaration_zero();
4066 declaration->source_position = specifiers->source_position;
4067 declaration->declared_storage_class = specifiers->declared_storage_class;
4068 declaration->modifiers = specifiers->modifiers;
4069 declaration->deprecated_string = specifiers->deprecated_string;
4070 declaration->get_property_sym = specifiers->get_property_sym;
4071 declaration->put_property_sym = specifiers->put_property_sym;
4072 declaration->is_inline = specifiers->is_inline;
4074 declaration->storage_class = specifiers->declared_storage_class;
4075 if (declaration->storage_class == STORAGE_CLASS_NONE
4076 && scope != global_scope) {
4077 declaration->storage_class = STORAGE_CLASS_AUTO;
4080 if (specifiers->alignment != 0) {
4081 /* TODO: add checks here */
4082 declaration->alignment = specifiers->alignment;
4085 construct_type_t *construct_type
4086 = parse_inner_declarator(declaration, may_be_abstract);
4087 type_t *const type = specifiers->type;
4088 declaration->type = construct_declarator_type(construct_type, type);
4090 parse_declaration_attributes(declaration);
4092 fix_declaration_type(declaration);
4094 if (construct_type != NULL) {
4095 obstack_free(&temp_obst, construct_type);
4101 static type_t *parse_abstract_declarator(type_t *base_type)
4103 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4105 type_t *result = construct_declarator_type(construct_type, base_type);
4106 if (construct_type != NULL) {
4107 obstack_free(&temp_obst, construct_type);
4113 static declaration_t *append_declaration(declaration_t* const declaration)
4115 if (last_declaration != NULL) {
4116 last_declaration->next = declaration;
4118 scope->declarations = declaration;
4120 last_declaration = declaration;
4125 * Check if the declaration of main is suspicious. main should be a
4126 * function with external linkage, returning int, taking either zero
4127 * arguments, two, or three arguments of appropriate types, ie.
4129 * int main([ int argc, char **argv [, char **env ] ]).
4131 * @param decl the declaration to check
4132 * @param type the function type of the declaration
4134 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4136 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4137 warningf(&decl->source_position,
4138 "'main' is normally a non-static function");
4140 if (skip_typeref(func_type->return_type) != type_int) {
4141 warningf(&decl->source_position,
4142 "return type of 'main' should be 'int', but is '%T'",
4143 func_type->return_type);
4145 const function_parameter_t *parm = func_type->parameters;
4147 type_t *const first_type = parm->type;
4148 if (!types_compatible(skip_typeref(first_type), type_int)) {
4149 warningf(&decl->source_position,
4150 "first argument of 'main' should be 'int', but is '%T'", first_type);
4154 type_t *const second_type = parm->type;
4155 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4156 warningf(&decl->source_position,
4157 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4161 type_t *const third_type = parm->type;
4162 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4163 warningf(&decl->source_position,
4164 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4168 goto warn_arg_count;
4172 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4178 * Check if a symbol is the equal to "main".
4180 static bool is_sym_main(const symbol_t *const sym)
4182 return strcmp(sym->string, "main") == 0;
4185 static declaration_t *internal_record_declaration(
4186 declaration_t *const declaration,
4187 const bool is_definition)
4189 const symbol_t *const symbol = declaration->symbol;
4190 const namespace_t namespc = (namespace_t)declaration->namespc;
4192 assert(symbol != NULL);
4193 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4195 type_t *const orig_type = declaration->type;
4196 type_t *const type = skip_typeref(orig_type);
4197 if (is_type_function(type) &&
4198 type->function.unspecified_parameters &&
4199 warning.strict_prototypes &&
4200 previous_declaration == NULL) {
4201 warningf(&declaration->source_position,
4202 "function declaration '%#T' is not a prototype",
4203 orig_type, declaration->symbol);
4206 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4207 check_type_of_main(declaration, &type->function);
4210 if (warning.nested_externs &&
4211 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4212 scope != global_scope) {
4213 warningf(&declaration->source_position,
4214 "nested extern declaration of '%#T'", declaration->type, symbol);
4217 assert(declaration != previous_declaration);
4218 if (previous_declaration != NULL
4219 && previous_declaration->parent_scope == scope) {
4220 /* can happen for K&R style declarations */
4221 if (previous_declaration->type == NULL) {
4222 previous_declaration->type = declaration->type;
4225 const type_t *prev_type = skip_typeref(previous_declaration->type);
4226 if (!types_compatible(type, prev_type)) {
4227 errorf(&declaration->source_position,
4228 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4229 orig_type, symbol, previous_declaration->type, symbol,
4230 &previous_declaration->source_position);
4232 unsigned old_storage_class = previous_declaration->storage_class;
4233 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4234 errorf(&declaration->source_position,
4235 "redeclaration of enum entry '%Y' (declared %P)",
4236 symbol, &previous_declaration->source_position);
4237 return previous_declaration;
4240 if (warning.redundant_decls &&
4242 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4243 !(previous_declaration->modifiers & DM_USED) &&
4244 !previous_declaration->used) {
4245 warningf(&previous_declaration->source_position,
4246 "unnecessary static forward declaration for '%#T'",
4247 previous_declaration->type, symbol);
4250 unsigned new_storage_class = declaration->storage_class;
4252 if (is_type_incomplete(prev_type)) {
4253 previous_declaration->type = type;
4257 /* pretend no storage class means extern for function
4258 * declarations (except if the previous declaration is neither
4259 * none nor extern) */
4260 if (is_type_function(type)) {
4261 if (prev_type->function.unspecified_parameters) {
4262 previous_declaration->type = type;
4266 switch (old_storage_class) {
4267 case STORAGE_CLASS_NONE:
4268 old_storage_class = STORAGE_CLASS_EXTERN;
4271 case STORAGE_CLASS_EXTERN:
4272 if (is_definition) {
4273 if (warning.missing_prototypes &&
4274 prev_type->function.unspecified_parameters &&
4275 !is_sym_main(symbol)) {
4276 warningf(&declaration->source_position,
4277 "no previous prototype for '%#T'",
4280 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4281 new_storage_class = STORAGE_CLASS_EXTERN;
4290 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4291 new_storage_class == STORAGE_CLASS_EXTERN) {
4292 warn_redundant_declaration:
4293 if (!is_definition &&
4294 warning.redundant_decls &&
4295 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4296 warningf(&declaration->source_position,
4297 "redundant declaration for '%Y' (declared %P)",
4298 symbol, &previous_declaration->source_position);
4300 } else if (current_function == NULL) {
4301 if (old_storage_class != STORAGE_CLASS_STATIC &&
4302 new_storage_class == STORAGE_CLASS_STATIC) {
4303 errorf(&declaration->source_position,
4304 "static declaration of '%Y' follows non-static declaration (declared %P)",
4305 symbol, &previous_declaration->source_position);
4306 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4307 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4308 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4310 goto warn_redundant_declaration;
4312 } else if (old_storage_class == new_storage_class) {
4313 errorf(&declaration->source_position,
4314 "redeclaration of '%Y' (declared %P)",
4315 symbol, &previous_declaration->source_position);
4317 errorf(&declaration->source_position,
4318 "redeclaration of '%Y' with different linkage (declared %P)",
4319 symbol, &previous_declaration->source_position);
4323 previous_declaration->modifiers |= declaration->modifiers;
4324 previous_declaration->is_inline |= declaration->is_inline;
4325 return previous_declaration;
4326 } else if (is_type_function(type)) {
4327 if (is_definition &&
4328 declaration->storage_class != STORAGE_CLASS_STATIC) {
4329 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4330 warningf(&declaration->source_position,
4331 "no previous prototype for '%#T'", orig_type, symbol);
4332 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4333 warningf(&declaration->source_position,
4334 "no previous declaration for '%#T'", orig_type,
4339 if (warning.missing_declarations &&
4340 scope == global_scope && (
4341 declaration->storage_class == STORAGE_CLASS_NONE ||
4342 declaration->storage_class == STORAGE_CLASS_THREAD
4344 warningf(&declaration->source_position,
4345 "no previous declaration for '%#T'", orig_type, symbol);
4349 assert(declaration->parent_scope == NULL);
4350 assert(scope != NULL);
4352 declaration->parent_scope = scope;
4354 environment_push(declaration);
4355 return append_declaration(declaration);
4358 static declaration_t *record_declaration(declaration_t *declaration)
4360 return internal_record_declaration(declaration, false);
4363 static declaration_t *record_definition(declaration_t *declaration)
4365 return internal_record_declaration(declaration, true);
4368 static void parser_error_multiple_definition(declaration_t *declaration,
4369 const source_position_t *source_position)
4371 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4372 declaration->symbol, &declaration->source_position);
4375 static bool is_declaration_specifier(const token_t *token,
4376 bool only_specifiers_qualifiers)
4378 switch(token->type) {
4383 return is_typedef_symbol(token->v.symbol);
4385 case T___extension__:
4387 return !only_specifiers_qualifiers;
4394 static void parse_init_declarator_rest(declaration_t *declaration)
4398 type_t *orig_type = declaration->type;
4399 type_t *type = skip_typeref(orig_type);
4401 if (declaration->init.initializer != NULL) {
4402 parser_error_multiple_definition(declaration, HERE);
4405 bool must_be_constant = false;
4406 if (declaration->storage_class == STORAGE_CLASS_STATIC
4407 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4408 || declaration->parent_scope == global_scope) {
4409 must_be_constant = true;
4412 parse_initializer_env_t env;
4413 env.type = orig_type;
4414 env.must_be_constant = must_be_constant;
4415 env.declaration = declaration;
4417 initializer_t *initializer = parse_initializer(&env);
4419 if (env.type != orig_type) {
4420 orig_type = env.type;
4421 type = skip_typeref(orig_type);
4422 declaration->type = env.type;
4425 if (is_type_function(type)) {
4426 errorf(&declaration->source_position,
4427 "initializers not allowed for function types at declator '%Y' (type '%T')",
4428 declaration->symbol, orig_type);
4430 declaration->init.initializer = initializer;
4434 /* parse rest of a declaration without any declarator */
4435 static void parse_anonymous_declaration_rest(
4436 const declaration_specifiers_t *specifiers,
4437 parsed_declaration_func finished_declaration)
4441 declaration_t *const declaration = allocate_declaration_zero();
4442 declaration->type = specifiers->type;
4443 declaration->declared_storage_class = specifiers->declared_storage_class;
4444 declaration->source_position = specifiers->source_position;
4445 declaration->modifiers = specifiers->modifiers;
4447 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4448 warningf(&declaration->source_position,
4449 "useless storage class in empty declaration");
4451 declaration->storage_class = STORAGE_CLASS_NONE;
4453 type_t *type = declaration->type;
4454 switch (type->kind) {
4455 case TYPE_COMPOUND_STRUCT:
4456 case TYPE_COMPOUND_UNION: {
4457 if (type->compound.declaration->symbol == NULL) {
4458 warningf(&declaration->source_position,
4459 "unnamed struct/union that defines no instances");
4468 warningf(&declaration->source_position, "empty declaration");
4472 finished_declaration(declaration);
4475 static void parse_declaration_rest(declaration_t *ndeclaration,
4476 const declaration_specifiers_t *specifiers,
4477 parsed_declaration_func finished_declaration)
4479 add_anchor_token(';');
4480 add_anchor_token('=');
4481 add_anchor_token(',');
4483 declaration_t *declaration = finished_declaration(ndeclaration);
4485 type_t *orig_type = declaration->type;
4486 type_t *type = skip_typeref(orig_type);
4488 if (type->kind != TYPE_FUNCTION &&
4489 declaration->is_inline &&
4490 is_type_valid(type)) {
4491 warningf(&declaration->source_position,
4492 "variable '%Y' declared 'inline'\n", declaration->symbol);
4495 if (token.type == '=') {
4496 parse_init_declarator_rest(declaration);
4499 if (token.type != ',')
4503 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4508 rem_anchor_token(';');
4509 rem_anchor_token('=');
4510 rem_anchor_token(',');
4513 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4515 symbol_t *symbol = declaration->symbol;
4516 if (symbol == NULL) {
4517 errorf(HERE, "anonymous declaration not valid as function parameter");
4520 namespace_t namespc = (namespace_t) declaration->namespc;
4521 if (namespc != NAMESPACE_NORMAL) {
4522 return record_declaration(declaration);
4525 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4526 if (previous_declaration == NULL ||
4527 previous_declaration->parent_scope != scope) {
4528 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4533 if (previous_declaration->type == NULL) {
4534 previous_declaration->type = declaration->type;
4535 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4536 previous_declaration->storage_class = declaration->storage_class;
4537 previous_declaration->parent_scope = scope;
4538 return previous_declaration;
4540 return record_declaration(declaration);
4544 static void parse_declaration(parsed_declaration_func finished_declaration)
4546 declaration_specifiers_t specifiers;
4547 memset(&specifiers, 0, sizeof(specifiers));
4548 parse_declaration_specifiers(&specifiers);
4550 if (token.type == ';') {
4551 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4553 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4554 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4558 static type_t *get_default_promoted_type(type_t *orig_type)
4560 type_t *result = orig_type;
4562 type_t *type = skip_typeref(orig_type);
4563 if (is_type_integer(type)) {
4564 result = promote_integer(type);
4565 } else if (type == type_float) {
4566 result = type_double;
4572 static void parse_kr_declaration_list(declaration_t *declaration)
4574 type_t *type = skip_typeref(declaration->type);
4575 if (!is_type_function(type))
4578 if (!type->function.kr_style_parameters)
4581 /* push function parameters */
4582 int top = environment_top();
4583 scope_t *last_scope = scope;
4584 set_scope(&declaration->scope);
4586 declaration_t *parameter = declaration->scope.declarations;
4587 for ( ; parameter != NULL; parameter = parameter->next) {
4588 assert(parameter->parent_scope == NULL);
4589 parameter->parent_scope = scope;
4590 environment_push(parameter);
4593 /* parse declaration list */
4594 while (is_declaration_specifier(&token, false)) {
4595 parse_declaration(finished_kr_declaration);
4598 /* pop function parameters */
4599 assert(scope == &declaration->scope);
4600 set_scope(last_scope);
4601 environment_pop_to(top);
4603 /* update function type */
4604 type_t *new_type = duplicate_type(type);
4606 function_parameter_t *parameters = NULL;
4607 function_parameter_t *last_parameter = NULL;
4609 declaration_t *parameter_declaration = declaration->scope.declarations;
4610 for( ; parameter_declaration != NULL;
4611 parameter_declaration = parameter_declaration->next) {
4612 type_t *parameter_type = parameter_declaration->type;
4613 if (parameter_type == NULL) {
4615 errorf(HERE, "no type specified for function parameter '%Y'",
4616 parameter_declaration->symbol);
4618 if (warning.implicit_int) {
4619 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4620 parameter_declaration->symbol);
4622 parameter_type = type_int;
4623 parameter_declaration->type = parameter_type;
4627 semantic_parameter(parameter_declaration);
4628 parameter_type = parameter_declaration->type;
4631 * we need the default promoted types for the function type
4633 parameter_type = get_default_promoted_type(parameter_type);
4635 function_parameter_t *function_parameter
4636 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4637 memset(function_parameter, 0, sizeof(function_parameter[0]));
4639 function_parameter->type = parameter_type;
4640 if (last_parameter != NULL) {
4641 last_parameter->next = function_parameter;
4643 parameters = function_parameter;
4645 last_parameter = function_parameter;
4648 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4650 new_type->function.parameters = parameters;
4651 new_type->function.unspecified_parameters = true;
4653 type = typehash_insert(new_type);
4654 if (type != new_type) {
4655 obstack_free(type_obst, new_type);
4658 declaration->type = type;
4661 static bool first_err = true;
4664 * When called with first_err set, prints the name of the current function,
4667 static void print_in_function(void)
4671 diagnosticf("%s: In function '%Y':\n",
4672 current_function->source_position.input_name,
4673 current_function->symbol);
4678 * Check if all labels are defined in the current function.
4679 * Check if all labels are used in the current function.
4681 static void check_labels(void)
4683 for (const goto_statement_t *goto_statement = goto_first;
4684 goto_statement != NULL;
4685 goto_statement = goto_statement->next) {
4686 declaration_t *label = goto_statement->label;
4689 if (label->source_position.input_name == NULL) {
4690 print_in_function();
4691 errorf(&goto_statement->base.source_position,
4692 "label '%Y' used but not defined", label->symbol);
4695 goto_first = goto_last = NULL;
4697 if (warning.unused_label) {
4698 for (const label_statement_t *label_statement = label_first;
4699 label_statement != NULL;
4700 label_statement = label_statement->next) {
4701 const declaration_t *label = label_statement->label;
4703 if (! label->used) {
4704 print_in_function();
4705 warningf(&label_statement->base.source_position,
4706 "label '%Y' defined but not used", label->symbol);
4710 label_first = label_last = NULL;
4714 * Check declarations of current_function for unused entities.
4716 static void check_declarations(void)
4718 if (warning.unused_parameter) {
4719 const scope_t *scope = ¤t_function->scope;
4721 if (is_sym_main(current_function->symbol)) {
4722 /* do not issue unused warnings for main */
4725 const declaration_t *parameter = scope->declarations;
4726 for (; parameter != NULL; parameter = parameter->next) {
4727 if (! parameter->used) {
4728 print_in_function();
4729 warningf(¶meter->source_position,
4730 "unused parameter '%Y'", parameter->symbol);
4734 if (warning.unused_variable) {
4738 static int determine_truth(expression_t const* const cond)
4741 !is_constant_expression(cond) ? 0 :
4742 fold_constant(cond) != 0 ? 1 :
4746 static bool noreturn_candidate;
4748 static void check_reachable(statement_t *const stmt)
4750 if (stmt->base.reachable)
4752 if (stmt->kind != STATEMENT_DO_WHILE)
4753 stmt->base.reachable = true;
4755 statement_t *last = stmt;
4757 switch (stmt->kind) {
4758 case STATEMENT_INVALID:
4759 case STATEMENT_EMPTY:
4760 case STATEMENT_DECLARATION:
4762 next = stmt->base.next;
4765 case STATEMENT_COMPOUND:
4766 next = stmt->compound.statements;
4769 case STATEMENT_RETURN:
4770 noreturn_candidate = false;
4773 case STATEMENT_IF: {
4774 if_statement_t const* const ifs = &stmt->ifs;
4775 int const val = determine_truth(ifs->condition);
4778 check_reachable(ifs->true_statement);
4783 if (ifs->false_statement != NULL) {
4784 check_reachable(ifs->false_statement);
4788 next = stmt->base.next;
4792 case STATEMENT_SWITCH: {
4793 switch_statement_t const *const switchs = &stmt->switchs;
4794 expression_t const *const expr = switchs->expression;
4796 if (is_constant_expression(expr)) {
4797 long const val = fold_constant(expr);
4798 case_label_statement_t * defaults = NULL;
4799 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4800 if (i->expression == NULL) {
4805 if (i->first_case <= val && val <= i->last_case) {
4806 check_reachable((statement_t*)i);
4811 if (defaults != NULL) {
4812 check_reachable((statement_t*)defaults);
4816 bool has_default = false;
4817 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4818 if (i->expression == NULL)
4821 check_reachable((statement_t*)i);
4828 next = stmt->base.next;
4832 case STATEMENT_EXPRESSION: {
4833 /* Check for noreturn function call */
4834 expression_t const *const expr = stmt->expression.expression;
4835 if (expr->kind == EXPR_CALL) {
4836 expression_t const *const func = expr->call.function;
4837 if (func->kind == EXPR_REFERENCE) {
4838 declaration_t const *const decl = func->reference.declaration;
4839 if (decl != NULL && decl->modifiers & DM_NORETURN) {
4845 next = stmt->base.next;
4849 case STATEMENT_CONTINUE: {
4850 statement_t *parent = stmt;
4852 parent = parent->base.parent;
4853 if (parent == NULL) /* continue not within loop */
4857 switch (parent->kind) {
4858 case STATEMENT_WHILE: goto continue_while;
4859 case STATEMENT_DO_WHILE: goto continue_do_while;
4860 case STATEMENT_FOR: goto continue_for;
4867 case STATEMENT_BREAK: {
4868 statement_t *parent = stmt;
4870 parent = parent->base.parent;
4871 if (parent == NULL) /* break not within loop/switch */
4874 switch (parent->kind) {
4875 case STATEMENT_SWITCH:
4876 case STATEMENT_WHILE:
4877 case STATEMENT_DO_WHILE:
4880 next = parent->base.next;
4881 goto found_break_parent;
4890 case STATEMENT_GOTO:
4891 next = stmt->gotos.label->init.statement;
4892 if (next == NULL) /* missing label */
4896 case STATEMENT_LABEL:
4897 next = stmt->label.statement;
4900 case STATEMENT_CASE_LABEL:
4901 next = stmt->case_label.statement;
4904 case STATEMENT_WHILE: {
4905 while_statement_t const *const whiles = &stmt->whiles;
4906 int const val = determine_truth(whiles->condition);
4909 check_reachable(whiles->body);
4914 next = stmt->base.next;
4918 case STATEMENT_DO_WHILE:
4919 next = stmt->do_while.body;
4922 case STATEMENT_FOR: {
4923 for_statement_t *const fors = &stmt->fors;
4925 if (fors->condition_reachable)
4927 fors->condition_reachable = true;
4929 expression_t const *const cond = fors->condition;
4931 cond == NULL ? 1 : determine_truth(cond);
4934 check_reachable(fors->body);
4939 next = stmt->base.next;
4943 case STATEMENT_MS_TRY:
4944 case STATEMENT_LEAVE:
4945 panic("unimplemented");
4948 while (next == NULL) {
4949 next = last->base.parent;
4951 noreturn_candidate = false;
4953 type_t *const type = current_function->type;
4954 assert(is_type_function(type));
4955 type_t *const ret = skip_typeref(type->function.return_type);
4956 if (warning.return_type &&
4957 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
4958 is_type_valid(ret) &&
4959 !is_sym_main(current_function->symbol)) {
4960 warningf(&stmt->base.source_position,
4961 "control reaches end of non-void function");
4966 switch (next->kind) {
4967 case STATEMENT_INVALID:
4968 case STATEMENT_EMPTY:
4969 case STATEMENT_DECLARATION:
4970 case STATEMENT_EXPRESSION:
4972 case STATEMENT_RETURN:
4973 case STATEMENT_CONTINUE:
4974 case STATEMENT_BREAK:
4975 case STATEMENT_GOTO:
4976 case STATEMENT_LEAVE:
4977 panic("invalid control flow in function");
4979 case STATEMENT_COMPOUND:
4981 case STATEMENT_SWITCH:
4982 case STATEMENT_LABEL:
4983 case STATEMENT_CASE_LABEL:
4985 next = next->base.next;
4988 case STATEMENT_WHILE: {
4990 if (next->base.reachable)
4992 next->base.reachable = true;
4994 while_statement_t const *const whiles = &next->whiles;
4995 int const val = determine_truth(whiles->condition);
4998 check_reachable(whiles->body);
5004 next = next->base.next;
5008 case STATEMENT_DO_WHILE: {
5010 if (next->base.reachable)
5012 next->base.reachable = true;
5014 do_while_statement_t const *const dw = &next->do_while;
5015 int const val = determine_truth(dw->condition);
5018 check_reachable(dw->body);
5024 next = next->base.next;
5028 case STATEMENT_FOR: {
5030 for_statement_t *const fors = &next->fors;
5032 fors->step_reachable = true;
5034 if (fors->condition_reachable)
5036 fors->condition_reachable = true;
5038 expression_t const *const cond = fors->condition;
5040 cond == NULL ? 1 : determine_truth(cond);
5043 check_reachable(fors->body);
5049 next = next->base.next;
5053 case STATEMENT_MS_TRY:
5054 panic("unimplemented");
5059 next = stmt->base.parent;
5061 warningf(&stmt->base.source_position,
5062 "control reaches end of non-void function");
5066 check_reachable(next);
5069 static void check_unreachable(statement_t const* const stmt)
5071 if (!stmt->base.reachable &&
5072 stmt->kind != STATEMENT_DO_WHILE &&
5073 stmt->kind != STATEMENT_FOR &&
5074 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5075 warningf(&stmt->base.source_position, "statement is unreachable");
5078 switch (stmt->kind) {
5079 case STATEMENT_INVALID:
5080 case STATEMENT_EMPTY:
5081 case STATEMENT_RETURN:
5082 case STATEMENT_DECLARATION:
5083 case STATEMENT_EXPRESSION:
5084 case STATEMENT_CONTINUE:
5085 case STATEMENT_BREAK:
5086 case STATEMENT_GOTO:
5088 case STATEMENT_LEAVE:
5091 case STATEMENT_COMPOUND:
5092 if (stmt->compound.statements)
5093 check_unreachable(stmt->compound.statements);
5097 check_unreachable(stmt->ifs.true_statement);
5098 if (stmt->ifs.false_statement != NULL)
5099 check_unreachable(stmt->ifs.false_statement);
5102 case STATEMENT_SWITCH:
5103 check_unreachable(stmt->switchs.body);
5106 case STATEMENT_LABEL:
5107 check_unreachable(stmt->label.statement);
5110 case STATEMENT_CASE_LABEL:
5111 check_unreachable(stmt->case_label.statement);
5114 case STATEMENT_WHILE:
5115 check_unreachable(stmt->whiles.body);
5118 case STATEMENT_DO_WHILE:
5119 check_unreachable(stmt->do_while.body);
5120 if (!stmt->base.reachable) {
5121 expression_t const *const cond = stmt->do_while.condition;
5122 if (determine_truth(cond) >= 0) {
5123 warningf(&cond->base.source_position,
5124 "condition of do-while-loop is unreachable");
5129 case STATEMENT_FOR: {
5130 for_statement_t const* const fors = &stmt->fors;
5132 // if init and step are unreachable, cond is unreachable, too
5133 if (!stmt->base.reachable && !fors->step_reachable) {
5134 warningf(&stmt->base.source_position, "statement is unreachable");
5136 if (!stmt->base.reachable && fors->initialisation != NULL) {
5137 warningf(&fors->initialisation->base.source_position,
5138 "initialisation of for-statement is unreachable");
5141 if (!fors->condition_reachable && fors->condition != NULL) {
5142 warningf(&fors->condition->base.source_position,
5143 "condition of for-statement is unreachable");
5146 if (!fors->step_reachable && fors->step != NULL) {
5147 warningf(&fors->step->base.source_position,
5148 "step of for-statement is unreachable");
5152 check_unreachable(stmt->fors.body);
5156 case STATEMENT_MS_TRY:
5157 panic("unimplemented");
5160 if (stmt->base.next)
5161 check_unreachable(stmt->base.next);
5164 static void parse_external_declaration(void)
5166 /* function-definitions and declarations both start with declaration
5168 declaration_specifiers_t specifiers;
5169 memset(&specifiers, 0, sizeof(specifiers));
5171 add_anchor_token(';');
5172 parse_declaration_specifiers(&specifiers);
5173 rem_anchor_token(';');
5175 /* must be a declaration */
5176 if (token.type == ';') {
5177 parse_anonymous_declaration_rest(&specifiers, append_declaration);
5181 add_anchor_token(',');
5182 add_anchor_token('=');
5183 rem_anchor_token(';');
5185 /* declarator is common to both function-definitions and declarations */
5186 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5188 rem_anchor_token(',');
5189 rem_anchor_token('=');
5190 rem_anchor_token(';');
5192 /* must be a declaration */
5193 switch (token.type) {
5196 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5200 parse_declaration_rest(ndeclaration, &specifiers, record_definition);
5204 /* must be a function definition */
5205 parse_kr_declaration_list(ndeclaration);
5207 if (token.type != '{') {
5208 parse_error_expected("while parsing function definition", '{', NULL);
5209 eat_until_matching_token(';');
5213 type_t *type = ndeclaration->type;
5215 /* note that we don't skip typerefs: the standard doesn't allow them here
5216 * (so we can't use is_type_function here) */
5217 if (type->kind != TYPE_FUNCTION) {
5218 if (is_type_valid(type)) {
5219 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5220 type, ndeclaration->symbol);
5226 /* § 6.7.5.3 (14) a function definition with () means no
5227 * parameters (and not unspecified parameters) */
5228 if (type->function.unspecified_parameters
5229 && type->function.parameters == NULL
5230 && !type->function.kr_style_parameters) {
5231 type_t *duplicate = duplicate_type(type);
5232 duplicate->function.unspecified_parameters = false;
5234 type = typehash_insert(duplicate);
5235 if (type != duplicate) {
5236 obstack_free(type_obst, duplicate);
5238 ndeclaration->type = type;
5241 declaration_t *const declaration = record_definition(ndeclaration);
5242 if (ndeclaration != declaration) {
5243 declaration->scope = ndeclaration->scope;
5245 type = skip_typeref(declaration->type);
5247 /* push function parameters and switch scope */
5248 int top = environment_top();
5249 scope_t *last_scope = scope;
5250 set_scope(&declaration->scope);
5252 declaration_t *parameter = declaration->scope.declarations;
5253 for( ; parameter != NULL; parameter = parameter->next) {
5254 if (parameter->parent_scope == &ndeclaration->scope) {
5255 parameter->parent_scope = scope;
5257 assert(parameter->parent_scope == NULL
5258 || parameter->parent_scope == scope);
5259 parameter->parent_scope = scope;
5260 if (parameter->symbol == NULL) {
5261 errorf(¶meter->source_position, "parameter name omitted");
5264 environment_push(parameter);
5267 if (declaration->init.statement != NULL) {
5268 parser_error_multiple_definition(declaration, HERE);
5271 /* parse function body */
5272 int label_stack_top = label_top();
5273 declaration_t *old_current_function = current_function;
5274 current_function = declaration;
5275 current_parent = NULL;
5277 statement_t *const body = parse_compound_statement(false);
5278 declaration->init.statement = body;
5281 check_declarations();
5282 if (warning.return_type ||
5283 warning.unreachable_code ||
5284 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5285 noreturn_candidate = true;
5286 check_reachable(body);
5287 if (warning.unreachable_code)
5288 check_unreachable(body);
5289 if (warning.missing_noreturn &&
5290 noreturn_candidate &&
5291 !(declaration->modifiers & DM_NORETURN)) {
5292 warningf(&body->base.source_position,
5293 "function '%#T' is candidate for attribute 'noreturn'",
5294 type, declaration->symbol);
5298 assert(current_parent == NULL);
5299 assert(current_function == declaration);
5300 current_function = old_current_function;
5301 label_pop_to(label_stack_top);
5304 assert(scope == &declaration->scope);
5305 set_scope(last_scope);
5306 environment_pop_to(top);
5309 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5310 source_position_t *source_position)
5312 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5314 type->bitfield.base_type = base_type;
5315 type->bitfield.size = size;
5320 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5323 declaration_t *iter = compound_declaration->scope.declarations;
5324 for( ; iter != NULL; iter = iter->next) {
5325 if (iter->namespc != NAMESPACE_NORMAL)
5328 if (iter->symbol == NULL) {
5329 type_t *type = skip_typeref(iter->type);
5330 if (is_type_compound(type)) {
5331 declaration_t *result
5332 = find_compound_entry(type->compound.declaration, symbol);
5339 if (iter->symbol == symbol) {
5347 static void parse_compound_declarators(declaration_t *struct_declaration,
5348 const declaration_specifiers_t *specifiers)
5350 declaration_t *last_declaration = struct_declaration->scope.declarations;
5351 if (last_declaration != NULL) {
5352 while(last_declaration->next != NULL) {
5353 last_declaration = last_declaration->next;
5358 declaration_t *declaration;
5360 if (token.type == ':') {
5361 source_position_t source_position = *HERE;
5364 type_t *base_type = specifiers->type;
5365 expression_t *size = parse_constant_expression();
5367 if (!is_type_integer(skip_typeref(base_type))) {
5368 errorf(HERE, "bitfield base type '%T' is not an integer type",
5372 type_t *type = make_bitfield_type(base_type, size, &source_position);
5374 declaration = allocate_declaration_zero();
5375 declaration->namespc = NAMESPACE_NORMAL;
5376 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5377 declaration->storage_class = STORAGE_CLASS_NONE;
5378 declaration->source_position = source_position;
5379 declaration->modifiers = specifiers->modifiers;
5380 declaration->type = type;
5382 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5384 type_t *orig_type = declaration->type;
5385 type_t *type = skip_typeref(orig_type);
5387 if (token.type == ':') {
5388 source_position_t source_position = *HERE;
5390 expression_t *size = parse_constant_expression();
5392 if (!is_type_integer(type)) {
5393 errorf(HERE, "bitfield base type '%T' is not an "
5394 "integer type", orig_type);
5397 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
5398 declaration->type = bitfield_type;
5400 /* TODO we ignore arrays for now... what is missing is a check
5401 * that they're at the end of the struct */
5402 if (is_type_incomplete(type) && !is_type_array(type)) {
5404 "compound member '%Y' has incomplete type '%T'",
5405 declaration->symbol, orig_type);
5406 } else if (is_type_function(type)) {
5407 errorf(HERE, "compound member '%Y' must not have function "
5408 "type '%T'", declaration->symbol, orig_type);
5413 /* make sure we don't define a symbol multiple times */
5414 symbol_t *symbol = declaration->symbol;
5415 if (symbol != NULL) {
5416 declaration_t *prev_decl
5417 = find_compound_entry(struct_declaration, symbol);
5419 if (prev_decl != NULL) {
5420 assert(prev_decl->symbol == symbol);
5421 errorf(&declaration->source_position,
5422 "multiple declarations of symbol '%Y' (declared %P)",
5423 symbol, &prev_decl->source_position);
5427 /* append declaration */
5428 if (last_declaration != NULL) {
5429 last_declaration->next = declaration;
5431 struct_declaration->scope.declarations = declaration;
5433 last_declaration = declaration;
5435 if (token.type != ',')
5445 static void parse_compound_type_entries(declaration_t *compound_declaration)
5448 add_anchor_token('}');
5450 while(token.type != '}' && token.type != T_EOF) {
5451 declaration_specifiers_t specifiers;
5452 memset(&specifiers, 0, sizeof(specifiers));
5453 parse_declaration_specifiers(&specifiers);
5455 parse_compound_declarators(compound_declaration, &specifiers);
5457 rem_anchor_token('}');
5459 if (token.type == T_EOF) {
5460 errorf(HERE, "EOF while parsing struct");
5465 static type_t *parse_typename(void)
5467 declaration_specifiers_t specifiers;
5468 memset(&specifiers, 0, sizeof(specifiers));
5469 parse_declaration_specifiers(&specifiers);
5470 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5471 /* TODO: improve error message, user does probably not know what a
5472 * storage class is...
5474 errorf(HERE, "typename may not have a storage class");
5477 type_t *result = parse_abstract_declarator(specifiers.type);
5485 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5486 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5487 expression_t *left);
5489 typedef struct expression_parser_function_t expression_parser_function_t;
5490 struct expression_parser_function_t {
5491 unsigned precedence;
5492 parse_expression_function parser;
5493 unsigned infix_precedence;
5494 parse_expression_infix_function infix_parser;
5497 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5500 * Prints an error message if an expression was expected but not read
5502 static expression_t *expected_expression_error(void)
5504 /* skip the error message if the error token was read */
5505 if (token.type != T_ERROR) {
5506 errorf(HERE, "expected expression, got token '%K'", &token);
5510 return create_invalid_expression();
5514 * Parse a string constant.
5516 static expression_t *parse_string_const(void)
5519 if (token.type == T_STRING_LITERAL) {
5520 string_t res = token.v.string;
5522 while (token.type == T_STRING_LITERAL) {
5523 res = concat_strings(&res, &token.v.string);
5526 if (token.type != T_WIDE_STRING_LITERAL) {
5527 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5528 /* note: that we use type_char_ptr here, which is already the
5529 * automatic converted type. revert_automatic_type_conversion
5530 * will construct the array type */
5531 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5532 cnst->string.value = res;
5536 wres = concat_string_wide_string(&res, &token.v.wide_string);
5538 wres = token.v.wide_string;
5543 switch (token.type) {
5544 case T_WIDE_STRING_LITERAL:
5545 wres = concat_wide_strings(&wres, &token.v.wide_string);
5548 case T_STRING_LITERAL:
5549 wres = concat_wide_string_string(&wres, &token.v.string);
5553 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5554 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5555 cnst->wide_string.value = wres;
5564 * Parse an integer constant.
5566 static expression_t *parse_int_const(void)
5568 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5569 cnst->base.source_position = *HERE;
5570 cnst->base.type = token.datatype;
5571 cnst->conste.v.int_value = token.v.intvalue;
5579 * Parse a character constant.
5581 static expression_t *parse_character_constant(void)
5583 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5585 cnst->base.source_position = *HERE;
5586 cnst->base.type = token.datatype;
5587 cnst->conste.v.character = token.v.string;
5589 if (cnst->conste.v.character.size != 1) {
5590 if (warning.multichar && (c_mode & _GNUC)) {
5592 warningf(HERE, "multi-character character constant");
5594 errorf(HERE, "more than 1 characters in character constant");
5603 * Parse a wide character constant.
5605 static expression_t *parse_wide_character_constant(void)
5607 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5609 cnst->base.source_position = *HERE;
5610 cnst->base.type = token.datatype;
5611 cnst->conste.v.wide_character = token.v.wide_string;
5613 if (cnst->conste.v.wide_character.size != 1) {
5614 if (warning.multichar && (c_mode & _GNUC)) {
5616 warningf(HERE, "multi-character character constant");
5618 errorf(HERE, "more than 1 characters in character constant");
5627 * Parse a float constant.
5629 static expression_t *parse_float_const(void)
5631 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5632 cnst->base.type = token.datatype;
5633 cnst->conste.v.float_value = token.v.floatvalue;
5640 static declaration_t *create_implicit_function(symbol_t *symbol,
5641 const source_position_t *source_position)
5643 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5644 ntype->function.return_type = type_int;
5645 ntype->function.unspecified_parameters = true;
5647 type_t *type = typehash_insert(ntype);
5648 if (type != ntype) {
5652 declaration_t *const declaration = allocate_declaration_zero();
5653 declaration->storage_class = STORAGE_CLASS_EXTERN;
5654 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5655 declaration->type = type;
5656 declaration->symbol = symbol;
5657 declaration->source_position = *source_position;
5659 bool strict_prototypes_old = warning.strict_prototypes;
5660 warning.strict_prototypes = false;
5661 record_declaration(declaration);
5662 warning.strict_prototypes = strict_prototypes_old;
5668 * Creates a return_type (func)(argument_type) function type if not
5671 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5672 type_t *argument_type2)
5674 function_parameter_t *parameter2
5675 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5676 memset(parameter2, 0, sizeof(parameter2[0]));
5677 parameter2->type = argument_type2;
5679 function_parameter_t *parameter1
5680 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5681 memset(parameter1, 0, sizeof(parameter1[0]));
5682 parameter1->type = argument_type1;
5683 parameter1->next = parameter2;
5685 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5686 type->function.return_type = return_type;
5687 type->function.parameters = parameter1;
5689 type_t *result = typehash_insert(type);
5690 if (result != type) {
5698 * Creates a return_type (func)(argument_type) function type if not
5701 * @param return_type the return type
5702 * @param argument_type the argument type
5704 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5706 function_parameter_t *parameter
5707 = obstack_alloc(type_obst, sizeof(parameter[0]));
5708 memset(parameter, 0, sizeof(parameter[0]));
5709 parameter->type = argument_type;
5711 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5712 type->function.return_type = return_type;
5713 type->function.parameters = parameter;
5715 type_t *result = typehash_insert(type);
5716 if (result != type) {
5723 static type_t *make_function_0_type(type_t *return_type)
5725 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5726 type->function.return_type = return_type;
5727 type->function.parameters = NULL;
5729 type_t *result = typehash_insert(type);
5730 if (result != type) {
5738 * Creates a function type for some function like builtins.
5740 * @param symbol the symbol describing the builtin
5742 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5744 switch(symbol->ID) {
5745 case T___builtin_alloca:
5746 return make_function_1_type(type_void_ptr, type_size_t);
5747 case T___builtin_huge_val:
5748 return make_function_0_type(type_double);
5749 case T___builtin_nan:
5750 return make_function_1_type(type_double, type_char_ptr);
5751 case T___builtin_nanf:
5752 return make_function_1_type(type_float, type_char_ptr);
5753 case T___builtin_nand:
5754 return make_function_1_type(type_long_double, type_char_ptr);
5755 case T___builtin_va_end:
5756 return make_function_1_type(type_void, type_valist);
5757 case T___builtin_expect:
5758 return make_function_2_type(type_long, type_long, type_long);
5760 internal_errorf(HERE, "not implemented builtin symbol found");
5765 * Performs automatic type cast as described in § 6.3.2.1.
5767 * @param orig_type the original type
5769 static type_t *automatic_type_conversion(type_t *orig_type)
5771 type_t *type = skip_typeref(orig_type);
5772 if (is_type_array(type)) {
5773 array_type_t *array_type = &type->array;
5774 type_t *element_type = array_type->element_type;
5775 unsigned qualifiers = array_type->base.qualifiers;
5777 return make_pointer_type(element_type, qualifiers);
5780 if (is_type_function(type)) {
5781 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5788 * reverts the automatic casts of array to pointer types and function
5789 * to function-pointer types as defined § 6.3.2.1
5791 type_t *revert_automatic_type_conversion(const expression_t *expression)
5793 switch (expression->kind) {
5794 case EXPR_REFERENCE: return expression->reference.declaration->type;
5795 case EXPR_SELECT: return expression->select.compound_entry->type;
5797 case EXPR_UNARY_DEREFERENCE: {
5798 const expression_t *const value = expression->unary.value;
5799 type_t *const type = skip_typeref(value->base.type);
5800 assert(is_type_pointer(type));
5801 return type->pointer.points_to;
5804 case EXPR_BUILTIN_SYMBOL:
5805 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5807 case EXPR_ARRAY_ACCESS: {
5808 const expression_t *array_ref = expression->array_access.array_ref;
5809 type_t *type_left = skip_typeref(array_ref->base.type);
5810 if (!is_type_valid(type_left))
5812 assert(is_type_pointer(type_left));
5813 return type_left->pointer.points_to;
5816 case EXPR_STRING_LITERAL: {
5817 size_t size = expression->string.value.size;
5818 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5821 case EXPR_WIDE_STRING_LITERAL: {
5822 size_t size = expression->wide_string.value.size;
5823 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5826 case EXPR_COMPOUND_LITERAL:
5827 return expression->compound_literal.type;
5832 return expression->base.type;
5835 static expression_t *parse_reference(void)
5837 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5839 reference_expression_t *ref = &expression->reference;
5840 symbol_t *const symbol = token.v.symbol;
5842 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5844 source_position_t source_position = token.source_position;
5847 if (declaration == NULL) {
5848 if (! strict_mode && token.type == '(') {
5849 /* an implicitly defined function */
5850 if (warning.implicit_function_declaration) {
5851 warningf(HERE, "implicit declaration of function '%Y'",
5855 declaration = create_implicit_function(symbol,
5858 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5859 return create_invalid_expression();
5863 type_t *type = declaration->type;
5865 /* we always do the auto-type conversions; the & and sizeof parser contains
5866 * code to revert this! */
5867 type = automatic_type_conversion(type);
5869 ref->declaration = declaration;
5870 ref->base.type = type;
5872 /* this declaration is used */
5873 declaration->used = true;
5875 /* check for deprecated functions */
5876 if (warning.deprecated_declarations &&
5877 declaration->modifiers & DM_DEPRECATED) {
5878 char const *const prefix = is_type_function(declaration->type) ?
5879 "function" : "variable";
5881 if (declaration->deprecated_string != NULL) {
5882 warningf(&source_position,
5883 "%s '%Y' is deprecated (declared %P): \"%s\"", prefix,
5884 declaration->symbol, &declaration->source_position,
5885 declaration->deprecated_string);
5887 warningf(&source_position,
5888 "%s '%Y' is deprecated (declared %P)", prefix,
5889 declaration->symbol, &declaration->source_position);
5896 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5900 /* TODO check if explicit cast is allowed and issue warnings/errors */
5903 static expression_t *parse_compound_literal(type_t *type)
5905 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5907 parse_initializer_env_t env;
5909 env.declaration = NULL;
5910 env.must_be_constant = false;
5911 initializer_t *initializer = parse_initializer(&env);
5914 expression->compound_literal.initializer = initializer;
5915 expression->compound_literal.type = type;
5916 expression->base.type = automatic_type_conversion(type);
5922 * Parse a cast expression.
5924 static expression_t *parse_cast(void)
5926 source_position_t source_position = token.source_position;
5928 type_t *type = parse_typename();
5930 /* matching add_anchor_token() is at call site */
5931 rem_anchor_token(')');
5934 if (token.type == '{') {
5935 return parse_compound_literal(type);
5938 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5939 cast->base.source_position = source_position;
5941 expression_t *value = parse_sub_expression(20);
5943 check_cast_allowed(value, type);
5945 cast->base.type = type;
5946 cast->unary.value = value;
5950 return create_invalid_expression();
5954 * Parse a statement expression.
5956 static expression_t *parse_statement_expression(void)
5958 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5960 statement_t *statement = parse_compound_statement(true);
5961 expression->statement.statement = statement;
5962 expression->base.source_position = statement->base.source_position;
5964 /* find last statement and use its type */
5965 type_t *type = type_void;
5966 const statement_t *stmt = statement->compound.statements;
5968 while (stmt->base.next != NULL)
5969 stmt = stmt->base.next;
5971 if (stmt->kind == STATEMENT_EXPRESSION) {
5972 type = stmt->expression.expression->base.type;
5975 warningf(&expression->base.source_position, "empty statement expression ({})");
5977 expression->base.type = type;
5983 return create_invalid_expression();
5987 * Parse a parenthesized expression.
5989 static expression_t *parse_parenthesized_expression(void)
5992 add_anchor_token(')');
5994 switch(token.type) {
5996 /* gcc extension: a statement expression */
5997 return parse_statement_expression();
6001 return parse_cast();
6003 if (is_typedef_symbol(token.v.symbol)) {
6004 return parse_cast();
6008 expression_t *result = parse_expression();
6009 rem_anchor_token(')');
6014 return create_invalid_expression();
6017 static expression_t *parse_function_keyword(void)
6022 if (current_function == NULL) {
6023 errorf(HERE, "'__func__' used outside of a function");
6026 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6027 expression->base.type = type_char_ptr;
6028 expression->funcname.kind = FUNCNAME_FUNCTION;
6033 static expression_t *parse_pretty_function_keyword(void)
6035 eat(T___PRETTY_FUNCTION__);
6037 if (current_function == NULL) {
6038 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6041 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6042 expression->base.type = type_char_ptr;
6043 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6048 static expression_t *parse_funcsig_keyword(void)
6052 if (current_function == NULL) {
6053 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6056 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6057 expression->base.type = type_char_ptr;
6058 expression->funcname.kind = FUNCNAME_FUNCSIG;
6063 static expression_t *parse_funcdname_keyword(void)
6065 eat(T___FUNCDNAME__);
6067 if (current_function == NULL) {
6068 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6071 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6072 expression->base.type = type_char_ptr;
6073 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6078 static designator_t *parse_designator(void)
6080 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6081 result->source_position = *HERE;
6083 if (token.type != T_IDENTIFIER) {
6084 parse_error_expected("while parsing member designator",
6085 T_IDENTIFIER, NULL);
6088 result->symbol = token.v.symbol;
6091 designator_t *last_designator = result;
6093 if (token.type == '.') {
6095 if (token.type != T_IDENTIFIER) {
6096 parse_error_expected("while parsing member designator",
6097 T_IDENTIFIER, NULL);
6100 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6101 designator->source_position = *HERE;
6102 designator->symbol = token.v.symbol;
6105 last_designator->next = designator;
6106 last_designator = designator;
6109 if (token.type == '[') {
6111 add_anchor_token(']');
6112 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6113 designator->source_position = *HERE;
6114 designator->array_index = parse_expression();
6115 rem_anchor_token(']');
6117 if (designator->array_index == NULL) {
6121 last_designator->next = designator;
6122 last_designator = designator;
6134 * Parse the __builtin_offsetof() expression.
6136 static expression_t *parse_offsetof(void)
6138 eat(T___builtin_offsetof);
6140 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6141 expression->base.type = type_size_t;
6144 add_anchor_token(',');
6145 type_t *type = parse_typename();
6146 rem_anchor_token(',');
6148 add_anchor_token(')');
6149 designator_t *designator = parse_designator();
6150 rem_anchor_token(')');
6153 expression->offsetofe.type = type;
6154 expression->offsetofe.designator = designator;
6157 memset(&path, 0, sizeof(path));
6158 path.top_type = type;
6159 path.path = NEW_ARR_F(type_path_entry_t, 0);
6161 descend_into_subtype(&path);
6163 if (!walk_designator(&path, designator, true)) {
6164 return create_invalid_expression();
6167 DEL_ARR_F(path.path);
6171 return create_invalid_expression();
6175 * Parses a _builtin_va_start() expression.
6177 static expression_t *parse_va_start(void)
6179 eat(T___builtin_va_start);
6181 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6184 add_anchor_token(',');
6185 expression->va_starte.ap = parse_assignment_expression();
6186 rem_anchor_token(',');
6188 expression_t *const expr = parse_assignment_expression();
6189 if (expr->kind == EXPR_REFERENCE) {
6190 declaration_t *const decl = expr->reference.declaration;
6192 return create_invalid_expression();
6193 if (decl->parent_scope == ¤t_function->scope &&
6194 decl->next == NULL) {
6195 expression->va_starte.parameter = decl;
6200 errorf(&expr->base.source_position,
6201 "second argument of 'va_start' must be last parameter of the current function");
6203 return create_invalid_expression();
6207 * Parses a _builtin_va_arg() expression.
6209 static expression_t *parse_va_arg(void)
6211 eat(T___builtin_va_arg);
6213 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6216 expression->va_arge.ap = parse_assignment_expression();
6218 expression->base.type = parse_typename();
6223 return create_invalid_expression();
6226 static expression_t *parse_builtin_symbol(void)
6228 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6230 symbol_t *symbol = token.v.symbol;
6232 expression->builtin_symbol.symbol = symbol;
6235 type_t *type = get_builtin_symbol_type(symbol);
6236 type = automatic_type_conversion(type);
6238 expression->base.type = type;
6243 * Parses a __builtin_constant() expression.
6245 static expression_t *parse_builtin_constant(void)
6247 eat(T___builtin_constant_p);
6249 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6252 add_anchor_token(')');
6253 expression->builtin_constant.value = parse_assignment_expression();
6254 rem_anchor_token(')');
6256 expression->base.type = type_int;
6260 return create_invalid_expression();
6264 * Parses a __builtin_prefetch() expression.
6266 static expression_t *parse_builtin_prefetch(void)
6268 eat(T___builtin_prefetch);
6270 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6273 add_anchor_token(')');
6274 expression->builtin_prefetch.adr = parse_assignment_expression();
6275 if (token.type == ',') {
6277 expression->builtin_prefetch.rw = parse_assignment_expression();
6279 if (token.type == ',') {
6281 expression->builtin_prefetch.locality = parse_assignment_expression();
6283 rem_anchor_token(')');
6285 expression->base.type = type_void;
6289 return create_invalid_expression();
6293 * Parses a __builtin_is_*() compare expression.
6295 static expression_t *parse_compare_builtin(void)
6297 expression_t *expression;
6299 switch(token.type) {
6300 case T___builtin_isgreater:
6301 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6303 case T___builtin_isgreaterequal:
6304 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6306 case T___builtin_isless:
6307 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6309 case T___builtin_islessequal:
6310 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6312 case T___builtin_islessgreater:
6313 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6315 case T___builtin_isunordered:
6316 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6319 internal_errorf(HERE, "invalid compare builtin found");
6322 expression->base.source_position = *HERE;
6326 expression->binary.left = parse_assignment_expression();
6328 expression->binary.right = parse_assignment_expression();
6331 type_t *const orig_type_left = expression->binary.left->base.type;
6332 type_t *const orig_type_right = expression->binary.right->base.type;
6334 type_t *const type_left = skip_typeref(orig_type_left);
6335 type_t *const type_right = skip_typeref(orig_type_right);
6336 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6337 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6338 type_error_incompatible("invalid operands in comparison",
6339 &expression->base.source_position, orig_type_left, orig_type_right);
6342 semantic_comparison(&expression->binary);
6347 return create_invalid_expression();
6352 * Parses a __builtin_expect() expression.
6354 static expression_t *parse_builtin_expect(void)
6356 eat(T___builtin_expect);
6358 expression_t *expression
6359 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6362 expression->binary.left = parse_assignment_expression();
6364 expression->binary.right = parse_constant_expression();
6367 expression->base.type = expression->binary.left->base.type;
6371 return create_invalid_expression();
6376 * Parses a MS assume() expression.
6378 static expression_t *parse_assume(void)
6382 expression_t *expression
6383 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6386 add_anchor_token(')');
6387 expression->unary.value = parse_assignment_expression();
6388 rem_anchor_token(')');
6391 expression->base.type = type_void;
6394 return create_invalid_expression();
6398 * Parse a microsoft __noop expression.
6400 static expression_t *parse_noop_expression(void)
6402 source_position_t source_position = *HERE;
6405 if (token.type == '(') {
6406 /* parse arguments */
6408 add_anchor_token(')');
6409 add_anchor_token(',');
6411 if (token.type != ')') {
6413 (void)parse_assignment_expression();
6414 if (token.type != ',')
6420 rem_anchor_token(',');
6421 rem_anchor_token(')');
6424 /* the result is a (int)0 */
6425 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6426 cnst->base.source_position = source_position;
6427 cnst->base.type = type_int;
6428 cnst->conste.v.int_value = 0;
6429 cnst->conste.is_ms_noop = true;
6434 return create_invalid_expression();
6438 * Parses a primary expression.
6440 static expression_t *parse_primary_expression(void)
6442 switch (token.type) {
6443 case T_INTEGER: return parse_int_const();
6444 case T_CHARACTER_CONSTANT: return parse_character_constant();
6445 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6446 case T_FLOATINGPOINT: return parse_float_const();
6447 case T_STRING_LITERAL:
6448 case T_WIDE_STRING_LITERAL: return parse_string_const();
6449 case T_IDENTIFIER: return parse_reference();
6450 case T___FUNCTION__:
6451 case T___func__: return parse_function_keyword();
6452 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6453 case T___FUNCSIG__: return parse_funcsig_keyword();
6454 case T___FUNCDNAME__: return parse_funcdname_keyword();
6455 case T___builtin_offsetof: return parse_offsetof();
6456 case T___builtin_va_start: return parse_va_start();
6457 case T___builtin_va_arg: return parse_va_arg();
6458 case T___builtin_expect:
6459 case T___builtin_alloca:
6460 case T___builtin_nan:
6461 case T___builtin_nand:
6462 case T___builtin_nanf:
6463 case T___builtin_huge_val:
6464 case T___builtin_va_end: return parse_builtin_symbol();
6465 case T___builtin_isgreater:
6466 case T___builtin_isgreaterequal:
6467 case T___builtin_isless:
6468 case T___builtin_islessequal:
6469 case T___builtin_islessgreater:
6470 case T___builtin_isunordered: return parse_compare_builtin();
6471 case T___builtin_constant_p: return parse_builtin_constant();
6472 case T___builtin_prefetch: return parse_builtin_prefetch();
6473 case T__assume: return parse_assume();
6475 case '(': return parse_parenthesized_expression();
6476 case T___noop: return parse_noop_expression();
6479 errorf(HERE, "unexpected token %K, expected an expression", &token);
6480 return create_invalid_expression();
6484 * Check if the expression has the character type and issue a warning then.
6486 static void check_for_char_index_type(const expression_t *expression)
6488 type_t *const type = expression->base.type;
6489 const type_t *const base_type = skip_typeref(type);
6491 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6492 warning.char_subscripts) {
6493 warningf(&expression->base.source_position,
6494 "array subscript has type '%T'", type);
6498 static expression_t *parse_array_expression(unsigned precedence,
6504 add_anchor_token(']');
6506 expression_t *inside = parse_expression();
6508 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6510 array_access_expression_t *array_access = &expression->array_access;
6512 type_t *const orig_type_left = left->base.type;
6513 type_t *const orig_type_inside = inside->base.type;
6515 type_t *const type_left = skip_typeref(orig_type_left);
6516 type_t *const type_inside = skip_typeref(orig_type_inside);
6518 type_t *return_type;
6519 if (is_type_pointer(type_left)) {
6520 return_type = type_left->pointer.points_to;
6521 array_access->array_ref = left;
6522 array_access->index = inside;
6523 check_for_char_index_type(inside);
6524 } else if (is_type_pointer(type_inside)) {
6525 return_type = type_inside->pointer.points_to;
6526 array_access->array_ref = inside;
6527 array_access->index = left;
6528 array_access->flipped = true;
6529 check_for_char_index_type(left);
6531 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6533 "array access on object with non-pointer types '%T', '%T'",
6534 orig_type_left, orig_type_inside);
6536 return_type = type_error_type;
6537 array_access->array_ref = create_invalid_expression();
6540 rem_anchor_token(']');
6541 if (token.type != ']') {
6542 parse_error_expected("Problem while parsing array access", ']', NULL);
6547 return_type = automatic_type_conversion(return_type);
6548 expression->base.type = return_type;
6553 static expression_t *parse_typeprop(expression_kind_t const kind,
6554 source_position_t const pos,
6555 unsigned const precedence)
6557 expression_t *tp_expression = allocate_expression_zero(kind);
6558 tp_expression->base.type = type_size_t;
6559 tp_expression->base.source_position = pos;
6561 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6563 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6565 add_anchor_token(')');
6566 type_t* const orig_type = parse_typename();
6567 tp_expression->typeprop.type = orig_type;
6569 type_t const* const type = skip_typeref(orig_type);
6570 char const* const wrong_type =
6571 is_type_incomplete(type) ? "incomplete" :
6572 type->kind == TYPE_FUNCTION ? "function designator" :
6573 type->kind == TYPE_BITFIELD ? "bitfield" :
6575 if (wrong_type != NULL) {
6576 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6577 what, wrong_type, type);
6580 rem_anchor_token(')');
6583 expression_t *expression = parse_sub_expression(precedence);
6585 type_t* const orig_type = revert_automatic_type_conversion(expression);
6586 expression->base.type = orig_type;
6588 type_t const* const type = skip_typeref(orig_type);
6589 char const* const wrong_type =
6590 is_type_incomplete(type) ? "incomplete" :
6591 type->kind == TYPE_FUNCTION ? "function designator" :
6592 type->kind == TYPE_BITFIELD ? "bitfield" :
6594 if (wrong_type != NULL) {
6595 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6598 tp_expression->typeprop.type = expression->base.type;
6599 tp_expression->typeprop.tp_expression = expression;
6602 return tp_expression;
6604 return create_invalid_expression();
6607 static expression_t *parse_sizeof(unsigned precedence)
6609 source_position_t pos = *HERE;
6611 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6614 static expression_t *parse_alignof(unsigned precedence)
6616 source_position_t pos = *HERE;
6618 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6621 static expression_t *parse_select_expression(unsigned precedence,
6622 expression_t *compound)
6625 assert(token.type == '.' || token.type == T_MINUSGREATER);
6627 bool is_pointer = (token.type == T_MINUSGREATER);
6630 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6631 select->select.compound = compound;
6633 if (token.type != T_IDENTIFIER) {
6634 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6637 symbol_t *symbol = token.v.symbol;
6638 select->select.symbol = symbol;
6641 type_t *const orig_type = compound->base.type;
6642 type_t *const type = skip_typeref(orig_type);
6644 type_t *type_left = type;
6646 if (!is_type_pointer(type)) {
6647 if (is_type_valid(type)) {
6648 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6650 return create_invalid_expression();
6652 type_left = type->pointer.points_to;
6654 type_left = skip_typeref(type_left);
6656 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6657 type_left->kind != TYPE_COMPOUND_UNION) {
6658 if (is_type_valid(type_left)) {
6659 errorf(HERE, "request for member '%Y' in something not a struct or "
6660 "union, but '%T'", symbol, type_left);
6662 return create_invalid_expression();
6665 declaration_t *const declaration = type_left->compound.declaration;
6667 if (!declaration->init.complete) {
6668 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6670 return create_invalid_expression();
6673 declaration_t *iter = find_compound_entry(declaration, symbol);
6675 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6676 return create_invalid_expression();
6679 /* we always do the auto-type conversions; the & and sizeof parser contains
6680 * code to revert this! */
6681 type_t *expression_type = automatic_type_conversion(iter->type);
6683 select->select.compound_entry = iter;
6684 select->base.type = expression_type;
6686 type_t *skipped = skip_typeref(iter->type);
6687 if (skipped->kind == TYPE_BITFIELD) {
6688 select->base.type = skipped->bitfield.base_type;
6694 static void check_call_argument(const function_parameter_t *parameter,
6695 call_argument_t *argument)
6697 type_t *expected_type = parameter->type;
6698 type_t *expected_type_skip = skip_typeref(expected_type);
6699 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6700 expression_t *arg_expr = argument->expression;
6702 /* handle transparent union gnu extension */
6703 if (is_type_union(expected_type_skip)
6704 && (expected_type_skip->base.modifiers
6705 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6706 declaration_t *union_decl = expected_type_skip->compound.declaration;
6708 declaration_t *declaration = union_decl->scope.declarations;
6709 type_t *best_type = NULL;
6710 for ( ; declaration != NULL; declaration = declaration->next) {
6711 type_t *decl_type = declaration->type;
6712 error = semantic_assign(decl_type, arg_expr);
6713 if (error == ASSIGN_ERROR_INCOMPATIBLE
6714 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6717 if (error == ASSIGN_SUCCESS) {
6718 best_type = decl_type;
6719 } else if (best_type == NULL) {
6720 best_type = decl_type;
6724 if (best_type != NULL) {
6725 expected_type = best_type;
6729 error = semantic_assign(expected_type, arg_expr);
6730 argument->expression = create_implicit_cast(argument->expression,
6733 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6734 report_assign_error(error, expected_type, arg_expr, "function call",
6735 &arg_expr->base.source_position);
6739 * Parse a call expression, ie. expression '( ... )'.
6741 * @param expression the function address
6743 static expression_t *parse_call_expression(unsigned precedence,
6744 expression_t *expression)
6747 expression_t *result = allocate_expression_zero(EXPR_CALL);
6748 result->base.source_position = expression->base.source_position;
6750 call_expression_t *call = &result->call;
6751 call->function = expression;
6753 type_t *const orig_type = expression->base.type;
6754 type_t *const type = skip_typeref(orig_type);
6756 function_type_t *function_type = NULL;
6757 if (is_type_pointer(type)) {
6758 type_t *const to_type = skip_typeref(type->pointer.points_to);
6760 if (is_type_function(to_type)) {
6761 function_type = &to_type->function;
6762 call->base.type = function_type->return_type;
6766 if (function_type == NULL && is_type_valid(type)) {
6767 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6770 /* parse arguments */
6772 add_anchor_token(')');
6773 add_anchor_token(',');
6775 if (token.type != ')') {
6776 call_argument_t *last_argument = NULL;
6779 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6781 argument->expression = parse_assignment_expression();
6782 if (last_argument == NULL) {
6783 call->arguments = argument;
6785 last_argument->next = argument;
6787 last_argument = argument;
6789 if (token.type != ',')
6794 rem_anchor_token(',');
6795 rem_anchor_token(')');
6798 if (function_type == NULL)
6801 function_parameter_t *parameter = function_type->parameters;
6802 call_argument_t *argument = call->arguments;
6803 if (!function_type->unspecified_parameters) {
6804 for( ; parameter != NULL && argument != NULL;
6805 parameter = parameter->next, argument = argument->next) {
6806 check_call_argument(parameter, argument);
6809 if (parameter != NULL) {
6810 errorf(HERE, "too few arguments to function '%E'", expression);
6811 } else if (argument != NULL && !function_type->variadic) {
6812 errorf(HERE, "too many arguments to function '%E'", expression);
6816 /* do default promotion */
6817 for( ; argument != NULL; argument = argument->next) {
6818 type_t *type = argument->expression->base.type;
6820 type = get_default_promoted_type(type);
6822 argument->expression
6823 = create_implicit_cast(argument->expression, type);
6826 check_format(&result->call);
6830 return create_invalid_expression();
6833 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6835 static bool same_compound_type(const type_t *type1, const type_t *type2)
6838 is_type_compound(type1) &&
6839 type1->kind == type2->kind &&
6840 type1->compound.declaration == type2->compound.declaration;
6844 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6846 * @param expression the conditional expression
6848 static expression_t *parse_conditional_expression(unsigned precedence,
6849 expression_t *expression)
6851 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6853 conditional_expression_t *conditional = &result->conditional;
6854 conditional->base.source_position = *HERE;
6855 conditional->condition = expression;
6858 add_anchor_token(':');
6861 type_t *const condition_type_orig = expression->base.type;
6862 type_t *const condition_type = skip_typeref(condition_type_orig);
6863 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6864 type_error("expected a scalar type in conditional condition",
6865 &expression->base.source_position, condition_type_orig);
6868 expression_t *true_expression = expression;
6869 bool gnu_cond = false;
6870 if ((c_mode & _GNUC) && token.type == ':') {
6873 true_expression = parse_expression();
6874 rem_anchor_token(':');
6876 expression_t *false_expression = parse_sub_expression(precedence);
6878 type_t *const orig_true_type = true_expression->base.type;
6879 type_t *const orig_false_type = false_expression->base.type;
6880 type_t *const true_type = skip_typeref(orig_true_type);
6881 type_t *const false_type = skip_typeref(orig_false_type);
6884 type_t *result_type;
6885 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6886 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6887 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6888 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6889 warningf(&conditional->base.source_position,
6890 "ISO C forbids conditional expression with only one void side");
6892 result_type = type_void;
6893 } else if (is_type_arithmetic(true_type)
6894 && is_type_arithmetic(false_type)) {
6895 result_type = semantic_arithmetic(true_type, false_type);
6897 true_expression = create_implicit_cast(true_expression, result_type);
6898 false_expression = create_implicit_cast(false_expression, result_type);
6900 conditional->true_expression = true_expression;
6901 conditional->false_expression = false_expression;
6902 conditional->base.type = result_type;
6903 } else if (same_compound_type(true_type, false_type)) {
6904 /* just take 1 of the 2 types */
6905 result_type = true_type;
6906 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6907 type_t *pointer_type;
6909 expression_t *other_expression;
6910 if (is_type_pointer(true_type) &&
6911 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6912 pointer_type = true_type;
6913 other_type = false_type;
6914 other_expression = false_expression;
6916 pointer_type = false_type;
6917 other_type = true_type;
6918 other_expression = true_expression;
6921 if (is_null_pointer_constant(other_expression)) {
6922 result_type = pointer_type;
6923 } else if (is_type_pointer(other_type)) {
6924 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6925 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6928 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6929 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6931 } else if (types_compatible(get_unqualified_type(to1),
6932 get_unqualified_type(to2))) {
6935 warningf(&conditional->base.source_position,
6936 "pointer types '%T' and '%T' in conditional expression are incompatible",
6937 true_type, false_type);
6941 type_t *const copy = duplicate_type(to);
6942 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6944 type_t *const type = typehash_insert(copy);
6948 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6949 } else if (is_type_integer(other_type)) {
6950 warningf(&conditional->base.source_position,
6951 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6952 result_type = pointer_type;
6954 type_error_incompatible("while parsing conditional",
6955 &expression->base.source_position, true_type, false_type);
6956 result_type = type_error_type;
6959 /* TODO: one pointer to void*, other some pointer */
6961 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6962 type_error_incompatible("while parsing conditional",
6963 &conditional->base.source_position, true_type,
6966 result_type = type_error_type;
6969 conditional->true_expression
6970 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
6971 conditional->false_expression
6972 = create_implicit_cast(false_expression, result_type);
6973 conditional->base.type = result_type;
6976 return create_invalid_expression();
6980 * Parse an extension expression.
6982 static expression_t *parse_extension(unsigned precedence)
6984 eat(T___extension__);
6986 /* TODO enable extensions */
6987 expression_t *expression = parse_sub_expression(precedence);
6988 /* TODO disable extensions */
6993 * Parse a __builtin_classify_type() expression.
6995 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6997 eat(T___builtin_classify_type);
6999 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7000 result->base.type = type_int;
7003 add_anchor_token(')');
7004 expression_t *expression = parse_sub_expression(precedence);
7005 rem_anchor_token(')');
7007 result->classify_type.type_expression = expression;
7011 return create_invalid_expression();
7014 static bool check_pointer_arithmetic(const source_position_t *source_position,
7015 type_t *pointer_type,
7016 type_t *orig_pointer_type)
7018 type_t *points_to = pointer_type->pointer.points_to;
7019 points_to = skip_typeref(points_to);
7021 if (is_type_incomplete(points_to)) {
7022 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7023 errorf(source_position,
7024 "arithmetic with pointer to incomplete type '%T' not allowed",
7027 } else if (warning.pointer_arith) {
7028 warningf(source_position,
7029 "pointer of type '%T' used in arithmetic",
7032 } else if (is_type_function(points_to)) {
7033 if (!(c_mode && _GNUC)) {
7034 errorf(source_position,
7035 "arithmetic with pointer to function type '%T' not allowed",
7038 } else if (warning.pointer_arith) {
7039 warningf(source_position,
7040 "pointer to a function '%T' used in arithmetic",
7047 static void semantic_incdec(unary_expression_t *expression)
7049 type_t *const orig_type = expression->value->base.type;
7050 type_t *const type = skip_typeref(orig_type);
7051 if (is_type_pointer(type)) {
7052 if (!check_pointer_arithmetic(&expression->base.source_position,
7056 } else if (!is_type_real(type) && is_type_valid(type)) {
7057 /* TODO: improve error message */
7058 errorf(&expression->base.source_position,
7059 "operation needs an arithmetic or pointer type");
7062 expression->base.type = orig_type;
7065 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7067 type_t *const orig_type = expression->value->base.type;
7068 type_t *const type = skip_typeref(orig_type);
7069 if (!is_type_arithmetic(type)) {
7070 if (is_type_valid(type)) {
7071 /* TODO: improve error message */
7072 errorf(&expression->base.source_position,
7073 "operation needs an arithmetic type");
7078 expression->base.type = orig_type;
7081 static void semantic_not(unary_expression_t *expression)
7083 type_t *const orig_type = expression->value->base.type;
7084 type_t *const type = skip_typeref(orig_type);
7085 if (!is_type_scalar(type) && is_type_valid(type)) {
7086 errorf(&expression->base.source_position,
7087 "operand of ! must be of scalar type");
7090 expression->base.type = type_int;
7093 static void semantic_unexpr_integer(unary_expression_t *expression)
7095 type_t *const orig_type = expression->value->base.type;
7096 type_t *const type = skip_typeref(orig_type);
7097 if (!is_type_integer(type)) {
7098 if (is_type_valid(type)) {
7099 errorf(&expression->base.source_position,
7100 "operand of ~ must be of integer type");
7105 expression->base.type = orig_type;
7108 static void semantic_dereference(unary_expression_t *expression)
7110 type_t *const orig_type = expression->value->base.type;
7111 type_t *const type = skip_typeref(orig_type);
7112 if (!is_type_pointer(type)) {
7113 if (is_type_valid(type)) {
7114 errorf(&expression->base.source_position,
7115 "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
7120 type_t *result_type = type->pointer.points_to;
7121 result_type = automatic_type_conversion(result_type);
7122 expression->base.type = result_type;
7125 static void set_address_taken(expression_t *expression, bool may_be_register)
7127 if (expression->kind != EXPR_REFERENCE)
7130 declaration_t *const declaration = expression->reference.declaration;
7131 /* happens for parse errors */
7132 if (declaration == NULL)
7135 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7136 errorf(&expression->base.source_position,
7137 "address of register variable '%Y' requested",
7138 declaration->symbol);
7140 declaration->address_taken = 1;
7145 * Check the semantic of the address taken expression.
7147 static void semantic_take_addr(unary_expression_t *expression)
7149 expression_t *value = expression->value;
7150 value->base.type = revert_automatic_type_conversion(value);
7152 type_t *orig_type = value->base.type;
7153 if (!is_type_valid(orig_type))
7156 set_address_taken(value, false);
7158 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7161 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7162 static expression_t *parse_##unexpression_type(unsigned precedence) \
7164 expression_t *unary_expression \
7165 = allocate_expression_zero(unexpression_type); \
7166 unary_expression->base.source_position = *HERE; \
7168 unary_expression->unary.value = parse_sub_expression(precedence); \
7170 sfunc(&unary_expression->unary); \
7172 return unary_expression; \
7175 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7176 semantic_unexpr_arithmetic)
7177 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7178 semantic_unexpr_arithmetic)
7179 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7181 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7182 semantic_dereference)
7183 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7185 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7186 semantic_unexpr_integer)
7187 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7189 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7192 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7194 static expression_t *parse_##unexpression_type(unsigned precedence, \
7195 expression_t *left) \
7197 (void) precedence; \
7199 expression_t *unary_expression \
7200 = allocate_expression_zero(unexpression_type); \
7201 unary_expression->base.source_position = *HERE; \
7203 unary_expression->unary.value = left; \
7205 sfunc(&unary_expression->unary); \
7207 return unary_expression; \
7210 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7211 EXPR_UNARY_POSTFIX_INCREMENT,
7213 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7214 EXPR_UNARY_POSTFIX_DECREMENT,
7217 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7219 /* TODO: handle complex + imaginary types */
7221 /* § 6.3.1.8 Usual arithmetic conversions */
7222 if (type_left == type_long_double || type_right == type_long_double) {
7223 return type_long_double;
7224 } else if (type_left == type_double || type_right == type_double) {
7226 } else if (type_left == type_float || type_right == type_float) {
7230 type_left = promote_integer(type_left);
7231 type_right = promote_integer(type_right);
7233 if (type_left == type_right)
7236 bool const signed_left = is_type_signed(type_left);
7237 bool const signed_right = is_type_signed(type_right);
7238 int const rank_left = get_rank(type_left);
7239 int const rank_right = get_rank(type_right);
7241 if (signed_left == signed_right)
7242 return rank_left >= rank_right ? type_left : type_right;
7251 u_rank = rank_right;
7252 u_type = type_right;
7254 s_rank = rank_right;
7255 s_type = type_right;
7260 if (u_rank >= s_rank)
7263 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7265 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7266 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7270 case ATOMIC_TYPE_INT: return type_unsigned_int;
7271 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7272 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7274 default: panic("invalid atomic type");
7279 * Check the semantic restrictions for a binary expression.
7281 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7283 expression_t *const left = expression->left;
7284 expression_t *const right = expression->right;
7285 type_t *const orig_type_left = left->base.type;
7286 type_t *const orig_type_right = right->base.type;
7287 type_t *const type_left = skip_typeref(orig_type_left);
7288 type_t *const type_right = skip_typeref(orig_type_right);
7290 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7291 /* TODO: improve error message */
7292 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7293 errorf(&expression->base.source_position,
7294 "operation needs arithmetic types");
7299 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7300 expression->left = create_implicit_cast(left, arithmetic_type);
7301 expression->right = create_implicit_cast(right, arithmetic_type);
7302 expression->base.type = arithmetic_type;
7305 static void semantic_shift_op(binary_expression_t *expression)
7307 expression_t *const left = expression->left;
7308 expression_t *const right = expression->right;
7309 type_t *const orig_type_left = left->base.type;
7310 type_t *const orig_type_right = right->base.type;
7311 type_t * type_left = skip_typeref(orig_type_left);
7312 type_t * type_right = skip_typeref(orig_type_right);
7314 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7315 /* TODO: improve error message */
7316 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7317 errorf(&expression->base.source_position,
7318 "operands of shift operation must have integer types");
7323 type_left = promote_integer(type_left);
7324 type_right = promote_integer(type_right);
7326 expression->left = create_implicit_cast(left, type_left);
7327 expression->right = create_implicit_cast(right, type_right);
7328 expression->base.type = type_left;
7331 static void semantic_add(binary_expression_t *expression)
7333 expression_t *const left = expression->left;
7334 expression_t *const right = expression->right;
7335 type_t *const orig_type_left = left->base.type;
7336 type_t *const orig_type_right = right->base.type;
7337 type_t *const type_left = skip_typeref(orig_type_left);
7338 type_t *const type_right = skip_typeref(orig_type_right);
7341 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7342 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7343 expression->left = create_implicit_cast(left, arithmetic_type);
7344 expression->right = create_implicit_cast(right, arithmetic_type);
7345 expression->base.type = arithmetic_type;
7347 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7348 check_pointer_arithmetic(&expression->base.source_position,
7349 type_left, orig_type_left);
7350 expression->base.type = type_left;
7351 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7352 check_pointer_arithmetic(&expression->base.source_position,
7353 type_right, orig_type_right);
7354 expression->base.type = type_right;
7355 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7356 errorf(&expression->base.source_position,
7357 "invalid operands to binary + ('%T', '%T')",
7358 orig_type_left, orig_type_right);
7362 static void semantic_sub(binary_expression_t *expression)
7364 expression_t *const left = expression->left;
7365 expression_t *const right = expression->right;
7366 type_t *const orig_type_left = left->base.type;
7367 type_t *const orig_type_right = right->base.type;
7368 type_t *const type_left = skip_typeref(orig_type_left);
7369 type_t *const type_right = skip_typeref(orig_type_right);
7370 source_position_t const *const pos = &expression->base.source_position;
7373 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7374 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7375 expression->left = create_implicit_cast(left, arithmetic_type);
7376 expression->right = create_implicit_cast(right, arithmetic_type);
7377 expression->base.type = arithmetic_type;
7379 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7380 check_pointer_arithmetic(&expression->base.source_position,
7381 type_left, orig_type_left);
7382 expression->base.type = type_left;
7383 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7384 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7385 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7386 if (!types_compatible(unqual_left, unqual_right)) {
7388 "subtracting pointers to incompatible types '%T' and '%T'",
7389 orig_type_left, orig_type_right);
7390 } else if (!is_type_object(unqual_left)) {
7391 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7392 warningf(pos, "subtracting pointers to void");
7394 errorf(pos, "subtracting pointers to non-object types '%T'",
7398 expression->base.type = type_ptrdiff_t;
7399 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7400 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7401 orig_type_left, orig_type_right);
7406 * Check the semantics of comparison expressions.
7408 * @param expression The expression to check.
7410 static void semantic_comparison(binary_expression_t *expression)
7412 expression_t *left = expression->left;
7413 expression_t *right = expression->right;
7414 type_t *orig_type_left = left->base.type;
7415 type_t *orig_type_right = right->base.type;
7417 type_t *type_left = skip_typeref(orig_type_left);
7418 type_t *type_right = skip_typeref(orig_type_right);
7420 /* TODO non-arithmetic types */
7421 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7422 /* test for signed vs unsigned compares */
7423 if (warning.sign_compare &&
7424 (expression->base.kind != EXPR_BINARY_EQUAL &&
7425 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7426 (is_type_signed(type_left) != is_type_signed(type_right))) {
7428 /* check if 1 of the operands is a constant, in this case we just
7429 * check wether we can safely represent the resulting constant in
7430 * the type of the other operand. */
7431 expression_t *const_expr = NULL;
7432 expression_t *other_expr = NULL;
7434 if (is_constant_expression(left)) {
7437 } else if (is_constant_expression(right)) {
7442 if (const_expr != NULL) {
7443 type_t *other_type = skip_typeref(other_expr->base.type);
7444 long val = fold_constant(const_expr);
7445 /* TODO: check if val can be represented by other_type */
7449 warningf(&expression->base.source_position,
7450 "comparison between signed and unsigned");
7452 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7453 expression->left = create_implicit_cast(left, arithmetic_type);
7454 expression->right = create_implicit_cast(right, arithmetic_type);
7455 expression->base.type = arithmetic_type;
7456 if (warning.float_equal &&
7457 (expression->base.kind == EXPR_BINARY_EQUAL ||
7458 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7459 is_type_float(arithmetic_type)) {
7460 warningf(&expression->base.source_position,
7461 "comparing floating point with == or != is unsafe");
7463 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7464 /* TODO check compatibility */
7465 } else if (is_type_pointer(type_left)) {
7466 expression->right = create_implicit_cast(right, type_left);
7467 } else if (is_type_pointer(type_right)) {
7468 expression->left = create_implicit_cast(left, type_right);
7469 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7470 type_error_incompatible("invalid operands in comparison",
7471 &expression->base.source_position,
7472 type_left, type_right);
7474 expression->base.type = type_int;
7478 * Checks if a compound type has constant fields.
7480 static bool has_const_fields(const compound_type_t *type)
7482 const scope_t *scope = &type->declaration->scope;
7483 const declaration_t *declaration = scope->declarations;
7485 for (; declaration != NULL; declaration = declaration->next) {
7486 if (declaration->namespc != NAMESPACE_NORMAL)
7489 const type_t *decl_type = skip_typeref(declaration->type);
7490 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7497 static bool is_lvalue(const expression_t *expression)
7499 switch (expression->kind) {
7500 case EXPR_REFERENCE:
7501 case EXPR_ARRAY_ACCESS:
7503 case EXPR_UNARY_DEREFERENCE:
7511 static bool is_valid_assignment_lhs(expression_t const* const left)
7513 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7514 type_t *const type_left = skip_typeref(orig_type_left);
7516 if (!is_lvalue(left)) {
7517 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7522 if (is_type_array(type_left)) {
7523 errorf(HERE, "cannot assign to arrays ('%E')", left);
7526 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7527 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7531 if (is_type_incomplete(type_left)) {
7532 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7533 left, orig_type_left);
7536 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7537 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7538 left, orig_type_left);
7545 static void semantic_arithmetic_assign(binary_expression_t *expression)
7547 expression_t *left = expression->left;
7548 expression_t *right = expression->right;
7549 type_t *orig_type_left = left->base.type;
7550 type_t *orig_type_right = right->base.type;
7552 if (!is_valid_assignment_lhs(left))
7555 type_t *type_left = skip_typeref(orig_type_left);
7556 type_t *type_right = skip_typeref(orig_type_right);
7558 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7559 /* TODO: improve error message */
7560 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7561 errorf(&expression->base.source_position,
7562 "operation needs arithmetic types");
7567 /* combined instructions are tricky. We can't create an implicit cast on
7568 * the left side, because we need the uncasted form for the store.
7569 * The ast2firm pass has to know that left_type must be right_type
7570 * for the arithmetic operation and create a cast by itself */
7571 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7572 expression->right = create_implicit_cast(right, arithmetic_type);
7573 expression->base.type = type_left;
7576 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7578 expression_t *const left = expression->left;
7579 expression_t *const right = expression->right;
7580 type_t *const orig_type_left = left->base.type;
7581 type_t *const orig_type_right = right->base.type;
7582 type_t *const type_left = skip_typeref(orig_type_left);
7583 type_t *const type_right = skip_typeref(orig_type_right);
7585 if (!is_valid_assignment_lhs(left))
7588 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7589 /* combined instructions are tricky. We can't create an implicit cast on
7590 * the left side, because we need the uncasted form for the store.
7591 * The ast2firm pass has to know that left_type must be right_type
7592 * for the arithmetic operation and create a cast by itself */
7593 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7594 expression->right = create_implicit_cast(right, arithmetic_type);
7595 expression->base.type = type_left;
7596 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7597 check_pointer_arithmetic(&expression->base.source_position,
7598 type_left, orig_type_left);
7599 expression->base.type = type_left;
7600 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7601 errorf(&expression->base.source_position,
7602 "incompatible types '%T' and '%T' in assignment",
7603 orig_type_left, orig_type_right);
7608 * Check the semantic restrictions of a logical expression.
7610 static void semantic_logical_op(binary_expression_t *expression)
7612 expression_t *const left = expression->left;
7613 expression_t *const right = expression->right;
7614 type_t *const orig_type_left = left->base.type;
7615 type_t *const orig_type_right = right->base.type;
7616 type_t *const type_left = skip_typeref(orig_type_left);
7617 type_t *const type_right = skip_typeref(orig_type_right);
7619 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
7620 /* TODO: improve error message */
7621 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7622 errorf(&expression->base.source_position,
7623 "operation needs scalar types");
7628 expression->base.type = type_int;
7632 * Check the semantic restrictions of a binary assign expression.
7634 static void semantic_binexpr_assign(binary_expression_t *expression)
7636 expression_t *left = expression->left;
7637 type_t *orig_type_left = left->base.type;
7639 type_t *type_left = revert_automatic_type_conversion(left);
7640 type_left = skip_typeref(orig_type_left);
7642 if (!is_valid_assignment_lhs(left))
7645 assign_error_t error = semantic_assign(orig_type_left, expression->right);
7646 report_assign_error(error, orig_type_left, expression->right,
7647 "assignment", &left->base.source_position);
7648 expression->right = create_implicit_cast(expression->right, orig_type_left);
7649 expression->base.type = orig_type_left;
7653 * Determine if the outermost operation (or parts thereof) of the given
7654 * expression has no effect in order to generate a warning about this fact.
7655 * Therefore in some cases this only examines some of the operands of the
7656 * expression (see comments in the function and examples below).
7658 * f() + 23; // warning, because + has no effect
7659 * x || f(); // no warning, because x controls execution of f()
7660 * x ? y : f(); // warning, because y has no effect
7661 * (void)x; // no warning to be able to suppress the warning
7662 * This function can NOT be used for an "expression has definitely no effect"-
7664 static bool expression_has_effect(const expression_t *const expr)
7666 switch (expr->kind) {
7667 case EXPR_UNKNOWN: break;
7668 case EXPR_INVALID: return true; /* do NOT warn */
7669 case EXPR_REFERENCE: return false;
7670 /* suppress the warning for microsoft __noop operations */
7671 case EXPR_CONST: return expr->conste.is_ms_noop;
7672 case EXPR_CHARACTER_CONSTANT: return false;
7673 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
7674 case EXPR_STRING_LITERAL: return false;
7675 case EXPR_WIDE_STRING_LITERAL: return false;
7678 const call_expression_t *const call = &expr->call;
7679 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7682 switch (call->function->builtin_symbol.symbol->ID) {
7683 case T___builtin_va_end: return true;
7684 default: return false;
7688 /* Generate the warning if either the left or right hand side of a
7689 * conditional expression has no effect */
7690 case EXPR_CONDITIONAL: {
7691 const conditional_expression_t *const cond = &expr->conditional;
7693 expression_has_effect(cond->true_expression) &&
7694 expression_has_effect(cond->false_expression);
7697 case EXPR_SELECT: return false;
7698 case EXPR_ARRAY_ACCESS: return false;
7699 case EXPR_SIZEOF: return false;
7700 case EXPR_CLASSIFY_TYPE: return false;
7701 case EXPR_ALIGNOF: return false;
7703 case EXPR_FUNCNAME: return false;
7704 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
7705 case EXPR_BUILTIN_CONSTANT_P: return false;
7706 case EXPR_BUILTIN_PREFETCH: return true;
7707 case EXPR_OFFSETOF: return false;
7708 case EXPR_VA_START: return true;
7709 case EXPR_VA_ARG: return true;
7710 case EXPR_STATEMENT: return true; // TODO
7711 case EXPR_COMPOUND_LITERAL: return false;
7713 case EXPR_UNARY_NEGATE: return false;
7714 case EXPR_UNARY_PLUS: return false;
7715 case EXPR_UNARY_BITWISE_NEGATE: return false;
7716 case EXPR_UNARY_NOT: return false;
7717 case EXPR_UNARY_DEREFERENCE: return false;
7718 case EXPR_UNARY_TAKE_ADDRESS: return false;
7719 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7720 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7721 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7722 case EXPR_UNARY_PREFIX_DECREMENT: return true;
7724 /* Treat void casts as if they have an effect in order to being able to
7725 * suppress the warning */
7726 case EXPR_UNARY_CAST: {
7727 type_t *const type = skip_typeref(expr->base.type);
7728 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7731 case EXPR_UNARY_CAST_IMPLICIT: return true;
7732 case EXPR_UNARY_ASSUME: return true;
7734 case EXPR_BINARY_ADD: return false;
7735 case EXPR_BINARY_SUB: return false;
7736 case EXPR_BINARY_MUL: return false;
7737 case EXPR_BINARY_DIV: return false;
7738 case EXPR_BINARY_MOD: return false;
7739 case EXPR_BINARY_EQUAL: return false;
7740 case EXPR_BINARY_NOTEQUAL: return false;
7741 case EXPR_BINARY_LESS: return false;
7742 case EXPR_BINARY_LESSEQUAL: return false;
7743 case EXPR_BINARY_GREATER: return false;
7744 case EXPR_BINARY_GREATEREQUAL: return false;
7745 case EXPR_BINARY_BITWISE_AND: return false;
7746 case EXPR_BINARY_BITWISE_OR: return false;
7747 case EXPR_BINARY_BITWISE_XOR: return false;
7748 case EXPR_BINARY_SHIFTLEFT: return false;
7749 case EXPR_BINARY_SHIFTRIGHT: return false;
7750 case EXPR_BINARY_ASSIGN: return true;
7751 case EXPR_BINARY_MUL_ASSIGN: return true;
7752 case EXPR_BINARY_DIV_ASSIGN: return true;
7753 case EXPR_BINARY_MOD_ASSIGN: return true;
7754 case EXPR_BINARY_ADD_ASSIGN: return true;
7755 case EXPR_BINARY_SUB_ASSIGN: return true;
7756 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7757 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7758 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7759 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7760 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7762 /* Only examine the right hand side of && and ||, because the left hand
7763 * side already has the effect of controlling the execution of the right
7765 case EXPR_BINARY_LOGICAL_AND:
7766 case EXPR_BINARY_LOGICAL_OR:
7767 /* Only examine the right hand side of a comma expression, because the left
7768 * hand side has a separate warning */
7769 case EXPR_BINARY_COMMA:
7770 return expression_has_effect(expr->binary.right);
7772 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7773 case EXPR_BINARY_ISGREATER: return false;
7774 case EXPR_BINARY_ISGREATEREQUAL: return false;
7775 case EXPR_BINARY_ISLESS: return false;
7776 case EXPR_BINARY_ISLESSEQUAL: return false;
7777 case EXPR_BINARY_ISLESSGREATER: return false;
7778 case EXPR_BINARY_ISUNORDERED: return false;
7781 internal_errorf(HERE, "unexpected expression");
7784 static void semantic_comma(binary_expression_t *expression)
7786 if (warning.unused_value) {
7787 const expression_t *const left = expression->left;
7788 if (!expression_has_effect(left)) {
7789 warningf(&left->base.source_position,
7790 "left-hand operand of comma expression has no effect");
7793 expression->base.type = expression->right->base.type;
7796 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7797 static expression_t *parse_##binexpression_type(unsigned precedence, \
7798 expression_t *left) \
7800 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7801 binexpr->base.source_position = *HERE; \
7802 binexpr->binary.left = left; \
7805 expression_t *right = parse_sub_expression(precedence + lr); \
7807 binexpr->binary.right = right; \
7808 sfunc(&binexpr->binary); \
7813 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7814 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7815 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7816 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7817 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7818 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7819 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7820 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7821 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7823 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7824 semantic_comparison, 1)
7825 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7826 semantic_comparison, 1)
7827 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7828 semantic_comparison, 1)
7829 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7830 semantic_comparison, 1)
7832 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7833 semantic_binexpr_arithmetic, 1)
7834 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7835 semantic_binexpr_arithmetic, 1)
7836 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7837 semantic_binexpr_arithmetic, 1)
7838 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7839 semantic_logical_op, 1)
7840 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7841 semantic_logical_op, 1)
7842 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7843 semantic_shift_op, 1)
7844 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7845 semantic_shift_op, 1)
7846 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7847 semantic_arithmetic_addsubb_assign, 0)
7848 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7849 semantic_arithmetic_addsubb_assign, 0)
7850 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7851 semantic_arithmetic_assign, 0)
7852 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7853 semantic_arithmetic_assign, 0)
7854 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7855 semantic_arithmetic_assign, 0)
7856 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7857 semantic_arithmetic_assign, 0)
7858 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7859 semantic_arithmetic_assign, 0)
7860 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7861 semantic_arithmetic_assign, 0)
7862 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7863 semantic_arithmetic_assign, 0)
7864 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7865 semantic_arithmetic_assign, 0)
7867 static expression_t *parse_sub_expression(unsigned precedence)
7869 if (token.type < 0) {
7870 return expected_expression_error();
7873 expression_parser_function_t *parser
7874 = &expression_parsers[token.type];
7875 source_position_t source_position = token.source_position;
7878 if (parser->parser != NULL) {
7879 left = parser->parser(parser->precedence);
7881 left = parse_primary_expression();
7883 assert(left != NULL);
7884 left->base.source_position = source_position;
7887 if (token.type < 0) {
7888 return expected_expression_error();
7891 parser = &expression_parsers[token.type];
7892 if (parser->infix_parser == NULL)
7894 if (parser->infix_precedence < precedence)
7897 left = parser->infix_parser(parser->infix_precedence, left);
7899 assert(left != NULL);
7900 assert(left->kind != EXPR_UNKNOWN);
7901 left->base.source_position = source_position;
7908 * Parse an expression.
7910 static expression_t *parse_expression(void)
7912 return parse_sub_expression(1);
7916 * Register a parser for a prefix-like operator with given precedence.
7918 * @param parser the parser function
7919 * @param token_type the token type of the prefix token
7920 * @param precedence the precedence of the operator
7922 static void register_expression_parser(parse_expression_function parser,
7923 int token_type, unsigned precedence)
7925 expression_parser_function_t *entry = &expression_parsers[token_type];
7927 if (entry->parser != NULL) {
7928 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7929 panic("trying to register multiple expression parsers for a token");
7931 entry->parser = parser;
7932 entry->precedence = precedence;
7936 * Register a parser for an infix operator with given precedence.
7938 * @param parser the parser function
7939 * @param token_type the token type of the infix operator
7940 * @param precedence the precedence of the operator
7942 static void register_infix_parser(parse_expression_infix_function parser,
7943 int token_type, unsigned precedence)
7945 expression_parser_function_t *entry = &expression_parsers[token_type];
7947 if (entry->infix_parser != NULL) {
7948 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7949 panic("trying to register multiple infix expression parsers for a "
7952 entry->infix_parser = parser;
7953 entry->infix_precedence = precedence;
7957 * Initialize the expression parsers.
7959 static void init_expression_parsers(void)
7961 memset(&expression_parsers, 0, sizeof(expression_parsers));
7963 register_infix_parser(parse_array_expression, '[', 30);
7964 register_infix_parser(parse_call_expression, '(', 30);
7965 register_infix_parser(parse_select_expression, '.', 30);
7966 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7967 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7969 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7972 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7973 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7974 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7975 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7976 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7977 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7978 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7979 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7980 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7981 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7982 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7983 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7984 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7985 T_EXCLAMATIONMARKEQUAL, 13);
7986 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7987 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7988 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7989 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7990 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7991 register_infix_parser(parse_conditional_expression, '?', 7);
7992 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7993 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7994 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7995 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7996 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7997 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7998 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7999 T_LESSLESSEQUAL, 2);
8000 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8001 T_GREATERGREATEREQUAL, 2);
8002 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8004 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8006 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8009 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8011 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8012 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8013 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8014 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8015 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8016 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8017 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8019 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8021 register_expression_parser(parse_sizeof, T_sizeof, 25);
8022 register_expression_parser(parse_alignof, T___alignof__, 25);
8023 register_expression_parser(parse_extension, T___extension__, 25);
8024 register_expression_parser(parse_builtin_classify_type,
8025 T___builtin_classify_type, 25);
8029 * Parse a asm statement arguments specification.
8031 static asm_argument_t *parse_asm_arguments(bool is_out)
8033 asm_argument_t *result = NULL;
8034 asm_argument_t *last = NULL;
8036 while (token.type == T_STRING_LITERAL || token.type == '[') {
8037 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8038 memset(argument, 0, sizeof(argument[0]));
8040 if (token.type == '[') {
8042 if (token.type != T_IDENTIFIER) {
8043 parse_error_expected("while parsing asm argument",
8044 T_IDENTIFIER, NULL);
8047 argument->symbol = token.v.symbol;
8052 argument->constraints = parse_string_literals();
8054 add_anchor_token(')');
8055 expression_t *expression = parse_expression();
8056 rem_anchor_token(')');
8058 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8059 * change size or type representation (e.g. int -> long is ok, but
8060 * int -> float is not) */
8061 if (expression->kind == EXPR_UNARY_CAST) {
8062 type_t *const type = expression->base.type;
8063 type_kind_t const kind = type->kind;
8064 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8067 if (kind == TYPE_ATOMIC) {
8068 atomic_type_kind_t const akind = type->atomic.akind;
8069 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8070 size = get_atomic_type_size(akind);
8072 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8073 size = get_atomic_type_size(get_intptr_kind());
8077 expression_t *const value = expression->unary.value;
8078 type_t *const value_type = value->base.type;
8079 type_kind_t const value_kind = value_type->kind;
8081 unsigned value_flags;
8082 unsigned value_size;
8083 if (value_kind == TYPE_ATOMIC) {
8084 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8085 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8086 value_size = get_atomic_type_size(value_akind);
8087 } else if (value_kind == TYPE_POINTER) {
8088 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8089 value_size = get_atomic_type_size(get_intptr_kind());
8094 if (value_flags != flags || value_size != size)
8098 } while (expression->kind == EXPR_UNARY_CAST);
8102 if (!is_lvalue(expression)) {
8103 errorf(&expression->base.source_position,
8104 "asm output argument is not an lvalue");
8107 argument->expression = expression;
8110 set_address_taken(expression, true);
8113 last->next = argument;
8119 if (token.type != ',')
8130 * Parse a asm statement clobber specification.
8132 static asm_clobber_t *parse_asm_clobbers(void)
8134 asm_clobber_t *result = NULL;
8135 asm_clobber_t *last = NULL;
8137 while(token.type == T_STRING_LITERAL) {
8138 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8139 clobber->clobber = parse_string_literals();
8142 last->next = clobber;
8148 if (token.type != ',')
8157 * Parse an asm statement.
8159 static statement_t *parse_asm_statement(void)
8163 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8164 statement->base.source_position = token.source_position;
8166 asm_statement_t *asm_statement = &statement->asms;
8168 if (token.type == T_volatile) {
8170 asm_statement->is_volatile = true;
8174 add_anchor_token(')');
8175 add_anchor_token(':');
8176 asm_statement->asm_text = parse_string_literals();
8178 if (token.type != ':') {
8179 rem_anchor_token(':');
8184 asm_statement->outputs = parse_asm_arguments(true);
8185 if (token.type != ':') {
8186 rem_anchor_token(':');
8191 asm_statement->inputs = parse_asm_arguments(false);
8192 if (token.type != ':') {
8193 rem_anchor_token(':');
8196 rem_anchor_token(':');
8199 asm_statement->clobbers = parse_asm_clobbers();
8202 rem_anchor_token(')');
8206 if (asm_statement->outputs == NULL) {
8207 /* GCC: An 'asm' instruction without any output operands will be treated
8208 * identically to a volatile 'asm' instruction. */
8209 asm_statement->is_volatile = true;
8214 return create_invalid_statement();
8218 * Parse a case statement.
8220 static statement_t *parse_case_statement(void)
8224 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8225 source_position_t *const pos = &statement->base.source_position;
8227 *pos = token.source_position;
8228 statement->case_label.expression = parse_expression();
8229 if (! is_constant_expression(statement->case_label.expression)) {
8230 errorf(pos, "case label does not reduce to an integer constant");
8231 statement->case_label.is_bad = true;
8233 long const val = fold_constant(statement->case_label.expression);
8234 statement->case_label.first_case = val;
8235 statement->case_label.last_case = val;
8238 if (c_mode & _GNUC) {
8239 if (token.type == T_DOTDOTDOT) {
8241 statement->case_label.end_range = parse_expression();
8242 if (! is_constant_expression(statement->case_label.end_range)) {
8243 errorf(pos, "case range does not reduce to an integer constant");
8244 statement->case_label.is_bad = true;
8246 long const val = fold_constant(statement->case_label.end_range);
8247 statement->case_label.last_case = val;
8249 if (val < statement->case_label.first_case) {
8250 statement->case_label.is_empty = true;
8251 warningf(pos, "empty range specified");
8257 PUSH_PARENT(statement);
8261 if (current_switch != NULL) {
8262 if (! statement->case_label.is_bad) {
8263 /* Check for duplicate case values */
8264 case_label_statement_t *c = &statement->case_label;
8265 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8266 if (l->is_bad || l->is_empty || l->expression == NULL)
8269 if (c->last_case < l->first_case || c->first_case > l->last_case)
8272 errorf(pos, "duplicate case value (previously used %P)",
8273 &l->base.source_position);
8277 /* link all cases into the switch statement */
8278 if (current_switch->last_case == NULL) {
8279 current_switch->first_case = &statement->case_label;
8281 current_switch->last_case->next = &statement->case_label;
8283 current_switch->last_case = &statement->case_label;
8285 errorf(pos, "case label not within a switch statement");
8288 statement_t *const inner_stmt = parse_statement();
8289 statement->case_label.statement = inner_stmt;
8290 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8291 errorf(&inner_stmt->base.source_position, "declaration after case label");
8298 return create_invalid_statement();
8302 * Parse a default statement.
8304 static statement_t *parse_default_statement(void)
8308 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8309 statement->base.source_position = token.source_position;
8311 PUSH_PARENT(statement);
8314 if (current_switch != NULL) {
8315 const case_label_statement_t *def_label = current_switch->default_label;
8316 if (def_label != NULL) {
8317 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8318 &def_label->base.source_position);
8320 current_switch->default_label = &statement->case_label;
8322 /* link all cases into the switch statement */
8323 if (current_switch->last_case == NULL) {
8324 current_switch->first_case = &statement->case_label;
8326 current_switch->last_case->next = &statement->case_label;
8328 current_switch->last_case = &statement->case_label;
8331 errorf(&statement->base.source_position,
8332 "'default' label not within a switch statement");
8335 statement_t *const inner_stmt = parse_statement();
8336 statement->case_label.statement = inner_stmt;
8337 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8338 errorf(&inner_stmt->base.source_position, "declaration after default label");
8345 return create_invalid_statement();
8349 * Return the declaration for a given label symbol or create a new one.
8351 * @param symbol the symbol of the label
8353 static declaration_t *get_label(symbol_t *symbol)
8355 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
8356 assert(current_function != NULL);
8357 /* if we found a label in the same function, then we already created the
8359 if (candidate != NULL
8360 && candidate->parent_scope == ¤t_function->scope) {
8364 /* otherwise we need to create a new one */
8365 declaration_t *const declaration = allocate_declaration_zero();
8366 declaration->namespc = NAMESPACE_LABEL;
8367 declaration->symbol = symbol;
8369 label_push(declaration);
8375 * Parse a label statement.
8377 static statement_t *parse_label_statement(void)
8379 assert(token.type == T_IDENTIFIER);
8380 symbol_t *symbol = token.v.symbol;
8383 declaration_t *label = get_label(symbol);
8385 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8386 statement->base.source_position = token.source_position;
8387 statement->label.label = label;
8389 PUSH_PARENT(statement);
8391 /* if source position is already set then the label is defined twice,
8392 * otherwise it was just mentioned in a goto so far */
8393 if (label->source_position.input_name != NULL) {
8394 errorf(HERE, "duplicate label '%Y' (declared %P)",
8395 symbol, &label->source_position);
8397 label->source_position = token.source_position;
8398 label->init.statement = statement;
8403 if (token.type == '}') {
8404 /* TODO only warn? */
8406 warningf(HERE, "label at end of compound statement");
8407 statement->label.statement = create_empty_statement();
8409 errorf(HERE, "label at end of compound statement");
8410 statement->label.statement = create_invalid_statement();
8412 } else if (token.type == ';') {
8413 /* Eat an empty statement here, to avoid the warning about an empty
8414 * statement after a label. label:; is commonly used to have a label
8415 * before a closing brace. */
8416 statement->label.statement = create_empty_statement();
8419 statement_t *const inner_stmt = parse_statement();
8420 statement->label.statement = inner_stmt;
8421 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8422 errorf(&inner_stmt->base.source_position, "declaration after label");
8426 /* remember the labels in a list for later checking */
8427 if (label_last == NULL) {
8428 label_first = &statement->label;
8430 label_last->next = &statement->label;
8432 label_last = &statement->label;
8439 * Parse an if statement.
8441 static statement_t *parse_if(void)
8445 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8446 statement->base.source_position = token.source_position;
8448 PUSH_PARENT(statement);
8451 add_anchor_token(')');
8452 statement->ifs.condition = parse_expression();
8453 rem_anchor_token(')');
8456 add_anchor_token(T_else);
8457 statement->ifs.true_statement = parse_statement();
8458 rem_anchor_token(T_else);
8460 if (token.type == T_else) {
8462 statement->ifs.false_statement = parse_statement();
8469 return create_invalid_statement();
8473 * Check that all enums are handled in a switch.
8475 * @param statement the switch statement to check
8477 static void check_enum_cases(const switch_statement_t *statement) {
8478 const type_t *type = skip_typeref(statement->expression->base.type);
8479 if (! is_type_enum(type))
8481 const enum_type_t *enumt = &type->enumt;
8483 /* if we have a default, no warnings */
8484 if (statement->default_label != NULL)
8487 /* FIXME: calculation of value should be done while parsing */
8488 const declaration_t *declaration;
8489 long last_value = -1;
8490 for (declaration = enumt->declaration->next;
8491 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8492 declaration = declaration->next) {
8493 const expression_t *expression = declaration->init.enum_value;
8494 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8496 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8497 if (l->expression == NULL)
8499 if (l->first_case <= value && value <= l->last_case) {
8505 warningf(&statement->base.source_position,
8506 "enumeration value '%Y' not handled in switch", declaration->symbol);
8513 * Parse a switch statement.
8515 static statement_t *parse_switch(void)
8519 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8520 statement->base.source_position = token.source_position;
8522 PUSH_PARENT(statement);
8525 add_anchor_token(')');
8526 expression_t *const expr = parse_expression();
8527 type_t * type = skip_typeref(expr->base.type);
8528 if (is_type_integer(type)) {
8529 type = promote_integer(type);
8530 } else if (is_type_valid(type)) {
8531 errorf(&expr->base.source_position,
8532 "switch quantity is not an integer, but '%T'", type);
8533 type = type_error_type;
8535 statement->switchs.expression = create_implicit_cast(expr, type);
8537 rem_anchor_token(')');
8539 switch_statement_t *rem = current_switch;
8540 current_switch = &statement->switchs;
8541 statement->switchs.body = parse_statement();
8542 current_switch = rem;
8544 if (warning.switch_default &&
8545 statement->switchs.default_label == NULL) {
8546 warningf(&statement->base.source_position, "switch has no default case");
8548 if (warning.switch_enum)
8549 check_enum_cases(&statement->switchs);
8555 return create_invalid_statement();
8558 static statement_t *parse_loop_body(statement_t *const loop)
8560 statement_t *const rem = current_loop;
8561 current_loop = loop;
8563 statement_t *const body = parse_statement();
8570 * Parse a while statement.
8572 static statement_t *parse_while(void)
8576 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8577 statement->base.source_position = token.source_position;
8579 PUSH_PARENT(statement);
8582 add_anchor_token(')');
8583 statement->whiles.condition = parse_expression();
8584 rem_anchor_token(')');
8587 statement->whiles.body = parse_loop_body(statement);
8593 return create_invalid_statement();
8597 * Parse a do statement.
8599 static statement_t *parse_do(void)
8603 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
8604 statement->base.source_position = token.source_position;
8606 PUSH_PARENT(statement)
8608 add_anchor_token(T_while);
8609 statement->do_while.body = parse_loop_body(statement);
8610 rem_anchor_token(T_while);
8614 add_anchor_token(')');
8615 statement->do_while.condition = parse_expression();
8616 rem_anchor_token(')');
8624 return create_invalid_statement();
8628 * Parse a for statement.
8630 static statement_t *parse_for(void)
8634 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
8635 statement->base.source_position = token.source_position;
8637 PUSH_PARENT(statement);
8639 int top = environment_top();
8640 scope_t *last_scope = scope;
8641 set_scope(&statement->fors.scope);
8644 add_anchor_token(')');
8646 if (token.type != ';') {
8647 if (is_declaration_specifier(&token, false)) {
8648 parse_declaration(record_declaration);
8650 add_anchor_token(';');
8651 expression_t *const init = parse_expression();
8652 statement->fors.initialisation = init;
8653 if (warning.unused_value && !expression_has_effect(init)) {
8654 warningf(&init->base.source_position,
8655 "initialisation of 'for'-statement has no effect");
8657 rem_anchor_token(';');
8664 if (token.type != ';') {
8665 add_anchor_token(';');
8666 statement->fors.condition = parse_expression();
8667 rem_anchor_token(';');
8670 if (token.type != ')') {
8671 expression_t *const step = parse_expression();
8672 statement->fors.step = step;
8673 if (warning.unused_value && !expression_has_effect(step)) {
8674 warningf(&step->base.source_position,
8675 "step of 'for'-statement has no effect");
8678 rem_anchor_token(')');
8680 statement->fors.body = parse_loop_body(statement);
8682 assert(scope == &statement->fors.scope);
8683 set_scope(last_scope);
8684 environment_pop_to(top);
8691 rem_anchor_token(')');
8692 assert(scope == &statement->fors.scope);
8693 set_scope(last_scope);
8694 environment_pop_to(top);
8696 return create_invalid_statement();
8700 * Parse a goto statement.
8702 static statement_t *parse_goto(void)
8706 if (token.type != T_IDENTIFIER) {
8707 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
8711 symbol_t *symbol = token.v.symbol;
8714 declaration_t *label = get_label(symbol);
8716 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
8717 statement->base.source_position = token.source_position;
8719 statement->gotos.label = label;
8721 /* remember the goto's in a list for later checking */
8722 if (goto_last == NULL) {
8723 goto_first = &statement->gotos;
8725 goto_last->next = &statement->gotos;
8727 goto_last = &statement->gotos;
8733 return create_invalid_statement();
8737 * Parse a continue statement.
8739 static statement_t *parse_continue(void)
8741 statement_t *statement;
8742 if (current_loop == NULL) {
8743 errorf(HERE, "continue statement not within loop");
8744 statement = create_invalid_statement();
8746 statement = allocate_statement_zero(STATEMENT_CONTINUE);
8748 statement->base.source_position = token.source_position;
8756 return create_invalid_statement();
8760 * Parse a break statement.
8762 static statement_t *parse_break(void)
8764 statement_t *statement;
8765 if (current_switch == NULL && current_loop == NULL) {
8766 errorf(HERE, "break statement not within loop or switch");
8767 statement = create_invalid_statement();
8769 statement = allocate_statement_zero(STATEMENT_BREAK);
8771 statement->base.source_position = token.source_position;
8779 return create_invalid_statement();
8783 * Parse a __leave statement.
8785 static statement_t *parse_leave(void)
8787 statement_t *statement;
8788 if (current_try == NULL) {
8789 errorf(HERE, "__leave statement not within __try");
8790 statement = create_invalid_statement();
8792 statement = allocate_statement_zero(STATEMENT_LEAVE);
8794 statement->base.source_position = token.source_position;
8802 return create_invalid_statement();
8806 * Check if a given declaration represents a local variable.
8808 static bool is_local_var_declaration(const declaration_t *declaration)
8810 switch ((storage_class_tag_t) declaration->storage_class) {
8811 case STORAGE_CLASS_AUTO:
8812 case STORAGE_CLASS_REGISTER: {
8813 const type_t *type = skip_typeref(declaration->type);
8814 if (is_type_function(type)) {
8826 * Check if a given declaration represents a variable.
8828 static bool is_var_declaration(const declaration_t *declaration)
8830 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
8833 const type_t *type = skip_typeref(declaration->type);
8834 return !is_type_function(type);
8838 * Check if a given expression represents a local variable.
8840 static bool is_local_variable(const expression_t *expression)
8842 if (expression->base.kind != EXPR_REFERENCE) {
8845 const declaration_t *declaration = expression->reference.declaration;
8846 return is_local_var_declaration(declaration);
8850 * Check if a given expression represents a local variable and
8851 * return its declaration then, else return NULL.
8853 declaration_t *expr_is_variable(const expression_t *expression)
8855 if (expression->base.kind != EXPR_REFERENCE) {
8858 declaration_t *declaration = expression->reference.declaration;
8859 if (is_var_declaration(declaration))
8865 * Parse a return statement.
8867 static statement_t *parse_return(void)
8869 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
8870 statement->base.source_position = token.source_position;
8874 expression_t *return_value = NULL;
8875 if (token.type != ';') {
8876 return_value = parse_expression();
8880 const type_t *const func_type = current_function->type;
8881 assert(is_type_function(func_type));
8882 type_t *const return_type = skip_typeref(func_type->function.return_type);
8884 if (return_value != NULL) {
8885 type_t *return_value_type = skip_typeref(return_value->base.type);
8887 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8888 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8889 warningf(&statement->base.source_position,
8890 "'return' with a value, in function returning void");
8891 return_value = NULL;
8893 assign_error_t error = semantic_assign(return_type, return_value);
8894 report_assign_error(error, return_type, return_value, "'return'",
8895 &statement->base.source_position);
8896 return_value = create_implicit_cast(return_value, return_type);
8898 /* check for returning address of a local var */
8899 if (return_value != NULL &&
8900 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8901 const expression_t *expression = return_value->unary.value;
8902 if (is_local_variable(expression)) {
8903 warningf(&statement->base.source_position,
8904 "function returns address of local variable");
8908 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8909 warningf(&statement->base.source_position,
8910 "'return' without value, in function returning non-void");
8913 statement->returns.value = return_value;
8917 return create_invalid_statement();
8921 * Parse a declaration statement.
8923 static statement_t *parse_declaration_statement(void)
8925 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8927 statement->base.source_position = token.source_position;
8929 declaration_t *before = last_declaration;
8930 parse_declaration(record_declaration);
8932 if (before == NULL) {
8933 statement->declaration.declarations_begin = scope->declarations;
8935 statement->declaration.declarations_begin = before->next;
8937 statement->declaration.declarations_end = last_declaration;
8943 * Parse an expression statement, ie. expr ';'.
8945 static statement_t *parse_expression_statement(void)
8947 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8949 statement->base.source_position = token.source_position;
8950 expression_t *const expr = parse_expression();
8951 statement->expression.expression = expr;
8957 return create_invalid_statement();
8961 * Parse a microsoft __try { } __finally { } or
8962 * __try{ } __except() { }
8964 static statement_t *parse_ms_try_statment(void)
8966 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8968 statement->base.source_position = token.source_position;
8971 ms_try_statement_t *rem = current_try;
8972 current_try = &statement->ms_try;
8973 statement->ms_try.try_statement = parse_compound_statement(false);
8976 if (token.type == T___except) {
8979 add_anchor_token(')');
8980 expression_t *const expr = parse_expression();
8981 type_t * type = skip_typeref(expr->base.type);
8982 if (is_type_integer(type)) {
8983 type = promote_integer(type);
8984 } else if (is_type_valid(type)) {
8985 errorf(&expr->base.source_position,
8986 "__expect expression is not an integer, but '%T'", type);
8987 type = type_error_type;
8989 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8990 rem_anchor_token(')');
8992 statement->ms_try.final_statement = parse_compound_statement(false);
8993 } else if (token.type == T__finally) {
8995 statement->ms_try.final_statement = parse_compound_statement(false);
8997 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8998 return create_invalid_statement();
9002 return create_invalid_statement();
9005 static statement_t *parse_empty_statement(void)
9007 if (warning.empty_statement) {
9008 warningf(HERE, "statement is empty");
9010 statement_t *const statement = create_empty_statement();
9016 * Parse a statement.
9017 * There's also parse_statement() which additionally checks for
9018 * "statement has no effect" warnings
9020 static statement_t *intern_parse_statement(void)
9022 statement_t *statement = NULL;
9024 /* declaration or statement */
9025 add_anchor_token(';');
9026 switch (token.type) {
9028 if (look_ahead(1)->type == ':') {
9029 statement = parse_label_statement();
9030 } else if (is_typedef_symbol(token.v.symbol)) {
9031 statement = parse_declaration_statement();
9033 statement = parse_expression_statement();
9037 case T___extension__:
9038 /* This can be a prefix to a declaration or an expression statement.
9039 * We simply eat it now and parse the rest with tail recursion. */
9042 } while (token.type == T___extension__);
9043 statement = parse_statement();
9047 statement = parse_declaration_statement();
9050 case ';': statement = parse_empty_statement(); break;
9051 case '{': statement = parse_compound_statement(false); break;
9052 case T___leave: statement = parse_leave(); break;
9053 case T___try: statement = parse_ms_try_statment(); break;
9054 case T_asm: statement = parse_asm_statement(); break;
9055 case T_break: statement = parse_break(); break;
9056 case T_case: statement = parse_case_statement(); break;
9057 case T_continue: statement = parse_continue(); break;
9058 case T_default: statement = parse_default_statement(); break;
9059 case T_do: statement = parse_do(); break;
9060 case T_for: statement = parse_for(); break;
9061 case T_goto: statement = parse_goto(); break;
9062 case T_if: statement = parse_if (); break;
9063 case T_return: statement = parse_return(); break;
9064 case T_switch: statement = parse_switch(); break;
9065 case T_while: statement = parse_while(); break;
9066 default: statement = parse_expression_statement(); break;
9068 rem_anchor_token(';');
9070 assert(statement != NULL
9071 && statement->base.source_position.input_name != NULL);
9077 * parse a statement and emits "statement has no effect" warning if needed
9078 * (This is really a wrapper around intern_parse_statement with check for 1
9079 * single warning. It is needed, because for statement expressions we have
9080 * to avoid the warning on the last statement)
9082 static statement_t *parse_statement(void)
9084 statement_t *statement = intern_parse_statement();
9086 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9087 expression_t *expression = statement->expression.expression;
9088 if (!expression_has_effect(expression)) {
9089 warningf(&expression->base.source_position,
9090 "statement has no effect");
9098 * Parse a compound statement.
9100 static statement_t *parse_compound_statement(bool inside_expression_statement)
9102 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9103 statement->base.source_position = token.source_position;
9105 PUSH_PARENT(statement);
9108 add_anchor_token('}');
9110 int top = environment_top();
9111 scope_t *last_scope = scope;
9112 set_scope(&statement->compound.scope);
9114 statement_t **anchor = &statement->compound.statements;
9115 bool only_decls_so_far = true;
9116 while (token.type != '}' && token.type != T_EOF) {
9117 statement_t *sub_statement = intern_parse_statement();
9118 if (is_invalid_statement(sub_statement)) {
9119 /* an error occurred. if we are at an anchor, return */
9125 if (warning.declaration_after_statement) {
9126 if (sub_statement->kind != STATEMENT_DECLARATION) {
9127 only_decls_so_far = false;
9128 } else if (!only_decls_so_far) {
9129 warningf(&sub_statement->base.source_position,
9130 "ISO C90 forbids mixed declarations and code");
9134 *anchor = sub_statement;
9136 while (sub_statement->base.next != NULL)
9137 sub_statement = sub_statement->base.next;
9139 anchor = &sub_statement->base.next;
9142 if (token.type == '}') {
9145 errorf(&statement->base.source_position,
9146 "end of file while looking for closing '}'");
9149 /* look over all statements again to produce no effect warnings */
9150 if (warning.unused_value) {
9151 statement_t *sub_statement = statement->compound.statements;
9152 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9153 if (sub_statement->kind != STATEMENT_EXPRESSION)
9155 /* don't emit a warning for the last expression in an expression
9156 * statement as it has always an effect */
9157 if (inside_expression_statement && sub_statement->base.next == NULL)
9160 expression_t *expression = sub_statement->expression.expression;
9161 if (!expression_has_effect(expression)) {
9162 warningf(&expression->base.source_position,
9163 "statement has no effect");
9169 rem_anchor_token('}');
9170 assert(scope == &statement->compound.scope);
9171 set_scope(last_scope);
9172 environment_pop_to(top);
9179 * Initialize builtin types.
9181 static void initialize_builtin_types(void)
9183 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9184 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9185 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9186 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9187 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9188 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9189 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9190 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9192 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9193 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9194 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9195 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9197 /* const version of wchar_t */
9198 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9199 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9200 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9202 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9206 * Check for unused global static functions and variables
9208 static void check_unused_globals(void)
9210 if (!warning.unused_function && !warning.unused_variable)
9213 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9215 decl->modifiers & DM_UNUSED ||
9216 decl->modifiers & DM_USED ||
9217 decl->storage_class != STORAGE_CLASS_STATIC)
9220 type_t *const type = decl->type;
9222 if (is_type_function(skip_typeref(type))) {
9223 if (!warning.unused_function || decl->is_inline)
9226 s = (decl->init.statement != NULL ? "defined" : "declared");
9228 if (!warning.unused_variable)
9234 warningf(&decl->source_position, "'%#T' %s but not used",
9235 type, decl->symbol, s);
9239 static void parse_global_asm(void)
9244 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9245 statement->base.source_position = token.source_position;
9246 statement->asms.asm_text = parse_string_literals();
9247 statement->base.next = unit->global_asm;
9248 unit->global_asm = statement;
9257 * Parse a translation unit.
9259 static void parse_translation_unit(void)
9261 for (;;) switch (token.type) {
9264 case T___extension__:
9265 parse_external_declaration();
9276 /* TODO error in strict mode */
9277 warningf(HERE, "stray ';' outside of function");
9282 errorf(HERE, "stray %K outside of function", &token);
9283 if (token.type == '(' || token.type == '{' || token.type == '[')
9284 eat_until_matching_token(token.type);
9293 * @return the translation unit or NULL if errors occurred.
9295 void start_parsing(void)
9297 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9298 label_stack = NEW_ARR_F(stack_entry_t, 0);
9299 diagnostic_count = 0;
9303 type_set_output(stderr);
9304 ast_set_output(stderr);
9306 assert(unit == NULL);
9307 unit = allocate_ast_zero(sizeof(unit[0]));
9309 assert(global_scope == NULL);
9310 global_scope = &unit->scope;
9312 assert(scope == NULL);
9313 set_scope(&unit->scope);
9315 initialize_builtin_types();
9318 translation_unit_t *finish_parsing(void)
9320 assert(scope == &unit->scope);
9322 last_declaration = NULL;
9324 assert(global_scope == &unit->scope);
9325 check_unused_globals();
9326 global_scope = NULL;
9328 DEL_ARR_F(environment_stack);
9329 DEL_ARR_F(label_stack);
9331 translation_unit_t *result = unit;
9338 lookahead_bufpos = 0;
9339 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9342 parse_translation_unit();
9346 * Initialize the parser.
9348 void init_parser(void)
9351 /* add predefined symbols for extended-decl-modifier */
9352 sym_align = symbol_table_insert("align");
9353 sym_allocate = symbol_table_insert("allocate");
9354 sym_dllimport = symbol_table_insert("dllimport");
9355 sym_dllexport = symbol_table_insert("dllexport");
9356 sym_naked = symbol_table_insert("naked");
9357 sym_noinline = symbol_table_insert("noinline");
9358 sym_noreturn = symbol_table_insert("noreturn");
9359 sym_nothrow = symbol_table_insert("nothrow");
9360 sym_novtable = symbol_table_insert("novtable");
9361 sym_property = symbol_table_insert("property");
9362 sym_get = symbol_table_insert("get");
9363 sym_put = symbol_table_insert("put");
9364 sym_selectany = symbol_table_insert("selectany");
9365 sym_thread = symbol_table_insert("thread");
9366 sym_uuid = symbol_table_insert("uuid");
9367 sym_deprecated = symbol_table_insert("deprecated");
9368 sym_restrict = symbol_table_insert("restrict");
9369 sym_noalias = symbol_table_insert("noalias");
9371 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9373 init_expression_parsers();
9374 obstack_init(&temp_obst);
9376 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9377 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9381 * Terminate the parser.
9383 void exit_parser(void)
9385 obstack_free(&temp_obst, NULL);