2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 //#define PRINT_TOKENS
43 #define MAX_LOOKAHEAD 2
46 declaration_t *old_declaration;
48 unsigned short namespc;
51 typedef struct gnu_attribute_t gnu_attribute_t;
52 struct gnu_attribute_t {
53 gnu_attribute_kind_t kind;
54 gnu_attribute_t *next;
63 typedef struct declaration_specifiers_t declaration_specifiers_t;
64 struct declaration_specifiers_t {
65 source_position_t source_position;
66 unsigned char declared_storage_class;
67 unsigned char alignment; /**< Alignment, 0 if not set. */
68 unsigned int is_inline : 1;
69 unsigned int deprecated : 1;
70 decl_modifiers_t modifiers; /**< declaration modifiers */
71 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
72 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
73 symbol_t *get_property_sym; /**< the name of the get property if set. */
74 symbol_t *put_property_sym; /**< the name of the put property if set. */
79 * An environment for parsing initializers (and compound literals).
81 typedef struct parse_initializer_env_t {
82 type_t *type; /**< the type of the initializer. In case of an
83 array type with unspecified size this gets
84 adjusted to the actual size. */
85 declaration_t *declaration; /**< the declaration that is initialized if any */
86 bool must_be_constant;
87 } parse_initializer_env_t;
89 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
92 static token_t lookahead_buffer[MAX_LOOKAHEAD];
93 static int lookahead_bufpos;
94 static stack_entry_t *environment_stack = NULL;
95 static stack_entry_t *label_stack = NULL;
96 static scope_t *global_scope = NULL;
97 static scope_t *scope = NULL;
98 static declaration_t *last_declaration = NULL;
99 static declaration_t *current_function = NULL;
100 static switch_statement_t *current_switch = NULL;
101 static statement_t *current_loop = NULL;
102 static ms_try_statement_t *current_try = NULL;
103 static goto_statement_t *goto_first = NULL;
104 static goto_statement_t *goto_last = NULL;
105 static label_statement_t *label_first = NULL;
106 static label_statement_t *label_last = NULL;
107 static translation_unit_t *unit = NULL;
108 static struct obstack temp_obst;
110 static source_position_t null_position = { NULL, 0 };
112 /* symbols for Microsoft extended-decl-modifier */
113 static const symbol_t *sym_align = NULL;
114 static const symbol_t *sym_allocate = NULL;
115 static const symbol_t *sym_dllimport = NULL;
116 static const symbol_t *sym_dllexport = NULL;
117 static const symbol_t *sym_naked = NULL;
118 static const symbol_t *sym_noinline = NULL;
119 static const symbol_t *sym_noreturn = NULL;
120 static const symbol_t *sym_nothrow = NULL;
121 static const symbol_t *sym_novtable = NULL;
122 static const symbol_t *sym_property = NULL;
123 static const symbol_t *sym_get = NULL;
124 static const symbol_t *sym_put = NULL;
125 static const symbol_t *sym_selectany = NULL;
126 static const symbol_t *sym_thread = NULL;
127 static const symbol_t *sym_uuid = NULL;
128 static const symbol_t *sym_deprecated = NULL;
129 static const symbol_t *sym_restrict = NULL;
130 static const symbol_t *sym_noalias = NULL;
132 /** The token anchor set */
133 static unsigned char token_anchor_set[T_LAST_TOKEN];
135 /** The current source position. */
136 #define HERE (&token.source_position)
138 static type_t *type_valist;
140 static statement_t *parse_compound_statement(bool inside_expression_statement);
141 static statement_t *parse_statement(void);
143 static expression_t *parse_sub_expression(unsigned precedence);
144 static expression_t *parse_expression(void);
145 static type_t *parse_typename(void);
147 static void parse_compound_type_entries(declaration_t *compound_declaration);
148 static declaration_t *parse_declarator(
149 const declaration_specifiers_t *specifiers, bool may_be_abstract);
150 static declaration_t *record_declaration(declaration_t *declaration);
152 static void semantic_comparison(binary_expression_t *expression);
154 #define STORAGE_CLASSES \
161 #define TYPE_QUALIFIERS \
168 #ifdef PROVIDE_COMPLEX
169 #define COMPLEX_SPECIFIERS \
171 #define IMAGINARY_SPECIFIERS \
174 #define COMPLEX_SPECIFIERS
175 #define IMAGINARY_SPECIFIERS
178 #define TYPE_SPECIFIERS \
193 case T___builtin_va_list: \
198 #define DECLARATION_START \
203 #define TYPENAME_START \
208 * Allocate an AST node with given size and
209 * initialize all fields with zero.
211 static void *allocate_ast_zero(size_t size)
213 void *res = allocate_ast(size);
214 memset(res, 0, size);
218 static declaration_t *allocate_declaration_zero(void)
220 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
221 declaration->type = type_error_type;
222 declaration->alignment = 0;
227 * Returns the size of a statement node.
229 * @param kind the statement kind
231 static size_t get_statement_struct_size(statement_kind_t kind)
233 static const size_t sizes[] = {
234 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
235 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
236 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
237 [STATEMENT_RETURN] = sizeof(return_statement_t),
238 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
239 [STATEMENT_IF] = sizeof(if_statement_t),
240 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
241 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
242 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
243 [STATEMENT_BREAK] = sizeof(statement_base_t),
244 [STATEMENT_GOTO] = sizeof(goto_statement_t),
245 [STATEMENT_LABEL] = sizeof(label_statement_t),
246 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
247 [STATEMENT_WHILE] = sizeof(while_statement_t),
248 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
249 [STATEMENT_FOR] = sizeof(for_statement_t),
250 [STATEMENT_ASM] = sizeof(asm_statement_t),
251 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
252 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
254 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
255 assert(sizes[kind] != 0);
260 * Returns the size of an expression node.
262 * @param kind the expression kind
264 static size_t get_expression_struct_size(expression_kind_t kind)
266 static const size_t sizes[] = {
267 [EXPR_INVALID] = sizeof(expression_base_t),
268 [EXPR_REFERENCE] = sizeof(reference_expression_t),
269 [EXPR_CONST] = sizeof(const_expression_t),
270 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
271 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
272 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
273 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
274 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
275 [EXPR_CALL] = sizeof(call_expression_t),
276 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
277 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
278 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
279 [EXPR_SELECT] = sizeof(select_expression_t),
280 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
281 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
282 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
283 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
284 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
285 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
286 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
287 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
288 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
289 [EXPR_VA_START] = sizeof(va_start_expression_t),
290 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
291 [EXPR_STATEMENT] = sizeof(statement_expression_t),
293 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
294 return sizes[EXPR_UNARY_FIRST];
296 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
297 return sizes[EXPR_BINARY_FIRST];
299 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
300 assert(sizes[kind] != 0);
305 * Allocate a statement node of given kind and initialize all
308 static statement_t *allocate_statement_zero(statement_kind_t kind)
310 size_t size = get_statement_struct_size(kind);
311 statement_t *res = allocate_ast_zero(size);
313 res->base.kind = kind;
318 * Allocate an expression node of given kind and initialize all
321 static expression_t *allocate_expression_zero(expression_kind_t kind)
323 size_t size = get_expression_struct_size(kind);
324 expression_t *res = allocate_ast_zero(size);
326 res->base.kind = kind;
327 res->base.type = type_error_type;
332 * Creates a new invalid expression.
334 static expression_t *create_invalid_expression(void)
336 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
337 expression->base.source_position = token.source_position;
342 * Creates a new invalid statement.
344 static statement_t *create_invalid_statement(void)
346 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
347 statement->base.source_position = token.source_position;
352 * Allocate a new empty statement.
354 static statement_t *create_empty_statement(void)
356 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
357 statement->base.source_position = token.source_position;
362 * Returns the size of a type node.
364 * @param kind the type kind
366 static size_t get_type_struct_size(type_kind_t kind)
368 static const size_t sizes[] = {
369 [TYPE_ATOMIC] = sizeof(atomic_type_t),
370 [TYPE_COMPLEX] = sizeof(complex_type_t),
371 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
372 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
373 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
374 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
375 [TYPE_ENUM] = sizeof(enum_type_t),
376 [TYPE_FUNCTION] = sizeof(function_type_t),
377 [TYPE_POINTER] = sizeof(pointer_type_t),
378 [TYPE_ARRAY] = sizeof(array_type_t),
379 [TYPE_BUILTIN] = sizeof(builtin_type_t),
380 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
381 [TYPE_TYPEOF] = sizeof(typeof_type_t),
383 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
384 assert(kind <= TYPE_TYPEOF);
385 assert(sizes[kind] != 0);
390 * Allocate a type node of given kind and initialize all
393 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
395 size_t size = get_type_struct_size(kind);
396 type_t *res = obstack_alloc(type_obst, size);
397 memset(res, 0, size);
399 res->base.kind = kind;
400 res->base.source_position = *source_position;
405 * Returns the size of an initializer node.
407 * @param kind the initializer kind
409 static size_t get_initializer_size(initializer_kind_t kind)
411 static const size_t sizes[] = {
412 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
413 [INITIALIZER_STRING] = sizeof(initializer_string_t),
414 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
415 [INITIALIZER_LIST] = sizeof(initializer_list_t),
416 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
418 assert(kind < sizeof(sizes) / sizeof(*sizes));
419 assert(sizes[kind] != 0);
424 * Allocate an initializer node of given kind and initialize all
427 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
429 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
436 * Free a type from the type obstack.
438 static void free_type(void *type)
440 obstack_free(type_obst, type);
444 * Returns the index of the top element of the environment stack.
446 static size_t environment_top(void)
448 return ARR_LEN(environment_stack);
452 * Returns the index of the top element of the label stack.
454 static size_t label_top(void)
456 return ARR_LEN(label_stack);
460 * Return the next token.
462 static inline void next_token(void)
464 token = lookahead_buffer[lookahead_bufpos];
465 lookahead_buffer[lookahead_bufpos] = lexer_token;
468 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
471 print_token(stderr, &token);
472 fprintf(stderr, "\n");
477 * Return the next token with a given lookahead.
479 static inline const token_t *look_ahead(int num)
481 assert(num > 0 && num <= MAX_LOOKAHEAD);
482 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
483 return &lookahead_buffer[pos];
487 * Adds a token to the token anchor set (a multi-set).
489 static void add_anchor_token(int token_type) {
490 assert(0 <= token_type && token_type < T_LAST_TOKEN);
491 ++token_anchor_set[token_type];
494 static int save_and_reset_anchor_state(int token_type) {
495 assert(0 <= token_type && token_type < T_LAST_TOKEN);
496 int count = token_anchor_set[token_type];
497 token_anchor_set[token_type] = 0;
501 static void restore_anchor_state(int token_type, int count) {
502 assert(0 <= token_type && token_type < T_LAST_TOKEN);
503 token_anchor_set[token_type] = count;
507 * Remove a token from the token anchor set (a multi-set).
509 static void rem_anchor_token(int token_type) {
510 assert(0 <= token_type && token_type < T_LAST_TOKEN);
511 --token_anchor_set[token_type];
514 static bool at_anchor(void) {
517 return token_anchor_set[token.type];
521 * Eat tokens until a matching token is found.
523 static void eat_until_matching_token(int type) {
524 unsigned parenthesis_count = 0;
525 unsigned brace_count = 0;
526 unsigned bracket_count = 0;
527 int end_token = type;
536 while(token.type != end_token ||
537 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
541 case '(': ++parenthesis_count; break;
542 case '{': ++brace_count; break;
543 case '[': ++bracket_count; break;
545 if(parenthesis_count > 0)
553 if(bracket_count > 0)
564 * Eat input tokens until an anchor is found.
566 static void eat_until_anchor(void) {
567 if(token.type == T_EOF)
569 while(token_anchor_set[token.type] == 0) {
570 if(token.type == '(' || token.type == '{' || token.type == '[')
571 eat_until_matching_token(token.type);
572 if(token.type == T_EOF)
578 static void eat_block(void) {
579 eat_until_matching_token('{');
580 if(token.type == '}')
585 * eat all token until a ';' is reached or a stop token is found.
587 static void eat_statement(void) {
588 eat_until_matching_token(';');
589 if(token.type == ';')
593 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
596 * Report a parse error because an expected token was not found.
599 #if defined __GNUC__ && __GNUC__ >= 4
600 __attribute__((sentinel))
602 void parse_error_expected(const char *message, ...)
604 if(message != NULL) {
605 errorf(HERE, "%s", message);
608 va_start(ap, message);
609 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
614 * Report a type error.
616 static void type_error(const char *msg, const source_position_t *source_position,
619 errorf(source_position, "%s, but found type '%T'", msg, type);
623 * Report an incompatible type.
625 static void type_error_incompatible(const char *msg,
626 const source_position_t *source_position, type_t *type1, type_t *type2)
628 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
633 * Expect the the current token is the expected token.
634 * If not, generate an error, eat the current statement,
635 * and goto the end_error label.
637 #define expect(expected) \
639 if(UNLIKELY(token.type != (expected))) { \
640 parse_error_expected(NULL, (expected), NULL); \
641 add_anchor_token(expected); \
642 eat_until_anchor(); \
643 if (token.type == expected) \
645 rem_anchor_token(expected); \
651 static void set_scope(scope_t *new_scope)
654 scope->last_declaration = last_declaration;
658 last_declaration = new_scope->last_declaration;
662 * Search a symbol in a given namespace and returns its declaration or
663 * NULL if this symbol was not found.
665 static declaration_t *get_declaration(const symbol_t *const symbol,
666 const namespace_t namespc)
668 declaration_t *declaration = symbol->declaration;
669 for( ; declaration != NULL; declaration = declaration->symbol_next) {
670 if(declaration->namespc == namespc)
678 * pushs an environment_entry on the environment stack and links the
679 * corresponding symbol to the new entry
681 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
683 symbol_t *symbol = declaration->symbol;
684 namespace_t namespc = (namespace_t) declaration->namespc;
686 /* replace/add declaration into declaration list of the symbol */
687 declaration_t *iter = symbol->declaration;
689 symbol->declaration = declaration;
691 declaration_t *iter_last = NULL;
692 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
693 /* replace an entry? */
694 if(iter->namespc == namespc) {
695 if(iter_last == NULL) {
696 symbol->declaration = declaration;
698 iter_last->symbol_next = declaration;
700 declaration->symbol_next = iter->symbol_next;
705 assert(iter_last->symbol_next == NULL);
706 iter_last->symbol_next = declaration;
710 /* remember old declaration */
712 entry.symbol = symbol;
713 entry.old_declaration = iter;
714 entry.namespc = (unsigned short) namespc;
715 ARR_APP1(stack_entry_t, *stack_ptr, entry);
718 static void environment_push(declaration_t *declaration)
720 assert(declaration->source_position.input_name != NULL);
721 assert(declaration->parent_scope != NULL);
722 stack_push(&environment_stack, declaration);
725 static void label_push(declaration_t *declaration)
727 declaration->parent_scope = ¤t_function->scope;
728 stack_push(&label_stack, declaration);
732 * pops symbols from the environment stack until @p new_top is the top element
734 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
736 stack_entry_t *stack = *stack_ptr;
737 size_t top = ARR_LEN(stack);
740 assert(new_top <= top);
744 for(i = top; i > new_top; --i) {
745 stack_entry_t *entry = &stack[i - 1];
747 declaration_t *old_declaration = entry->old_declaration;
748 symbol_t *symbol = entry->symbol;
749 namespace_t namespc = (namespace_t)entry->namespc;
751 /* replace/remove declaration */
752 declaration_t *declaration = symbol->declaration;
753 assert(declaration != NULL);
754 if(declaration->namespc == namespc) {
755 if(old_declaration == NULL) {
756 symbol->declaration = declaration->symbol_next;
758 symbol->declaration = old_declaration;
761 declaration_t *iter_last = declaration;
762 declaration_t *iter = declaration->symbol_next;
763 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
764 /* replace an entry? */
765 if(iter->namespc == namespc) {
766 assert(iter_last != NULL);
767 iter_last->symbol_next = old_declaration;
768 if(old_declaration != NULL) {
769 old_declaration->symbol_next = iter->symbol_next;
774 assert(iter != NULL);
778 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
781 static void environment_pop_to(size_t new_top)
783 stack_pop_to(&environment_stack, new_top);
786 static void label_pop_to(size_t new_top)
788 stack_pop_to(&label_stack, new_top);
792 static int get_rank(const type_t *type)
794 assert(!is_typeref(type));
795 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
796 * and esp. footnote 108). However we can't fold constants (yet), so we
797 * can't decide whether unsigned int is possible, while int always works.
798 * (unsigned int would be preferable when possible... for stuff like
799 * struct { enum { ... } bla : 4; } ) */
800 if(type->kind == TYPE_ENUM)
801 return ATOMIC_TYPE_INT;
803 assert(type->kind == TYPE_ATOMIC);
804 return type->atomic.akind;
807 static type_t *promote_integer(type_t *type)
809 if(type->kind == TYPE_BITFIELD)
810 type = type->bitfield.base_type;
812 if(get_rank(type) < ATOMIC_TYPE_INT)
819 * Create a cast expression.
821 * @param expression the expression to cast
822 * @param dest_type the destination type
824 static expression_t *create_cast_expression(expression_t *expression,
827 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
829 cast->unary.value = expression;
830 cast->base.type = dest_type;
836 * Check if a given expression represents the 0 pointer constant.
838 static bool is_null_pointer_constant(const expression_t *expression)
840 /* skip void* cast */
841 if(expression->kind == EXPR_UNARY_CAST
842 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
843 expression = expression->unary.value;
846 /* TODO: not correct yet, should be any constant integer expression
847 * which evaluates to 0 */
848 if (expression->kind != EXPR_CONST)
851 type_t *const type = skip_typeref(expression->base.type);
852 if (!is_type_integer(type))
855 return expression->conste.v.int_value == 0;
859 * Create an implicit cast expression.
861 * @param expression the expression to cast
862 * @param dest_type the destination type
864 static expression_t *create_implicit_cast(expression_t *expression,
867 type_t *const source_type = expression->base.type;
869 if (source_type == dest_type)
872 return create_cast_expression(expression, dest_type);
875 /** Implements the rules from § 6.5.16.1 */
876 static type_t *semantic_assign(type_t *orig_type_left,
877 const expression_t *const right,
879 const source_position_t *source_position)
881 type_t *const orig_type_right = right->base.type;
882 type_t *const type_left = skip_typeref(orig_type_left);
883 type_t *const type_right = skip_typeref(orig_type_right);
885 if(is_type_pointer(type_left)) {
886 if(is_null_pointer_constant(right)) {
887 return orig_type_left;
888 } else if(is_type_pointer(type_right)) {
889 type_t *points_to_left
890 = skip_typeref(type_left->pointer.points_to);
891 type_t *points_to_right
892 = skip_typeref(type_right->pointer.points_to);
894 /* the left type has all qualifiers from the right type */
895 unsigned missing_qualifiers
896 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
897 if(missing_qualifiers != 0) {
898 errorf(source_position,
899 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
900 return orig_type_left;
903 points_to_left = get_unqualified_type(points_to_left);
904 points_to_right = get_unqualified_type(points_to_right);
906 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
907 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
908 return orig_type_left;
911 if (!types_compatible(points_to_left, points_to_right)) {
912 warningf(source_position,
913 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
914 orig_type_left, context, right, orig_type_right);
917 return orig_type_left;
918 } else if(is_type_integer(type_right)) {
919 warningf(source_position,
920 "%s makes pointer '%T' from integer '%T' without a cast",
921 context, orig_type_left, orig_type_right);
922 return orig_type_left;
924 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
925 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
926 && is_type_pointer(type_right))) {
927 return orig_type_left;
928 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
929 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
930 type_t *const unqual_type_left = get_unqualified_type(type_left);
931 type_t *const unqual_type_right = get_unqualified_type(type_right);
932 if (types_compatible(unqual_type_left, unqual_type_right)) {
933 return orig_type_left;
935 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
936 warningf(source_position,
937 "%s makes integer '%T' from pointer '%T' without a cast",
938 context, orig_type_left, orig_type_right);
939 return orig_type_left;
942 if (!is_type_valid(type_left))
945 if (!is_type_valid(type_right))
946 return orig_type_right;
951 static expression_t *parse_constant_expression(void)
953 /* start parsing at precedence 7 (conditional expression) */
954 expression_t *result = parse_sub_expression(7);
956 if(!is_constant_expression(result)) {
957 errorf(&result->base.source_position,
958 "expression '%E' is not constant\n", result);
964 static expression_t *parse_assignment_expression(void)
966 /* start parsing at precedence 2 (assignment expression) */
967 return parse_sub_expression(2);
970 static type_t *make_global_typedef(const char *name, type_t *type)
972 symbol_t *const symbol = symbol_table_insert(name);
974 declaration_t *const declaration = allocate_declaration_zero();
975 declaration->namespc = NAMESPACE_NORMAL;
976 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
977 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
978 declaration->type = type;
979 declaration->symbol = symbol;
980 declaration->source_position = builtin_source_position;
982 record_declaration(declaration);
984 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
985 typedef_type->typedeft.declaration = declaration;
990 static string_t parse_string_literals(void)
992 assert(token.type == T_STRING_LITERAL);
993 string_t result = token.v.string;
997 while (token.type == T_STRING_LITERAL) {
998 result = concat_strings(&result, &token.v.string);
1005 static const char *gnu_attribute_names[GNU_AK_LAST] = {
1006 [GNU_AK_CONST] = "const",
1007 [GNU_AK_VOLATILE] = "volatile",
1008 [GNU_AK_CDECL] = "cdecl",
1009 [GNU_AK_STDCALL] = "stdcall",
1010 [GNU_AK_FASTCALL] = "fastcall",
1011 [GNU_AK_DEPRECATED] = "deprecated",
1012 [GNU_AK_NOINLINE] = "noinline",
1013 [GNU_AK_NORETURN] = "noreturn",
1014 [GNU_AK_NAKED] = "naked",
1015 [GNU_AK_PURE] = "pure",
1016 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1017 [GNU_AK_MALLOC] = "malloc",
1018 [GNU_AK_WEAK] = "weak",
1019 [GNU_AK_CONSTRUCTOR] = "constructor",
1020 [GNU_AK_DESTRUCTOR] = "destructor",
1021 [GNU_AK_NOTHROW] = "nothrow",
1022 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1023 [GNU_AK_COMMON] = "coommon",
1024 [GNU_AK_NOCOMMON] = "nocommon",
1025 [GNU_AK_PACKED] = "packed",
1026 [GNU_AK_SHARED] = "shared",
1027 [GNU_AK_NOTSHARED] = "notshared",
1028 [GNU_AK_USED] = "used",
1029 [GNU_AK_UNUSED] = "unused",
1030 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1031 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1032 [GNU_AK_LONGCALL] = "longcall",
1033 [GNU_AK_SHORTCALL] = "shortcall",
1034 [GNU_AK_LONG_CALL] = "long_call",
1035 [GNU_AK_SHORT_CALL] = "short_call",
1036 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1037 [GNU_AK_INTERRUPT] = "interrupt",
1038 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1039 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1040 [GNU_AK_NESTING] = "nesting",
1041 [GNU_AK_NEAR] = "near",
1042 [GNU_AK_FAR] = "far",
1043 [GNU_AK_SIGNAL] = "signal",
1044 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1045 [GNU_AK_TINY_DATA] = "tiny_data",
1046 [GNU_AK_SAVEALL] = "saveall",
1047 [GNU_AK_FLATTEN] = "flatten",
1048 [GNU_AK_SSEREGPARM] = "sseregparm",
1049 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1050 [GNU_AK_RETURN_TWICE] = "return_twice",
1051 [GNU_AK_MAY_ALIAS] = "may_alias",
1052 [GNU_AK_MS_STRUCT] = "ms_struct",
1053 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1054 [GNU_AK_DLLIMPORT] = "dllimport",
1055 [GNU_AK_DLLEXPORT] = "dllexport",
1056 [GNU_AK_ALIGNED] = "aligned",
1057 [GNU_AK_ALIAS] = "alias",
1058 [GNU_AK_SECTION] = "section",
1059 [GNU_AK_FORMAT] = "format",
1060 [GNU_AK_FORMAT_ARG] = "format_arg",
1061 [GNU_AK_WEAKREF] = "weakref",
1062 [GNU_AK_NONNULL] = "nonnull",
1063 [GNU_AK_TLS_MODEL] = "tls_model",
1064 [GNU_AK_VISIBILITY] = "visibility",
1065 [GNU_AK_REGPARM] = "regparm",
1066 [GNU_AK_MODE] = "mode",
1067 [GNU_AK_MODEL] = "model",
1068 [GNU_AK_TRAP_EXIT] = "trap_exit",
1069 [GNU_AK_SP_SWITCH] = "sp_switch",
1070 [GNU_AK_SENTINEL] = "sentinel"
1074 * compare two string, ignoring double underscores on the second.
1076 static int strcmp_underscore(const char *s1, const char *s2) {
1077 if(s2[0] == '_' && s2[1] == '_') {
1079 size_t l1 = strlen(s1);
1080 if(l1 + 2 != strlen(s2)) {
1084 return strncmp(s1, s2, l1);
1086 return strcmp(s1, s2);
1090 * Allocate a new gnu temporal attribute.
1092 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1093 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1094 attribute->kind = kind;
1095 attribute->next = NULL;
1096 attribute->invalid = false;
1097 attribute->have_arguments = false;
1103 * parse one constant expression argument.
1105 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1106 expression_t *expression;
1107 add_anchor_token(')');
1108 expression = parse_constant_expression();
1109 rem_anchor_token(')');
1114 attribute->invalid = true;
1118 * parse a list of constant expressions arguments.
1120 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1121 expression_t *expression;
1122 add_anchor_token(')');
1123 add_anchor_token(',');
1125 expression = parse_constant_expression();
1126 if(token.type != ',')
1130 rem_anchor_token(',');
1131 rem_anchor_token(')');
1136 attribute->invalid = true;
1140 * parse one string literal argument.
1142 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1145 add_anchor_token('(');
1146 if(token.type != T_STRING_LITERAL) {
1147 parse_error_expected("while parsing attribute directive",
1148 T_STRING_LITERAL, NULL);
1151 *string = parse_string_literals();
1152 rem_anchor_token('(');
1156 attribute->invalid = true;
1160 * parse one tls model.
1162 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1163 static const char *tls_models[] = {
1169 string_t string = { NULL, 0 };
1170 parse_gnu_attribute_string_arg(attribute, &string);
1171 if(string.begin != NULL) {
1172 for(size_t i = 0; i < 4; ++i) {
1173 if(strcmp(tls_models[i], string.begin) == 0) {
1174 attribute->u.value = i;
1179 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1180 attribute->invalid = true;
1184 * parse one tls model.
1186 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1187 static const char *visibilities[] = {
1193 string_t string = { NULL, 0 };
1194 parse_gnu_attribute_string_arg(attribute, &string);
1195 if(string.begin != NULL) {
1196 for(size_t i = 0; i < 4; ++i) {
1197 if(strcmp(visibilities[i], string.begin) == 0) {
1198 attribute->u.value = i;
1203 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1204 attribute->invalid = true;
1208 * parse one (code) model.
1210 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1211 static const char *visibilities[] = {
1216 string_t string = { NULL, 0 };
1217 parse_gnu_attribute_string_arg(attribute, &string);
1218 if(string.begin != NULL) {
1219 for(int i = 0; i < 3; ++i) {
1220 if(strcmp(visibilities[i], string.begin) == 0) {
1221 attribute->u.value = i;
1226 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1227 attribute->invalid = true;
1230 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1232 /* TODO: find out what is allowed here... */
1234 /* at least: byte, word, pointer, list of machine modes
1235 * __XXX___ is interpreted as XXX */
1236 add_anchor_token(')');
1237 expect(T_IDENTIFIER);
1238 rem_anchor_token(')');
1242 attribute->invalid = true;
1246 * parse one interrupt argument.
1248 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1249 static const char *interrupts[] = {
1256 string_t string = { NULL, 0 };
1257 parse_gnu_attribute_string_arg(attribute, &string);
1258 if(string.begin != NULL) {
1259 for(size_t i = 0; i < 5; ++i) {
1260 if(strcmp(interrupts[i], string.begin) == 0) {
1261 attribute->u.value = i;
1266 errorf(HERE, "'%s' is an interrupt", string.begin);
1267 attribute->invalid = true;
1271 * parse ( identifier, const expression, const expression )
1273 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1274 static const char *format_names[] = {
1282 if(token.type != T_IDENTIFIER) {
1283 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1286 const char *name = token.v.symbol->string;
1287 for(i = 0; i < 4; ++i) {
1288 if(strcmp_underscore(format_names[i], name) == 0)
1292 if(warning.attribute)
1293 warningf(HERE, "'%s' is an unrecognized format function type", name);
1298 add_anchor_token(')');
1299 add_anchor_token(',');
1300 parse_constant_expression();
1301 rem_anchor_token(',');
1302 rem_anchor_token('(');
1305 add_anchor_token(')');
1306 parse_constant_expression();
1307 rem_anchor_token('(');
1311 attribute->u.value = true;
1314 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1316 if(!attribute->have_arguments)
1319 /* should have no arguments */
1320 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1321 eat_until_matching_token('(');
1322 /* we have already consumed '(', so we stop before ')', eat it */
1324 attribute->invalid = true;
1328 * Parse one GNU attribute.
1330 * Note that attribute names can be specified WITH or WITHOUT
1331 * double underscores, ie const or __const__.
1333 * The following attributes are parsed without arguments
1358 * no_instrument_function
1359 * warn_unused_result
1376 * externally_visible
1384 * The following attributes are parsed with arguments
1385 * aligned( const expression )
1386 * alias( string literal )
1387 * section( string literal )
1388 * format( identifier, const expression, const expression )
1389 * format_arg( const expression )
1390 * tls_model( string literal )
1391 * visibility( string literal )
1392 * regparm( const expression )
1393 * model( string leteral )
1394 * trap_exit( const expression )
1395 * sp_switch( string literal )
1397 * The following attributes might have arguments
1398 * weak_ref( string literal )
1399 * non_null( const expression // ',' )
1400 * interrupt( string literal )
1401 * sentinel( constant expression )
1403 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1405 gnu_attribute_t *head = *attributes;
1406 gnu_attribute_t *last = *attributes;
1407 decl_modifiers_t modifiers = 0;
1408 gnu_attribute_t *attribute;
1410 eat(T___attribute__);
1414 if(token.type != ')') {
1415 /* find the end of the list */
1417 while(last->next != NULL)
1421 /* non-empty attribute list */
1424 if(token.type == T_const) {
1426 } else if(token.type == T_volatile) {
1428 } else if(token.type == T_cdecl) {
1429 /* __attribute__((cdecl)), WITH ms mode */
1431 } else if(token.type != T_IDENTIFIER) {
1432 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1435 const symbol_t *sym = token.v.symbol;
1440 for(i = 0; i < GNU_AK_LAST; ++i) {
1441 if(strcmp_underscore(gnu_attribute_names[i], name) == 0)
1444 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1447 if(kind == GNU_AK_LAST) {
1448 if(warning.attribute)
1449 warningf(HERE, "'%s' attribute directive ignored", name);
1451 /* skip possible arguments */
1452 if(token.type == '(') {
1453 eat_until_matching_token(')');
1456 /* check for arguments */
1457 attribute = allocate_gnu_attribute(kind);
1458 if(token.type == '(') {
1460 if(token.type == ')') {
1461 /* empty args are allowed */
1464 attribute->have_arguments = true;
1469 case GNU_AK_VOLATILE:
1471 case GNU_AK_STDCALL:
1472 case GNU_AK_FASTCALL:
1473 case GNU_AK_DEPRECATED:
1478 case GNU_AK_NOCOMMON:
1480 case GNU_AK_NOTSHARED:
1483 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1484 case GNU_AK_WARN_UNUSED_RESULT:
1485 case GNU_AK_LONGCALL:
1486 case GNU_AK_SHORTCALL:
1487 case GNU_AK_LONG_CALL:
1488 case GNU_AK_SHORT_CALL:
1489 case GNU_AK_FUNCTION_VECTOR:
1490 case GNU_AK_INTERRUPT_HANDLER:
1491 case GNU_AK_NMI_HANDLER:
1492 case GNU_AK_NESTING:
1496 case GNU_AK_EIGTHBIT_DATA:
1497 case GNU_AK_TINY_DATA:
1498 case GNU_AK_SAVEALL:
1499 case GNU_AK_FLATTEN:
1500 case GNU_AK_SSEREGPARM:
1501 case GNU_AK_EXTERNALLY_VISIBLE:
1502 case GNU_AK_RETURN_TWICE:
1503 case GNU_AK_MAY_ALIAS:
1504 case GNU_AK_MS_STRUCT:
1505 case GNU_AK_GCC_STRUCT:
1506 check_no_argument(attribute, name);
1510 check_no_argument(attribute, name);
1511 modifiers |= DM_PURE;
1514 case GNU_AK_ALWAYS_INLINE:
1515 check_no_argument(attribute, name);
1516 modifiers |= DM_FORCEINLINE;
1519 case GNU_AK_DLLIMPORT:
1520 check_no_argument(attribute, name);
1521 modifiers |= DM_DLLIMPORT;
1524 case GNU_AK_DLLEXPORT:
1525 check_no_argument(attribute, name);
1526 modifiers |= DM_DLLEXPORT;
1530 check_no_argument(attribute, name);
1531 modifiers |= DM_PACKED;
1534 case GNU_AK_NOINLINE:
1535 check_no_argument(attribute, name);
1536 modifiers |= DM_NOINLINE;
1539 case GNU_AK_NORETURN:
1540 check_no_argument(attribute, name);
1541 modifiers |= DM_NORETURN;
1544 case GNU_AK_NOTHROW:
1545 check_no_argument(attribute, name);
1546 modifiers |= DM_NOTHROW;
1549 case GNU_AK_TRANSPARENT_UNION:
1550 check_no_argument(attribute, name);
1551 modifiers |= DM_TRANSPARENT_UNION;
1554 case GNU_AK_CONSTRUCTOR:
1555 check_no_argument(attribute, name);
1556 modifiers |= DM_CONSTRUCTOR;
1559 case GNU_AK_DESTRUCTOR:
1560 check_no_argument(attribute, name);
1561 modifiers |= DM_DESTRUCTOR;
1564 case GNU_AK_ALIGNED:
1565 case GNU_AK_FORMAT_ARG:
1566 case GNU_AK_REGPARM:
1567 case GNU_AK_TRAP_EXIT:
1568 if(!attribute->have_arguments) {
1569 /* should have arguments */
1570 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1571 attribute->invalid = true;
1573 parse_gnu_attribute_const_arg(attribute);
1576 case GNU_AK_SECTION:
1577 case GNU_AK_SP_SWITCH:
1578 if(!attribute->have_arguments) {
1579 /* should have arguments */
1580 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1581 attribute->invalid = true;
1583 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1586 if(!attribute->have_arguments) {
1587 /* should have arguments */
1588 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1589 attribute->invalid = true;
1591 parse_gnu_attribute_format_args(attribute);
1593 case GNU_AK_WEAKREF:
1594 /* may have one string argument */
1595 if(attribute->have_arguments)
1596 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1598 case GNU_AK_NONNULL:
1599 if(attribute->have_arguments)
1600 parse_gnu_attribute_const_arg_list(attribute);
1602 case GNU_AK_TLS_MODEL:
1603 if(!attribute->have_arguments) {
1604 /* should have arguments */
1605 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1607 parse_gnu_attribute_tls_model_arg(attribute);
1609 case GNU_AK_VISIBILITY:
1610 if(!attribute->have_arguments) {
1611 /* should have arguments */
1612 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1614 parse_gnu_attribute_visibility_arg(attribute);
1617 if(!attribute->have_arguments) {
1618 /* should have arguments */
1619 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1621 parse_gnu_attribute_model_arg(attribute);
1625 if(!attribute->have_arguments) {
1626 /* should have arguments */
1627 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1629 parse_gnu_attribute_mode_arg(attribute);
1632 case GNU_AK_INTERRUPT:
1633 /* may have one string argument */
1634 if(attribute->have_arguments)
1635 parse_gnu_attribute_interrupt_arg(attribute);
1637 case GNU_AK_SENTINEL:
1638 /* may have one string argument */
1639 if(attribute->have_arguments)
1640 parse_gnu_attribute_const_arg(attribute);
1643 /* already handled */
1647 if(attribute != NULL) {
1649 last->next = attribute;
1652 head = last = attribute;
1656 if(token.type != ',')
1670 * Parse GNU attributes.
1672 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1674 decl_modifiers_t modifiers = 0;
1677 switch(token.type) {
1678 case T___attribute__: {
1679 modifiers |= parse_gnu_attribute(attributes);
1685 if(token.type != T_STRING_LITERAL) {
1686 parse_error_expected("while parsing assembler attribute",
1687 T_STRING_LITERAL, NULL);
1688 eat_until_matching_token('(');
1691 parse_string_literals();
1696 goto attributes_finished;
1700 attributes_finished:
1705 static designator_t *parse_designation(void)
1707 designator_t *result = NULL;
1708 designator_t *last = NULL;
1711 designator_t *designator;
1712 switch(token.type) {
1714 designator = allocate_ast_zero(sizeof(designator[0]));
1715 designator->source_position = token.source_position;
1717 add_anchor_token(']');
1718 designator->array_index = parse_constant_expression();
1719 rem_anchor_token(']');
1723 designator = allocate_ast_zero(sizeof(designator[0]));
1724 designator->source_position = token.source_position;
1726 if(token.type != T_IDENTIFIER) {
1727 parse_error_expected("while parsing designator",
1728 T_IDENTIFIER, NULL);
1731 designator->symbol = token.v.symbol;
1739 assert(designator != NULL);
1741 last->next = designator;
1743 result = designator;
1751 static initializer_t *initializer_from_string(array_type_t *type,
1752 const string_t *const string)
1754 /* TODO: check len vs. size of array type */
1757 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1758 initializer->string.string = *string;
1763 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1764 wide_string_t *const string)
1766 /* TODO: check len vs. size of array type */
1769 initializer_t *const initializer =
1770 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1771 initializer->wide_string.string = *string;
1777 * Build an initializer from a given expression.
1779 static initializer_t *initializer_from_expression(type_t *orig_type,
1780 expression_t *expression)
1782 /* TODO check that expression is a constant expression */
1784 /* § 6.7.8.14/15 char array may be initialized by string literals */
1785 type_t *type = skip_typeref(orig_type);
1786 type_t *expr_type_orig = expression->base.type;
1787 type_t *expr_type = skip_typeref(expr_type_orig);
1788 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1789 array_type_t *const array_type = &type->array;
1790 type_t *const element_type = skip_typeref(array_type->element_type);
1792 if (element_type->kind == TYPE_ATOMIC) {
1793 atomic_type_kind_t akind = element_type->atomic.akind;
1794 switch (expression->kind) {
1795 case EXPR_STRING_LITERAL:
1796 if (akind == ATOMIC_TYPE_CHAR
1797 || akind == ATOMIC_TYPE_SCHAR
1798 || akind == ATOMIC_TYPE_UCHAR) {
1799 return initializer_from_string(array_type,
1800 &expression->string.value);
1803 case EXPR_WIDE_STRING_LITERAL: {
1804 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1805 if (get_unqualified_type(element_type) == bare_wchar_type) {
1806 return initializer_from_wide_string(array_type,
1807 &expression->wide_string.value);
1817 type_t *const res_type = semantic_assign(type, expression, "initializer",
1818 &expression->base.source_position);
1819 if (res_type == NULL)
1822 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1823 result->value.value = create_implicit_cast(expression, res_type);
1829 * Checks if a given expression can be used as an constant initializer.
1831 static bool is_initializer_constant(const expression_t *expression)
1833 return is_constant_expression(expression)
1834 || is_address_constant(expression);
1838 * Parses an scalar initializer.
1840 * § 6.7.8.11; eat {} without warning
1842 static initializer_t *parse_scalar_initializer(type_t *type,
1843 bool must_be_constant)
1845 /* there might be extra {} hierarchies */
1847 while(token.type == '{') {
1850 warningf(HERE, "extra curly braces around scalar initializer");
1855 expression_t *expression = parse_assignment_expression();
1856 if(must_be_constant && !is_initializer_constant(expression)) {
1857 errorf(&expression->base.source_position,
1858 "Initialisation expression '%E' is not constant\n",
1862 initializer_t *initializer = initializer_from_expression(type, expression);
1864 if(initializer == NULL) {
1865 errorf(&expression->base.source_position,
1866 "expression '%E' (type '%T') doesn't match expected type '%T'",
1867 expression, expression->base.type, type);
1872 bool additional_warning_displayed = false;
1874 if(token.type == ',') {
1877 if(token.type != '}') {
1878 if(!additional_warning_displayed) {
1879 warningf(HERE, "additional elements in scalar initializer");
1880 additional_warning_displayed = true;
1891 * An entry in the type path.
1893 typedef struct type_path_entry_t type_path_entry_t;
1894 struct type_path_entry_t {
1895 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1897 size_t index; /**< For array types: the current index. */
1898 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1903 * A type path expression a position inside compound or array types.
1905 typedef struct type_path_t type_path_t;
1906 struct type_path_t {
1907 type_path_entry_t *path; /**< An flexible array containing the current path. */
1908 type_t *top_type; /**< type of the element the path points */
1909 size_t max_index; /**< largest index in outermost array */
1913 * Prints a type path for debugging.
1915 static __attribute__((unused)) void debug_print_type_path(
1916 const type_path_t *path)
1918 size_t len = ARR_LEN(path->path);
1920 for(size_t i = 0; i < len; ++i) {
1921 const type_path_entry_t *entry = & path->path[i];
1923 type_t *type = skip_typeref(entry->type);
1924 if(is_type_compound(type)) {
1925 /* in gcc mode structs can have no members */
1926 if(entry->v.compound_entry == NULL) {
1930 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1931 } else if(is_type_array(type)) {
1932 fprintf(stderr, "[%zd]", entry->v.index);
1934 fprintf(stderr, "-INVALID-");
1937 if(path->top_type != NULL) {
1938 fprintf(stderr, " (");
1939 print_type(path->top_type);
1940 fprintf(stderr, ")");
1945 * Return the top type path entry, ie. in a path
1946 * (type).a.b returns the b.
1948 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1950 size_t len = ARR_LEN(path->path);
1952 return &path->path[len-1];
1956 * Enlarge the type path by an (empty) element.
1958 static type_path_entry_t *append_to_type_path(type_path_t *path)
1960 size_t len = ARR_LEN(path->path);
1961 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1963 type_path_entry_t *result = & path->path[len];
1964 memset(result, 0, sizeof(result[0]));
1969 * Descending into a sub-type. Enter the scope of the current
1972 static void descend_into_subtype(type_path_t *path)
1974 type_t *orig_top_type = path->top_type;
1975 type_t *top_type = skip_typeref(orig_top_type);
1977 assert(is_type_compound(top_type) || is_type_array(top_type));
1979 type_path_entry_t *top = append_to_type_path(path);
1980 top->type = top_type;
1982 if(is_type_compound(top_type)) {
1983 declaration_t *declaration = top_type->compound.declaration;
1984 declaration_t *entry = declaration->scope.declarations;
1985 top->v.compound_entry = entry;
1988 path->top_type = entry->type;
1990 path->top_type = NULL;
1993 assert(is_type_array(top_type));
1996 path->top_type = top_type->array.element_type;
2001 * Pop an entry from the given type path, ie. returning from
2002 * (type).a.b to (type).a
2004 static void ascend_from_subtype(type_path_t *path)
2006 type_path_entry_t *top = get_type_path_top(path);
2008 path->top_type = top->type;
2010 size_t len = ARR_LEN(path->path);
2011 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2015 * Pop entries from the given type path until the given
2016 * path level is reached.
2018 static void ascend_to(type_path_t *path, size_t top_path_level)
2020 size_t len = ARR_LEN(path->path);
2022 while(len > top_path_level) {
2023 ascend_from_subtype(path);
2024 len = ARR_LEN(path->path);
2028 static bool walk_designator(type_path_t *path, const designator_t *designator,
2029 bool used_in_offsetof)
2031 for( ; designator != NULL; designator = designator->next) {
2032 type_path_entry_t *top = get_type_path_top(path);
2033 type_t *orig_type = top->type;
2035 type_t *type = skip_typeref(orig_type);
2037 if(designator->symbol != NULL) {
2038 symbol_t *symbol = designator->symbol;
2039 if(!is_type_compound(type)) {
2040 if(is_type_valid(type)) {
2041 errorf(&designator->source_position,
2042 "'.%Y' designator used for non-compound type '%T'",
2048 declaration_t *declaration = type->compound.declaration;
2049 declaration_t *iter = declaration->scope.declarations;
2050 for( ; iter != NULL; iter = iter->next) {
2051 if(iter->symbol == symbol) {
2056 errorf(&designator->source_position,
2057 "'%T' has no member named '%Y'", orig_type, symbol);
2060 if(used_in_offsetof) {
2061 type_t *real_type = skip_typeref(iter->type);
2062 if(real_type->kind == TYPE_BITFIELD) {
2063 errorf(&designator->source_position,
2064 "offsetof designator '%Y' may not specify bitfield",
2070 top->type = orig_type;
2071 top->v.compound_entry = iter;
2072 orig_type = iter->type;
2074 expression_t *array_index = designator->array_index;
2075 assert(designator->array_index != NULL);
2077 if(!is_type_array(type)) {
2078 if(is_type_valid(type)) {
2079 errorf(&designator->source_position,
2080 "[%E] designator used for non-array type '%T'",
2081 array_index, orig_type);
2085 if(!is_type_valid(array_index->base.type)) {
2089 long index = fold_constant(array_index);
2090 if(!used_in_offsetof) {
2092 errorf(&designator->source_position,
2093 "array index [%E] must be positive", array_index);
2096 if(type->array.size_constant == true) {
2097 long array_size = type->array.size;
2098 if(index >= array_size) {
2099 errorf(&designator->source_position,
2100 "designator [%E] (%d) exceeds array size %d",
2101 array_index, index, array_size);
2107 top->type = orig_type;
2108 top->v.index = (size_t) index;
2109 orig_type = type->array.element_type;
2111 path->top_type = orig_type;
2113 if(designator->next != NULL) {
2114 descend_into_subtype(path);
2123 static void advance_current_object(type_path_t *path, size_t top_path_level)
2125 type_path_entry_t *top = get_type_path_top(path);
2127 type_t *type = skip_typeref(top->type);
2128 if(is_type_union(type)) {
2129 /* in unions only the first element is initialized */
2130 top->v.compound_entry = NULL;
2131 } else if(is_type_struct(type)) {
2132 declaration_t *entry = top->v.compound_entry;
2134 entry = entry->next;
2135 top->v.compound_entry = entry;
2137 path->top_type = entry->type;
2141 assert(is_type_array(type));
2145 if(!type->array.size_constant || top->v.index < type->array.size) {
2150 /* we're past the last member of the current sub-aggregate, try if we
2151 * can ascend in the type hierarchy and continue with another subobject */
2152 size_t len = ARR_LEN(path->path);
2154 if(len > top_path_level) {
2155 ascend_from_subtype(path);
2156 advance_current_object(path, top_path_level);
2158 path->top_type = NULL;
2163 * skip until token is found.
2165 static void skip_until(int type) {
2166 while(token.type != type) {
2167 if(token.type == T_EOF)
2174 * skip any {...} blocks until a closing bracket is reached.
2176 static void skip_initializers(void)
2178 if(token.type == '{')
2181 while(token.type != '}') {
2182 if(token.type == T_EOF)
2184 if(token.type == '{') {
2192 static initializer_t *create_empty_initializer(void)
2194 static initializer_t empty_initializer
2195 = { .list = { { INITIALIZER_LIST }, 0 } };
2196 return &empty_initializer;
2200 * Parse a part of an initialiser for a struct or union,
2202 static initializer_t *parse_sub_initializer(type_path_t *path,
2203 type_t *outer_type, size_t top_path_level,
2204 parse_initializer_env_t *env)
2206 if(token.type == '}') {
2207 /* empty initializer */
2208 return create_empty_initializer();
2211 type_t *orig_type = path->top_type;
2212 type_t *type = NULL;
2214 if (orig_type == NULL) {
2215 /* We are initializing an empty compound. */
2217 type = skip_typeref(orig_type);
2219 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2220 * initializers in this case. */
2221 if(!is_type_valid(type)) {
2222 skip_initializers();
2223 return create_empty_initializer();
2227 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2230 designator_t *designator = NULL;
2231 if(token.type == '.' || token.type == '[') {
2232 designator = parse_designation();
2234 /* reset path to toplevel, evaluate designator from there */
2235 ascend_to(path, top_path_level);
2236 if(!walk_designator(path, designator, false)) {
2237 /* can't continue after designation error */
2241 initializer_t *designator_initializer
2242 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2243 designator_initializer->designator.designator = designator;
2244 ARR_APP1(initializer_t*, initializers, designator_initializer);
2246 orig_type = path->top_type;
2247 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2252 if(token.type == '{') {
2253 if(type != NULL && is_type_scalar(type)) {
2254 sub = parse_scalar_initializer(type, env->must_be_constant);
2258 if (env->declaration != NULL)
2259 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2260 env->declaration->symbol);
2262 errorf(HERE, "extra brace group at end of initializer");
2264 descend_into_subtype(path);
2266 add_anchor_token('}');
2267 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2269 rem_anchor_token('}');
2272 ascend_from_subtype(path);
2276 goto error_parse_next;
2280 /* must be an expression */
2281 expression_t *expression = parse_assignment_expression();
2283 if(env->must_be_constant && !is_initializer_constant(expression)) {
2284 errorf(&expression->base.source_position,
2285 "Initialisation expression '%E' is not constant\n",
2290 /* we are already outside, ... */
2294 /* handle { "string" } special case */
2295 if((expression->kind == EXPR_STRING_LITERAL
2296 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2297 && outer_type != NULL) {
2298 sub = initializer_from_expression(outer_type, expression);
2300 if(token.type == ',') {
2303 if(token.type != '}') {
2304 warningf(HERE, "excessive elements in initializer for type '%T'",
2307 /* TODO: eat , ... */
2312 /* descend into subtypes until expression matches type */
2314 orig_type = path->top_type;
2315 type = skip_typeref(orig_type);
2317 sub = initializer_from_expression(orig_type, expression);
2321 if(!is_type_valid(type)) {
2324 if(is_type_scalar(type)) {
2325 errorf(&expression->base.source_position,
2326 "expression '%E' doesn't match expected type '%T'",
2327 expression, orig_type);
2331 descend_into_subtype(path);
2335 /* update largest index of top array */
2336 const type_path_entry_t *first = &path->path[0];
2337 type_t *first_type = first->type;
2338 first_type = skip_typeref(first_type);
2339 if(is_type_array(first_type)) {
2340 size_t index = first->v.index;
2341 if(index > path->max_index)
2342 path->max_index = index;
2346 /* append to initializers list */
2347 ARR_APP1(initializer_t*, initializers, sub);
2350 if(env->declaration != NULL)
2351 warningf(HERE, "excess elements in struct initializer for '%Y'",
2352 env->declaration->symbol);
2354 warningf(HERE, "excess elements in struct initializer");
2358 if(token.type == '}') {
2362 if(token.type == '}') {
2367 /* advance to the next declaration if we are not at the end */
2368 advance_current_object(path, top_path_level);
2369 orig_type = path->top_type;
2370 if(orig_type != NULL)
2371 type = skip_typeref(orig_type);
2377 size_t len = ARR_LEN(initializers);
2378 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2379 initializer_t *result = allocate_ast_zero(size);
2380 result->kind = INITIALIZER_LIST;
2381 result->list.len = len;
2382 memcpy(&result->list.initializers, initializers,
2383 len * sizeof(initializers[0]));
2385 DEL_ARR_F(initializers);
2386 ascend_to(path, top_path_level+1);
2391 skip_initializers();
2392 DEL_ARR_F(initializers);
2393 ascend_to(path, top_path_level+1);
2398 * Parses an initializer. Parsers either a compound literal
2399 * (env->declaration == NULL) or an initializer of a declaration.
2401 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2403 type_t *type = skip_typeref(env->type);
2404 initializer_t *result = NULL;
2407 if(is_type_scalar(type)) {
2408 result = parse_scalar_initializer(type, env->must_be_constant);
2409 } else if(token.type == '{') {
2413 memset(&path, 0, sizeof(path));
2414 path.top_type = env->type;
2415 path.path = NEW_ARR_F(type_path_entry_t, 0);
2417 descend_into_subtype(&path);
2419 add_anchor_token('}');
2420 result = parse_sub_initializer(&path, env->type, 1, env);
2421 rem_anchor_token('}');
2423 max_index = path.max_index;
2424 DEL_ARR_F(path.path);
2428 /* parse_scalar_initializer() also works in this case: we simply
2429 * have an expression without {} around it */
2430 result = parse_scalar_initializer(type, env->must_be_constant);
2433 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2434 * the array type size */
2435 if(is_type_array(type) && type->array.size_expression == NULL
2436 && result != NULL) {
2438 switch (result->kind) {
2439 case INITIALIZER_LIST:
2440 size = max_index + 1;
2443 case INITIALIZER_STRING:
2444 size = result->string.string.size;
2447 case INITIALIZER_WIDE_STRING:
2448 size = result->wide_string.string.size;
2451 case INITIALIZER_DESIGNATOR:
2452 case INITIALIZER_VALUE:
2453 /* can happen for parse errors */
2458 internal_errorf(HERE, "invalid initializer type");
2461 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2462 cnst->base.type = type_size_t;
2463 cnst->conste.v.int_value = size;
2465 type_t *new_type = duplicate_type(type);
2467 new_type->array.size_expression = cnst;
2468 new_type->array.size_constant = true;
2469 new_type->array.size = size;
2470 env->type = new_type;
2478 static declaration_t *append_declaration(declaration_t *declaration);
2480 static declaration_t *parse_compound_type_specifier(bool is_struct)
2482 gnu_attribute_t *attributes = NULL;
2483 decl_modifiers_t modifiers = 0;
2490 symbol_t *symbol = NULL;
2491 declaration_t *declaration = NULL;
2493 if (token.type == T___attribute__) {
2494 modifiers |= parse_attributes(&attributes);
2497 if(token.type == T_IDENTIFIER) {
2498 symbol = token.v.symbol;
2502 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2504 declaration = get_declaration(symbol, NAMESPACE_UNION);
2506 } else if(token.type != '{') {
2508 parse_error_expected("while parsing struct type specifier",
2509 T_IDENTIFIER, '{', NULL);
2511 parse_error_expected("while parsing union type specifier",
2512 T_IDENTIFIER, '{', NULL);
2518 if(declaration == NULL) {
2519 declaration = allocate_declaration_zero();
2520 declaration->namespc =
2521 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2522 declaration->source_position = token.source_position;
2523 declaration->symbol = symbol;
2524 declaration->parent_scope = scope;
2525 if (symbol != NULL) {
2526 environment_push(declaration);
2528 append_declaration(declaration);
2531 if(token.type == '{') {
2532 if (declaration->init.complete) {
2533 assert(symbol != NULL);
2534 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2535 is_struct ? "struct" : "union", symbol,
2536 &declaration->source_position);
2537 declaration->scope.declarations = NULL;
2539 declaration->init.complete = true;
2541 parse_compound_type_entries(declaration);
2542 modifiers |= parse_attributes(&attributes);
2545 declaration->modifiers |= modifiers;
2549 static void parse_enum_entries(type_t *const enum_type)
2553 if(token.type == '}') {
2555 errorf(HERE, "empty enum not allowed");
2559 add_anchor_token('}');
2561 if(token.type != T_IDENTIFIER) {
2562 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2564 rem_anchor_token('}');
2568 declaration_t *const entry = allocate_declaration_zero();
2569 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2570 entry->type = enum_type;
2571 entry->symbol = token.v.symbol;
2572 entry->source_position = token.source_position;
2575 if(token.type == '=') {
2577 expression_t *value = parse_constant_expression();
2579 value = create_implicit_cast(value, enum_type);
2580 entry->init.enum_value = value;
2585 record_declaration(entry);
2587 if(token.type != ',')
2590 } while(token.type != '}');
2591 rem_anchor_token('}');
2599 static type_t *parse_enum_specifier(void)
2601 gnu_attribute_t *attributes = NULL;
2602 declaration_t *declaration;
2606 if(token.type == T_IDENTIFIER) {
2607 symbol = token.v.symbol;
2610 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2611 } else if(token.type != '{') {
2612 parse_error_expected("while parsing enum type specifier",
2613 T_IDENTIFIER, '{', NULL);
2620 if(declaration == NULL) {
2621 declaration = allocate_declaration_zero();
2622 declaration->namespc = NAMESPACE_ENUM;
2623 declaration->source_position = token.source_position;
2624 declaration->symbol = symbol;
2625 declaration->parent_scope = scope;
2628 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2629 type->enumt.declaration = declaration;
2631 if(token.type == '{') {
2632 if(declaration->init.complete) {
2633 errorf(HERE, "multiple definitions of enum %Y", symbol);
2635 if (symbol != NULL) {
2636 environment_push(declaration);
2638 append_declaration(declaration);
2639 declaration->init.complete = true;
2641 parse_enum_entries(type);
2642 parse_attributes(&attributes);
2649 * if a symbol is a typedef to another type, return true
2651 static bool is_typedef_symbol(symbol_t *symbol)
2653 const declaration_t *const declaration =
2654 get_declaration(symbol, NAMESPACE_NORMAL);
2656 declaration != NULL &&
2657 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2660 static type_t *parse_typeof(void)
2667 add_anchor_token(')');
2669 expression_t *expression = NULL;
2672 switch(token.type) {
2673 case T___extension__:
2674 /* this can be a prefix to a typename or an expression */
2675 /* we simply eat it now. */
2678 } while(token.type == T___extension__);
2682 if(is_typedef_symbol(token.v.symbol)) {
2683 type = parse_typename();
2685 expression = parse_expression();
2686 type = expression->base.type;
2691 type = parse_typename();
2695 expression = parse_expression();
2696 type = expression->base.type;
2700 rem_anchor_token(')');
2703 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2704 typeof_type->typeoft.expression = expression;
2705 typeof_type->typeoft.typeof_type = type;
2713 SPECIFIER_SIGNED = 1 << 0,
2714 SPECIFIER_UNSIGNED = 1 << 1,
2715 SPECIFIER_LONG = 1 << 2,
2716 SPECIFIER_INT = 1 << 3,
2717 SPECIFIER_DOUBLE = 1 << 4,
2718 SPECIFIER_CHAR = 1 << 5,
2719 SPECIFIER_SHORT = 1 << 6,
2720 SPECIFIER_LONG_LONG = 1 << 7,
2721 SPECIFIER_FLOAT = 1 << 8,
2722 SPECIFIER_BOOL = 1 << 9,
2723 SPECIFIER_VOID = 1 << 10,
2724 SPECIFIER_INT8 = 1 << 11,
2725 SPECIFIER_INT16 = 1 << 12,
2726 SPECIFIER_INT32 = 1 << 13,
2727 SPECIFIER_INT64 = 1 << 14,
2728 SPECIFIER_INT128 = 1 << 15,
2729 SPECIFIER_COMPLEX = 1 << 16,
2730 SPECIFIER_IMAGINARY = 1 << 17,
2733 static type_t *create_builtin_type(symbol_t *const symbol,
2734 type_t *const real_type)
2736 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2737 type->builtin.symbol = symbol;
2738 type->builtin.real_type = real_type;
2740 type_t *result = typehash_insert(type);
2741 if(type != result) {
2748 static type_t *get_typedef_type(symbol_t *symbol)
2750 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2751 if(declaration == NULL ||
2752 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2755 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2756 type->typedeft.declaration = declaration;
2762 * check for the allowed MS alignment values.
2764 static bool check_elignment_value(long long intvalue) {
2765 if(intvalue < 1 || intvalue > 8192) {
2766 errorf(HERE, "illegal alignment value");
2769 unsigned v = (unsigned)intvalue;
2770 for(unsigned i = 1; i <= 8192; i += i) {
2774 errorf(HERE, "alignment must be power of two");
2778 #define DET_MOD(name, tag) do { \
2779 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2780 *modifiers |= tag; \
2783 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2785 decl_modifiers_t *modifiers = &specifiers->modifiers;
2788 if(token.type == T_restrict) {
2790 DET_MOD(restrict, DM_RESTRICT);
2792 } else if(token.type != T_IDENTIFIER)
2794 symbol_t *symbol = token.v.symbol;
2795 if(symbol == sym_align) {
2798 if(token.type != T_INTEGER)
2800 if(check_elignment_value(token.v.intvalue)) {
2801 if(specifiers->alignment != 0)
2802 warningf(HERE, "align used more than once");
2803 specifiers->alignment = (unsigned char)token.v.intvalue;
2807 } else if(symbol == sym_allocate) {
2810 if(token.type != T_IDENTIFIER)
2812 (void)token.v.symbol;
2814 } else if(symbol == sym_dllimport) {
2816 DET_MOD(dllimport, DM_DLLIMPORT);
2817 } else if(symbol == sym_dllexport) {
2819 DET_MOD(dllexport, DM_DLLEXPORT);
2820 } else if(symbol == sym_thread) {
2822 DET_MOD(thread, DM_THREAD);
2823 } else if(symbol == sym_naked) {
2825 DET_MOD(naked, DM_NAKED);
2826 } else if(symbol == sym_noinline) {
2828 DET_MOD(noinline, DM_NOINLINE);
2829 } else if(symbol == sym_noreturn) {
2831 DET_MOD(noreturn, DM_NORETURN);
2832 } else if(symbol == sym_nothrow) {
2834 DET_MOD(nothrow, DM_NOTHROW);
2835 } else if(symbol == sym_novtable) {
2837 DET_MOD(novtable, DM_NOVTABLE);
2838 } else if(symbol == sym_property) {
2842 bool is_get = false;
2843 if(token.type != T_IDENTIFIER)
2845 if(token.v.symbol == sym_get) {
2847 } else if(token.v.symbol == sym_put) {
2849 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2854 if(token.type != T_IDENTIFIER)
2857 if(specifiers->get_property_sym != NULL) {
2858 errorf(HERE, "get property name already specified");
2860 specifiers->get_property_sym = token.v.symbol;
2863 if(specifiers->put_property_sym != NULL) {
2864 errorf(HERE, "put property name already specified");
2866 specifiers->put_property_sym = token.v.symbol;
2870 if(token.type == ',') {
2877 } else if(symbol == sym_selectany) {
2879 DET_MOD(selectany, DM_SELECTANY);
2880 } else if(symbol == sym_uuid) {
2883 if(token.type != T_STRING_LITERAL)
2887 } else if(symbol == sym_deprecated) {
2889 if(specifiers->deprecated != 0)
2890 warningf(HERE, "deprecated used more than once");
2891 specifiers->deprecated = 1;
2892 if(token.type == '(') {
2894 if(token.type == T_STRING_LITERAL) {
2895 specifiers->deprecated_string = token.v.string.begin;
2898 errorf(HERE, "string literal expected");
2902 } else if(symbol == sym_noalias) {
2904 DET_MOD(noalias, DM_NOALIAS);
2906 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2908 if(token.type == '(')
2912 if (token.type == ',')
2919 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2921 type_t *type = NULL;
2922 unsigned type_qualifiers = 0;
2923 unsigned type_specifiers = 0;
2926 specifiers->source_position = token.source_position;
2929 switch(token.type) {
2932 #define MATCH_STORAGE_CLASS(token, class) \
2934 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2935 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2937 specifiers->declared_storage_class = class; \
2941 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2942 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2943 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2944 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2945 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2950 add_anchor_token(')');
2951 parse_microsoft_extended_decl_modifier(specifiers);
2952 rem_anchor_token(')');
2957 switch (specifiers->declared_storage_class) {
2958 case STORAGE_CLASS_NONE:
2959 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2962 case STORAGE_CLASS_EXTERN:
2963 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2966 case STORAGE_CLASS_STATIC:
2967 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2971 errorf(HERE, "multiple storage classes in declaration specifiers");
2977 /* type qualifiers */
2978 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2980 type_qualifiers |= qualifier; \
2984 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2985 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2986 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2987 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2988 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2989 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2990 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2991 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2993 case T___extension__:
2998 /* type specifiers */
2999 #define MATCH_SPECIFIER(token, specifier, name) \
3002 if(type_specifiers & specifier) { \
3003 errorf(HERE, "multiple " name " type specifiers given"); \
3005 type_specifiers |= specifier; \
3009 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3010 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3011 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3012 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3013 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3014 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3015 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3016 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3017 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3018 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3019 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3020 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3021 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3022 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3023 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3024 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3026 case T__forceinline:
3027 /* only in microsoft mode */
3028 specifiers->modifiers |= DM_FORCEINLINE;
3032 specifiers->is_inline = true;
3037 if(type_specifiers & SPECIFIER_LONG_LONG) {
3038 errorf(HERE, "multiple type specifiers given");
3039 } else if(type_specifiers & SPECIFIER_LONG) {
3040 type_specifiers |= SPECIFIER_LONG_LONG;
3042 type_specifiers |= SPECIFIER_LONG;
3047 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3049 type->compound.declaration = parse_compound_type_specifier(true);
3053 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3055 type->compound.declaration = parse_compound_type_specifier(false);
3059 type = parse_enum_specifier();
3062 type = parse_typeof();
3064 case T___builtin_va_list:
3065 type = duplicate_type(type_valist);
3069 case T___attribute__:
3070 specifiers->modifiers
3071 |= parse_attributes(&specifiers->gnu_attributes);
3074 case T_IDENTIFIER: {
3075 /* only parse identifier if we haven't found a type yet */
3076 if(type != NULL || type_specifiers != 0)
3077 goto finish_specifiers;
3079 type_t *typedef_type = get_typedef_type(token.v.symbol);
3081 if(typedef_type == NULL)
3082 goto finish_specifiers;
3085 type = typedef_type;
3089 /* function specifier */
3091 goto finish_specifiers;
3098 atomic_type_kind_t atomic_type;
3100 /* match valid basic types */
3101 switch(type_specifiers) {
3102 case SPECIFIER_VOID:
3103 atomic_type = ATOMIC_TYPE_VOID;
3105 case SPECIFIER_CHAR:
3106 atomic_type = ATOMIC_TYPE_CHAR;
3108 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3109 atomic_type = ATOMIC_TYPE_SCHAR;
3111 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3112 atomic_type = ATOMIC_TYPE_UCHAR;
3114 case SPECIFIER_SHORT:
3115 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3116 case SPECIFIER_SHORT | SPECIFIER_INT:
3117 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3118 atomic_type = ATOMIC_TYPE_SHORT;
3120 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3121 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3122 atomic_type = ATOMIC_TYPE_USHORT;
3125 case SPECIFIER_SIGNED:
3126 case SPECIFIER_SIGNED | SPECIFIER_INT:
3127 atomic_type = ATOMIC_TYPE_INT;
3129 case SPECIFIER_UNSIGNED:
3130 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3131 atomic_type = ATOMIC_TYPE_UINT;
3133 case SPECIFIER_LONG:
3134 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3135 case SPECIFIER_LONG | SPECIFIER_INT:
3136 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3137 atomic_type = ATOMIC_TYPE_LONG;
3139 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3140 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3141 atomic_type = ATOMIC_TYPE_ULONG;
3143 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3144 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3145 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3146 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3148 atomic_type = ATOMIC_TYPE_LONGLONG;
3150 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3151 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3153 atomic_type = ATOMIC_TYPE_ULONGLONG;
3156 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3157 atomic_type = unsigned_int8_type_kind;
3160 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3161 atomic_type = unsigned_int16_type_kind;
3164 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3165 atomic_type = unsigned_int32_type_kind;
3168 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3169 atomic_type = unsigned_int64_type_kind;
3172 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3173 atomic_type = unsigned_int128_type_kind;
3176 case SPECIFIER_INT8:
3177 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3178 atomic_type = int8_type_kind;
3181 case SPECIFIER_INT16:
3182 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3183 atomic_type = int16_type_kind;
3186 case SPECIFIER_INT32:
3187 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3188 atomic_type = int32_type_kind;
3191 case SPECIFIER_INT64:
3192 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3193 atomic_type = int64_type_kind;
3196 case SPECIFIER_INT128:
3197 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3198 atomic_type = int128_type_kind;
3201 case SPECIFIER_FLOAT:
3202 atomic_type = ATOMIC_TYPE_FLOAT;
3204 case SPECIFIER_DOUBLE:
3205 atomic_type = ATOMIC_TYPE_DOUBLE;
3207 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3208 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3210 case SPECIFIER_BOOL:
3211 atomic_type = ATOMIC_TYPE_BOOL;
3213 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3214 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3215 atomic_type = ATOMIC_TYPE_FLOAT;
3217 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3218 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3219 atomic_type = ATOMIC_TYPE_DOUBLE;
3221 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3222 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3223 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3226 /* invalid specifier combination, give an error message */
3227 if(type_specifiers == 0) {
3228 if (! strict_mode) {
3229 if (warning.implicit_int) {
3230 warningf(HERE, "no type specifiers in declaration, using 'int'");
3232 atomic_type = ATOMIC_TYPE_INT;
3235 errorf(HERE, "no type specifiers given in declaration");
3237 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3238 (type_specifiers & SPECIFIER_UNSIGNED)) {
3239 errorf(HERE, "signed and unsigned specifiers gives");
3240 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3241 errorf(HERE, "only integer types can be signed or unsigned");
3243 errorf(HERE, "multiple datatypes in declaration");
3245 atomic_type = ATOMIC_TYPE_INVALID;
3248 if(type_specifiers & SPECIFIER_COMPLEX &&
3249 atomic_type != ATOMIC_TYPE_INVALID) {
3250 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3251 type->complex.akind = atomic_type;
3252 } else if(type_specifiers & SPECIFIER_IMAGINARY &&
3253 atomic_type != ATOMIC_TYPE_INVALID) {
3254 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3255 type->imaginary.akind = atomic_type;
3257 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3258 type->atomic.akind = atomic_type;
3262 if(type_specifiers != 0) {
3263 errorf(HERE, "multiple datatypes in declaration");
3267 type->base.qualifiers = type_qualifiers;
3268 /* FIXME: check type qualifiers here */
3270 type_t *result = typehash_insert(type);
3271 if(newtype && result != type) {
3275 specifiers->type = result;
3280 static type_qualifiers_t parse_type_qualifiers(void)
3282 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3285 switch(token.type) {
3286 /* type qualifiers */
3287 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3288 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3289 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3290 /* microsoft extended type modifiers */
3291 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3292 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3293 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3294 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3295 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3298 return type_qualifiers;
3303 static declaration_t *parse_identifier_list(void)
3305 declaration_t *declarations = NULL;
3306 declaration_t *last_declaration = NULL;
3308 declaration_t *const declaration = allocate_declaration_zero();
3309 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3310 declaration->source_position = token.source_position;
3311 declaration->symbol = token.v.symbol;
3314 if(last_declaration != NULL) {
3315 last_declaration->next = declaration;
3317 declarations = declaration;
3319 last_declaration = declaration;
3321 if (token.type != ',') {
3325 } while(token.type == T_IDENTIFIER);
3327 return declarations;
3330 static void semantic_parameter(declaration_t *declaration)
3332 /* TODO: improve error messages */
3334 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3335 errorf(HERE, "typedef not allowed in parameter list");
3336 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3337 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3338 errorf(HERE, "parameter may only have none or register storage class");
3341 type_t *const orig_type = declaration->type;
3342 type_t * type = skip_typeref(orig_type);
3344 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3345 * into a pointer. § 6.7.5.3 (7) */
3346 if (is_type_array(type)) {
3347 type_t *const element_type = type->array.element_type;
3349 type = make_pointer_type(element_type, type->base.qualifiers);
3351 declaration->type = type;
3354 if(is_type_incomplete(type)) {
3355 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3356 orig_type, declaration->symbol);
3360 static declaration_t *parse_parameter(void)
3362 declaration_specifiers_t specifiers;
3363 memset(&specifiers, 0, sizeof(specifiers));
3365 parse_declaration_specifiers(&specifiers);
3367 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3369 semantic_parameter(declaration);
3374 static declaration_t *parse_parameters(function_type_t *type)
3376 declaration_t *declarations = NULL;
3379 add_anchor_token(')');
3380 int saved_comma_state = save_and_reset_anchor_state(',');
3382 if(token.type == T_IDENTIFIER) {
3383 symbol_t *symbol = token.v.symbol;
3384 if(!is_typedef_symbol(symbol)) {
3385 type->kr_style_parameters = true;
3386 declarations = parse_identifier_list();
3387 goto parameters_finished;
3391 if(token.type == ')') {
3392 type->unspecified_parameters = 1;
3393 goto parameters_finished;
3395 if(token.type == T_void && look_ahead(1)->type == ')') {
3397 goto parameters_finished;
3400 declaration_t *declaration;
3401 declaration_t *last_declaration = NULL;
3402 function_parameter_t *parameter;
3403 function_parameter_t *last_parameter = NULL;
3406 switch(token.type) {
3410 goto parameters_finished;
3413 case T___extension__:
3415 declaration = parse_parameter();
3417 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3418 memset(parameter, 0, sizeof(parameter[0]));
3419 parameter->type = declaration->type;
3421 if(last_parameter != NULL) {
3422 last_declaration->next = declaration;
3423 last_parameter->next = parameter;
3425 type->parameters = parameter;
3426 declarations = declaration;
3428 last_parameter = parameter;
3429 last_declaration = declaration;
3433 goto parameters_finished;
3435 if (token.type != ',') {
3436 goto parameters_finished;
3442 parameters_finished:
3443 rem_anchor_token(')');
3446 restore_anchor_state(',', saved_comma_state);
3447 return declarations;
3450 restore_anchor_state(',', saved_comma_state);
3459 } construct_type_kind_t;
3461 typedef struct construct_type_t construct_type_t;
3462 struct construct_type_t {
3463 construct_type_kind_t kind;
3464 construct_type_t *next;
3467 typedef struct parsed_pointer_t parsed_pointer_t;
3468 struct parsed_pointer_t {
3469 construct_type_t construct_type;
3470 type_qualifiers_t type_qualifiers;
3473 typedef struct construct_function_type_t construct_function_type_t;
3474 struct construct_function_type_t {
3475 construct_type_t construct_type;
3476 type_t *function_type;
3479 typedef struct parsed_array_t parsed_array_t;
3480 struct parsed_array_t {
3481 construct_type_t construct_type;
3482 type_qualifiers_t type_qualifiers;
3488 typedef struct construct_base_type_t construct_base_type_t;
3489 struct construct_base_type_t {
3490 construct_type_t construct_type;
3494 static construct_type_t *parse_pointer_declarator(void)
3498 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3499 memset(pointer, 0, sizeof(pointer[0]));
3500 pointer->construct_type.kind = CONSTRUCT_POINTER;
3501 pointer->type_qualifiers = parse_type_qualifiers();
3503 return (construct_type_t*) pointer;
3506 static construct_type_t *parse_array_declarator(void)
3509 add_anchor_token(']');
3511 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3512 memset(array, 0, sizeof(array[0]));
3513 array->construct_type.kind = CONSTRUCT_ARRAY;
3515 if(token.type == T_static) {
3516 array->is_static = true;
3520 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3521 if(type_qualifiers != 0) {
3522 if(token.type == T_static) {
3523 array->is_static = true;
3527 array->type_qualifiers = type_qualifiers;
3529 if(token.type == '*' && look_ahead(1)->type == ']') {
3530 array->is_variable = true;
3532 } else if(token.type != ']') {
3533 array->size = parse_assignment_expression();
3536 rem_anchor_token(']');
3539 return (construct_type_t*) array;
3544 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3547 if(declaration != NULL) {
3548 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3550 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3553 declaration_t *parameters = parse_parameters(&type->function);
3554 if(declaration != NULL) {
3555 declaration->scope.declarations = parameters;
3558 construct_function_type_t *construct_function_type =
3559 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3560 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3561 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3562 construct_function_type->function_type = type;
3564 return (construct_type_t*) construct_function_type;
3567 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3568 bool may_be_abstract)
3570 /* construct a single linked list of construct_type_t's which describe
3571 * how to construct the final declarator type */
3572 construct_type_t *first = NULL;
3573 construct_type_t *last = NULL;
3574 gnu_attribute_t *attributes = NULL;
3577 while(token.type == '*') {
3578 construct_type_t *type = parse_pointer_declarator();
3589 /* TODO: find out if this is correct */
3590 decl_modifiers_t modifiers = parse_attributes(&attributes);
3591 if (declaration != NULL)
3592 declaration->modifiers |= modifiers;
3594 construct_type_t *inner_types = NULL;
3596 switch(token.type) {
3598 if(declaration == NULL) {
3599 errorf(HERE, "no identifier expected in typename");
3601 declaration->symbol = token.v.symbol;
3602 declaration->source_position = token.source_position;
3608 add_anchor_token(')');
3609 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3610 rem_anchor_token(')');
3616 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3617 /* avoid a loop in the outermost scope, because eat_statement doesn't
3619 if(token.type == '}' && current_function == NULL) {
3627 construct_type_t *p = last;
3630 construct_type_t *type;
3631 switch(token.type) {
3633 type = parse_function_declarator(declaration);
3636 type = parse_array_declarator();
3639 goto declarator_finished;
3642 /* insert in the middle of the list (behind p) */
3644 type->next = p->next;
3655 declarator_finished:
3656 modifiers = parse_attributes(&attributes);
3657 if (declaration != NULL)
3658 declaration->modifiers |= modifiers;
3660 /* append inner_types at the end of the list, we don't to set last anymore
3661 * as it's not needed anymore */
3663 assert(first == NULL);
3664 first = inner_types;
3666 last->next = inner_types;
3674 static type_t *construct_declarator_type(construct_type_t *construct_list,
3677 construct_type_t *iter = construct_list;
3678 for( ; iter != NULL; iter = iter->next) {
3679 switch(iter->kind) {
3680 case CONSTRUCT_INVALID:
3681 internal_errorf(HERE, "invalid type construction found");
3682 case CONSTRUCT_FUNCTION: {
3683 construct_function_type_t *construct_function_type
3684 = (construct_function_type_t*) iter;
3686 type_t *function_type = construct_function_type->function_type;
3688 function_type->function.return_type = type;
3690 type_t *skipped_return_type = skip_typeref(type);
3691 if (is_type_function(skipped_return_type)) {
3692 errorf(HERE, "function returning function is not allowed");
3693 type = type_error_type;
3694 } else if (is_type_array(skipped_return_type)) {
3695 errorf(HERE, "function returning array is not allowed");
3696 type = type_error_type;
3698 type = function_type;
3703 case CONSTRUCT_POINTER: {
3704 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3705 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3706 pointer_type->pointer.points_to = type;
3707 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3709 type = pointer_type;
3713 case CONSTRUCT_ARRAY: {
3714 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3715 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3717 expression_t *size_expression = parsed_array->size;
3718 if(size_expression != NULL) {
3720 = create_implicit_cast(size_expression, type_size_t);
3723 array_type->base.qualifiers = parsed_array->type_qualifiers;
3724 array_type->array.element_type = type;
3725 array_type->array.is_static = parsed_array->is_static;
3726 array_type->array.is_variable = parsed_array->is_variable;
3727 array_type->array.size_expression = size_expression;
3729 if(size_expression != NULL) {
3730 if(is_constant_expression(size_expression)) {
3731 array_type->array.size_constant = true;
3732 array_type->array.size
3733 = fold_constant(size_expression);
3735 array_type->array.is_vla = true;
3739 type_t *skipped_type = skip_typeref(type);
3740 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3741 errorf(HERE, "array of void is not allowed");
3742 type = type_error_type;
3750 type_t *hashed_type = typehash_insert(type);
3751 if(hashed_type != type) {
3752 /* the function type was constructed earlier freeing it here will
3753 * destroy other types... */
3754 if(iter->kind != CONSTRUCT_FUNCTION) {
3764 static declaration_t *parse_declarator(
3765 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3767 declaration_t *const declaration = allocate_declaration_zero();
3768 declaration->declared_storage_class = specifiers->declared_storage_class;
3769 declaration->modifiers = specifiers->modifiers;
3770 declaration->deprecated = specifiers->deprecated;
3771 declaration->deprecated_string = specifiers->deprecated_string;
3772 declaration->get_property_sym = specifiers->get_property_sym;
3773 declaration->put_property_sym = specifiers->put_property_sym;
3774 declaration->is_inline = specifiers->is_inline;
3776 declaration->storage_class = specifiers->declared_storage_class;
3777 if(declaration->storage_class == STORAGE_CLASS_NONE
3778 && scope != global_scope) {
3779 declaration->storage_class = STORAGE_CLASS_AUTO;
3782 if(specifiers->alignment != 0) {
3783 /* TODO: add checks here */
3784 declaration->alignment = specifiers->alignment;
3787 construct_type_t *construct_type
3788 = parse_inner_declarator(declaration, may_be_abstract);
3789 type_t *const type = specifiers->type;
3790 declaration->type = construct_declarator_type(construct_type, type);
3792 if(construct_type != NULL) {
3793 obstack_free(&temp_obst, construct_type);
3799 static type_t *parse_abstract_declarator(type_t *base_type)
3801 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3803 type_t *result = construct_declarator_type(construct_type, base_type);
3804 if(construct_type != NULL) {
3805 obstack_free(&temp_obst, construct_type);
3811 static declaration_t *append_declaration(declaration_t* const declaration)
3813 if (last_declaration != NULL) {
3814 last_declaration->next = declaration;
3816 scope->declarations = declaration;
3818 last_declaration = declaration;
3823 * Check if the declaration of main is suspicious. main should be a
3824 * function with external linkage, returning int, taking either zero
3825 * arguments, two, or three arguments of appropriate types, ie.
3827 * int main([ int argc, char **argv [, char **env ] ]).
3829 * @param decl the declaration to check
3830 * @param type the function type of the declaration
3832 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3834 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3835 warningf(&decl->source_position,
3836 "'main' is normally a non-static function");
3838 if (skip_typeref(func_type->return_type) != type_int) {
3839 warningf(&decl->source_position,
3840 "return type of 'main' should be 'int', but is '%T'",
3841 func_type->return_type);
3843 const function_parameter_t *parm = func_type->parameters;
3845 type_t *const first_type = parm->type;
3846 if (!types_compatible(skip_typeref(first_type), type_int)) {
3847 warningf(&decl->source_position,
3848 "first argument of 'main' should be 'int', but is '%T'", first_type);
3852 type_t *const second_type = parm->type;
3853 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3854 warningf(&decl->source_position,
3855 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3859 type_t *const third_type = parm->type;
3860 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3861 warningf(&decl->source_position,
3862 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3866 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3870 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3876 * Check if a symbol is the equal to "main".
3878 static bool is_sym_main(const symbol_t *const sym)
3880 return strcmp(sym->string, "main") == 0;
3883 static declaration_t *internal_record_declaration(
3884 declaration_t *const declaration,
3885 const bool is_function_definition)
3887 const symbol_t *const symbol = declaration->symbol;
3888 const namespace_t namespc = (namespace_t)declaration->namespc;
3890 assert(declaration->symbol != NULL);
3891 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3893 type_t *const orig_type = declaration->type;
3894 type_t *const type = skip_typeref(orig_type);
3895 if (is_type_function(type) &&
3896 type->function.unspecified_parameters &&
3897 warning.strict_prototypes &&
3898 previous_declaration == NULL) {
3899 warningf(&declaration->source_position,
3900 "function declaration '%#T' is not a prototype",
3901 orig_type, declaration->symbol);
3904 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3905 check_type_of_main(declaration, &type->function);
3908 assert(declaration != previous_declaration);
3909 if (previous_declaration != NULL
3910 && previous_declaration->parent_scope == scope) {
3911 /* can happen for K&R style declarations */
3912 if (previous_declaration->type == NULL) {
3913 previous_declaration->type = declaration->type;
3916 const type_t *prev_type = skip_typeref(previous_declaration->type);
3917 if (!types_compatible(type, prev_type)) {
3918 errorf(&declaration->source_position,
3919 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3920 orig_type, symbol, previous_declaration->type, symbol,
3921 &previous_declaration->source_position);
3923 unsigned old_storage_class = previous_declaration->storage_class;
3924 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3925 errorf(&declaration->source_position,
3926 "redeclaration of enum entry '%Y' (declared %P)",
3927 symbol, &previous_declaration->source_position);
3928 return previous_declaration;
3931 unsigned new_storage_class = declaration->storage_class;
3933 if (is_type_incomplete(prev_type)) {
3934 previous_declaration->type = type;
3938 /* pretend no storage class means extern for function
3939 * declarations (except if the previous declaration is neither
3940 * none nor extern) */
3941 if (is_type_function(type)) {
3942 if (prev_type->function.unspecified_parameters) {
3943 previous_declaration->type = type;
3947 switch (old_storage_class) {
3948 case STORAGE_CLASS_NONE:
3949 old_storage_class = STORAGE_CLASS_EXTERN;
3951 case STORAGE_CLASS_EXTERN:
3952 if (is_function_definition) {
3953 if (warning.missing_prototypes &&
3954 prev_type->function.unspecified_parameters &&
3955 !is_sym_main(symbol)) {
3956 warningf(&declaration->source_position,
3957 "no previous prototype for '%#T'",
3960 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3961 new_storage_class = STORAGE_CLASS_EXTERN;
3970 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3971 new_storage_class == STORAGE_CLASS_EXTERN) {
3972 warn_redundant_declaration:
3973 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
3974 warningf(&declaration->source_position,
3975 "redundant declaration for '%Y' (declared %P)",
3976 symbol, &previous_declaration->source_position);
3978 } else if (current_function == NULL) {
3979 if (old_storage_class != STORAGE_CLASS_STATIC &&
3980 new_storage_class == STORAGE_CLASS_STATIC) {
3981 errorf(&declaration->source_position,
3982 "static declaration of '%Y' follows non-static declaration (declared %P)",
3983 symbol, &previous_declaration->source_position);
3984 } else if (old_storage_class != STORAGE_CLASS_EXTERN
3985 && !is_function_definition) {
3986 goto warn_redundant_declaration;
3987 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3988 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3989 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3991 } else if (old_storage_class == new_storage_class) {
3992 errorf(&declaration->source_position,
3993 "redeclaration of '%Y' (declared %P)",
3994 symbol, &previous_declaration->source_position);
3996 errorf(&declaration->source_position,
3997 "redeclaration of '%Y' with different linkage (declared %P)",
3998 symbol, &previous_declaration->source_position);
4002 if (declaration->is_inline)
4003 previous_declaration->is_inline = true;
4004 return previous_declaration;
4005 } else if (is_function_definition) {
4006 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4007 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4008 warningf(&declaration->source_position,
4009 "no previous prototype for '%#T'", orig_type, symbol);
4010 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4011 warningf(&declaration->source_position,
4012 "no previous declaration for '%#T'", orig_type,
4016 } else if (warning.missing_declarations &&
4017 scope == global_scope &&
4018 !is_type_function(type) && (
4019 declaration->storage_class == STORAGE_CLASS_NONE ||
4020 declaration->storage_class == STORAGE_CLASS_THREAD
4022 warningf(&declaration->source_position,
4023 "no previous declaration for '%#T'", orig_type, symbol);
4026 assert(declaration->parent_scope == NULL);
4027 assert(scope != NULL);
4029 declaration->parent_scope = scope;
4031 environment_push(declaration);
4032 return append_declaration(declaration);
4035 static declaration_t *record_declaration(declaration_t *declaration)
4037 return internal_record_declaration(declaration, false);
4040 static declaration_t *record_function_definition(declaration_t *declaration)
4042 return internal_record_declaration(declaration, true);
4045 static void parser_error_multiple_definition(declaration_t *declaration,
4046 const source_position_t *source_position)
4048 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4049 declaration->symbol, &declaration->source_position);
4052 static bool is_declaration_specifier(const token_t *token,
4053 bool only_specifiers_qualifiers)
4055 switch(token->type) {
4060 return is_typedef_symbol(token->v.symbol);
4062 case T___extension__:
4064 return !only_specifiers_qualifiers;
4071 static void parse_init_declarator_rest(declaration_t *declaration)
4075 type_t *orig_type = declaration->type;
4076 type_t *type = skip_typeref(orig_type);
4078 if(declaration->init.initializer != NULL) {
4079 parser_error_multiple_definition(declaration, HERE);
4082 bool must_be_constant = false;
4083 if(declaration->storage_class == STORAGE_CLASS_STATIC
4084 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4085 || declaration->parent_scope == global_scope) {
4086 must_be_constant = true;
4089 parse_initializer_env_t env;
4090 env.type = orig_type;
4091 env.must_be_constant = must_be_constant;
4092 env.declaration = declaration;
4094 initializer_t *initializer = parse_initializer(&env);
4096 if(env.type != orig_type) {
4097 orig_type = env.type;
4098 type = skip_typeref(orig_type);
4099 declaration->type = env.type;
4102 if(is_type_function(type)) {
4103 errorf(&declaration->source_position,
4104 "initializers not allowed for function types at declator '%Y' (type '%T')",
4105 declaration->symbol, orig_type);
4107 declaration->init.initializer = initializer;
4111 /* parse rest of a declaration without any declarator */
4112 static void parse_anonymous_declaration_rest(
4113 const declaration_specifiers_t *specifiers,
4114 parsed_declaration_func finished_declaration)
4118 declaration_t *const declaration = allocate_declaration_zero();
4119 declaration->type = specifiers->type;
4120 declaration->declared_storage_class = specifiers->declared_storage_class;
4121 declaration->source_position = specifiers->source_position;
4122 declaration->modifiers = specifiers->modifiers;
4124 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4125 warningf(&declaration->source_position,
4126 "useless storage class in empty declaration");
4128 declaration->storage_class = STORAGE_CLASS_NONE;
4130 type_t *type = declaration->type;
4131 switch (type->kind) {
4132 case TYPE_COMPOUND_STRUCT:
4133 case TYPE_COMPOUND_UNION: {
4134 if (type->compound.declaration->symbol == NULL) {
4135 warningf(&declaration->source_position,
4136 "unnamed struct/union that defines no instances");
4145 warningf(&declaration->source_position, "empty declaration");
4149 finished_declaration(declaration);
4152 static void parse_declaration_rest(declaration_t *ndeclaration,
4153 const declaration_specifiers_t *specifiers,
4154 parsed_declaration_func finished_declaration)
4156 add_anchor_token(';');
4157 add_anchor_token('=');
4158 add_anchor_token(',');
4160 declaration_t *declaration = finished_declaration(ndeclaration);
4162 type_t *orig_type = declaration->type;
4163 type_t *type = skip_typeref(orig_type);
4165 if (type->kind != TYPE_FUNCTION &&
4166 declaration->is_inline &&
4167 is_type_valid(type)) {
4168 warningf(&declaration->source_position,
4169 "variable '%Y' declared 'inline'\n", declaration->symbol);
4172 if(token.type == '=') {
4173 parse_init_declarator_rest(declaration);
4176 if(token.type != ',')
4180 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4185 rem_anchor_token(';');
4186 rem_anchor_token('=');
4187 rem_anchor_token(',');
4190 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4192 symbol_t *symbol = declaration->symbol;
4193 if(symbol == NULL) {
4194 errorf(HERE, "anonymous declaration not valid as function parameter");
4197 namespace_t namespc = (namespace_t) declaration->namespc;
4198 if(namespc != NAMESPACE_NORMAL) {
4199 return record_declaration(declaration);
4202 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4203 if(previous_declaration == NULL ||
4204 previous_declaration->parent_scope != scope) {
4205 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4210 if(previous_declaration->type == NULL) {
4211 previous_declaration->type = declaration->type;
4212 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4213 previous_declaration->storage_class = declaration->storage_class;
4214 previous_declaration->parent_scope = scope;
4215 return previous_declaration;
4217 return record_declaration(declaration);
4221 static void parse_declaration(parsed_declaration_func finished_declaration)
4223 declaration_specifiers_t specifiers;
4224 memset(&specifiers, 0, sizeof(specifiers));
4225 parse_declaration_specifiers(&specifiers);
4227 if(token.type == ';') {
4228 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4230 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4231 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4235 static type_t *get_default_promoted_type(type_t *orig_type)
4237 type_t *result = orig_type;
4239 type_t *type = skip_typeref(orig_type);
4240 if(is_type_integer(type)) {
4241 result = promote_integer(type);
4242 } else if(type == type_float) {
4243 result = type_double;
4249 static void parse_kr_declaration_list(declaration_t *declaration)
4251 type_t *type = skip_typeref(declaration->type);
4252 if (!is_type_function(type))
4255 if (!type->function.kr_style_parameters)
4258 /* push function parameters */
4259 int top = environment_top();
4260 scope_t *last_scope = scope;
4261 set_scope(&declaration->scope);
4263 declaration_t *parameter = declaration->scope.declarations;
4264 for ( ; parameter != NULL; parameter = parameter->next) {
4265 assert(parameter->parent_scope == NULL);
4266 parameter->parent_scope = scope;
4267 environment_push(parameter);
4270 /* parse declaration list */
4271 while (is_declaration_specifier(&token, false)) {
4272 parse_declaration(finished_kr_declaration);
4275 /* pop function parameters */
4276 assert(scope == &declaration->scope);
4277 set_scope(last_scope);
4278 environment_pop_to(top);
4280 /* update function type */
4281 type_t *new_type = duplicate_type(type);
4283 function_parameter_t *parameters = NULL;
4284 function_parameter_t *last_parameter = NULL;
4286 declaration_t *parameter_declaration = declaration->scope.declarations;
4287 for( ; parameter_declaration != NULL;
4288 parameter_declaration = parameter_declaration->next) {
4289 type_t *parameter_type = parameter_declaration->type;
4290 if(parameter_type == NULL) {
4292 errorf(HERE, "no type specified for function parameter '%Y'",
4293 parameter_declaration->symbol);
4295 if (warning.implicit_int) {
4296 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4297 parameter_declaration->symbol);
4299 parameter_type = type_int;
4300 parameter_declaration->type = parameter_type;
4304 semantic_parameter(parameter_declaration);
4305 parameter_type = parameter_declaration->type;
4308 * we need the default promoted types for the function type
4310 parameter_type = get_default_promoted_type(parameter_type);
4312 function_parameter_t *function_parameter
4313 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4314 memset(function_parameter, 0, sizeof(function_parameter[0]));
4316 function_parameter->type = parameter_type;
4317 if(last_parameter != NULL) {
4318 last_parameter->next = function_parameter;
4320 parameters = function_parameter;
4322 last_parameter = function_parameter;
4325 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4327 new_type->function.parameters = parameters;
4328 new_type->function.unspecified_parameters = true;
4330 type = typehash_insert(new_type);
4331 if(type != new_type) {
4332 obstack_free(type_obst, new_type);
4335 declaration->type = type;
4338 static bool first_err = true;
4341 * When called with first_err set, prints the name of the current function,
4344 static void print_in_function(void) {
4347 diagnosticf("%s: In function '%Y':\n",
4348 current_function->source_position.input_name,
4349 current_function->symbol);
4354 * Check if all labels are defined in the current function.
4355 * Check if all labels are used in the current function.
4357 static void check_labels(void)
4359 for (const goto_statement_t *goto_statement = goto_first;
4360 goto_statement != NULL;
4361 goto_statement = goto_statement->next) {
4362 declaration_t *label = goto_statement->label;
4365 if (label->source_position.input_name == NULL) {
4366 print_in_function();
4367 errorf(&goto_statement->base.source_position,
4368 "label '%Y' used but not defined", label->symbol);
4371 goto_first = goto_last = NULL;
4373 if (warning.unused_label) {
4374 for (const label_statement_t *label_statement = label_first;
4375 label_statement != NULL;
4376 label_statement = label_statement->next) {
4377 const declaration_t *label = label_statement->label;
4379 if (! label->used) {
4380 print_in_function();
4381 warningf(&label_statement->base.source_position,
4382 "label '%Y' defined but not used", label->symbol);
4386 label_first = label_last = NULL;
4390 * Check declarations of current_function for unused entities.
4392 static void check_declarations(void)
4394 if (warning.unused_parameter) {
4395 const scope_t *scope = ¤t_function->scope;
4397 const declaration_t *parameter = scope->declarations;
4398 for (; parameter != NULL; parameter = parameter->next) {
4399 if (! parameter->used) {
4400 print_in_function();
4401 warningf(¶meter->source_position,
4402 "unused parameter '%Y'", parameter->symbol);
4406 if (warning.unused_variable) {
4410 static void parse_external_declaration(void)
4412 /* function-definitions and declarations both start with declaration
4414 declaration_specifiers_t specifiers;
4415 memset(&specifiers, 0, sizeof(specifiers));
4417 add_anchor_token(';');
4418 parse_declaration_specifiers(&specifiers);
4419 rem_anchor_token(';');
4421 /* must be a declaration */
4422 if(token.type == ';') {
4423 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4427 add_anchor_token(',');
4428 add_anchor_token('=');
4429 rem_anchor_token(';');
4431 /* declarator is common to both function-definitions and declarations */
4432 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4434 rem_anchor_token(',');
4435 rem_anchor_token('=');
4436 rem_anchor_token(';');
4438 /* must be a declaration */
4439 if(token.type == ',' || token.type == '=' || token.type == ';') {
4440 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4444 /* must be a function definition */
4445 parse_kr_declaration_list(ndeclaration);
4447 if(token.type != '{') {
4448 parse_error_expected("while parsing function definition", '{', NULL);
4449 eat_until_matching_token(';');
4453 type_t *type = ndeclaration->type;
4455 /* note that we don't skip typerefs: the standard doesn't allow them here
4456 * (so we can't use is_type_function here) */
4457 if(type->kind != TYPE_FUNCTION) {
4458 if (is_type_valid(type)) {
4459 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4460 type, ndeclaration->symbol);
4466 /* § 6.7.5.3 (14) a function definition with () means no
4467 * parameters (and not unspecified parameters) */
4468 if(type->function.unspecified_parameters
4469 && type->function.parameters == NULL
4470 && !type->function.kr_style_parameters) {
4471 type_t *duplicate = duplicate_type(type);
4472 duplicate->function.unspecified_parameters = false;
4474 type = typehash_insert(duplicate);
4475 if(type != duplicate) {
4476 obstack_free(type_obst, duplicate);
4478 ndeclaration->type = type;
4481 declaration_t *const declaration = record_function_definition(ndeclaration);
4482 if(ndeclaration != declaration) {
4483 declaration->scope = ndeclaration->scope;
4485 type = skip_typeref(declaration->type);
4487 /* push function parameters and switch scope */
4488 int top = environment_top();
4489 scope_t *last_scope = scope;
4490 set_scope(&declaration->scope);
4492 declaration_t *parameter = declaration->scope.declarations;
4493 for( ; parameter != NULL; parameter = parameter->next) {
4494 if(parameter->parent_scope == &ndeclaration->scope) {
4495 parameter->parent_scope = scope;
4497 assert(parameter->parent_scope == NULL
4498 || parameter->parent_scope == scope);
4499 parameter->parent_scope = scope;
4500 environment_push(parameter);
4503 if(declaration->init.statement != NULL) {
4504 parser_error_multiple_definition(declaration, HERE);
4506 goto end_of_parse_external_declaration;
4508 /* parse function body */
4509 int label_stack_top = label_top();
4510 declaration_t *old_current_function = current_function;
4511 current_function = declaration;
4513 declaration->init.statement = parse_compound_statement(false);
4516 check_declarations();
4518 assert(current_function == declaration);
4519 current_function = old_current_function;
4520 label_pop_to(label_stack_top);
4523 end_of_parse_external_declaration:
4524 assert(scope == &declaration->scope);
4525 set_scope(last_scope);
4526 environment_pop_to(top);
4529 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4530 source_position_t *source_position)
4532 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4534 type->bitfield.base_type = base_type;
4535 type->bitfield.size = size;
4540 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4543 declaration_t *iter = compound_declaration->scope.declarations;
4544 for( ; iter != NULL; iter = iter->next) {
4545 if(iter->namespc != NAMESPACE_NORMAL)
4548 if(iter->symbol == NULL) {
4549 type_t *type = skip_typeref(iter->type);
4550 if(is_type_compound(type)) {
4551 declaration_t *result
4552 = find_compound_entry(type->compound.declaration, symbol);
4559 if(iter->symbol == symbol) {
4567 static void parse_compound_declarators(declaration_t *struct_declaration,
4568 const declaration_specifiers_t *specifiers)
4570 declaration_t *last_declaration = struct_declaration->scope.declarations;
4571 if(last_declaration != NULL) {
4572 while(last_declaration->next != NULL) {
4573 last_declaration = last_declaration->next;
4578 declaration_t *declaration;
4580 if(token.type == ':') {
4581 source_position_t source_position = *HERE;
4584 type_t *base_type = specifiers->type;
4585 expression_t *size = parse_constant_expression();
4587 if(!is_type_integer(skip_typeref(base_type))) {
4588 errorf(HERE, "bitfield base type '%T' is not an integer type",
4592 type_t *type = make_bitfield_type(base_type, size, &source_position);
4594 declaration = allocate_declaration_zero();
4595 declaration->namespc = NAMESPACE_NORMAL;
4596 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4597 declaration->storage_class = STORAGE_CLASS_NONE;
4598 declaration->source_position = source_position;
4599 declaration->modifiers = specifiers->modifiers;
4600 declaration->type = type;
4602 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4604 type_t *orig_type = declaration->type;
4605 type_t *type = skip_typeref(orig_type);
4607 if(token.type == ':') {
4608 source_position_t source_position = *HERE;
4610 expression_t *size = parse_constant_expression();
4612 if(!is_type_integer(type)) {
4613 errorf(HERE, "bitfield base type '%T' is not an "
4614 "integer type", orig_type);
4617 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4618 declaration->type = bitfield_type;
4620 /* TODO we ignore arrays for now... what is missing is a check
4621 * that they're at the end of the struct */
4622 if(is_type_incomplete(type) && !is_type_array(type)) {
4624 "compound member '%Y' has incomplete type '%T'",
4625 declaration->symbol, orig_type);
4626 } else if(is_type_function(type)) {
4627 errorf(HERE, "compound member '%Y' must not have function "
4628 "type '%T'", declaration->symbol, orig_type);
4633 /* make sure we don't define a symbol multiple times */
4634 symbol_t *symbol = declaration->symbol;
4635 if(symbol != NULL) {
4636 declaration_t *prev_decl
4637 = find_compound_entry(struct_declaration, symbol);
4639 if(prev_decl != NULL) {
4640 assert(prev_decl->symbol == symbol);
4641 errorf(&declaration->source_position,
4642 "multiple declarations of symbol '%Y' (declared %P)",
4643 symbol, &prev_decl->source_position);
4647 /* append declaration */
4648 if(last_declaration != NULL) {
4649 last_declaration->next = declaration;
4651 struct_declaration->scope.declarations = declaration;
4653 last_declaration = declaration;
4655 if(token.type != ',')
4665 static void parse_compound_type_entries(declaration_t *compound_declaration)
4668 add_anchor_token('}');
4670 while(token.type != '}' && token.type != T_EOF) {
4671 declaration_specifiers_t specifiers;
4672 memset(&specifiers, 0, sizeof(specifiers));
4673 parse_declaration_specifiers(&specifiers);
4675 parse_compound_declarators(compound_declaration, &specifiers);
4677 rem_anchor_token('}');
4679 if(token.type == T_EOF) {
4680 errorf(HERE, "EOF while parsing struct");
4685 static type_t *parse_typename(void)
4687 declaration_specifiers_t specifiers;
4688 memset(&specifiers, 0, sizeof(specifiers));
4689 parse_declaration_specifiers(&specifiers);
4690 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4691 /* TODO: improve error message, user does probably not know what a
4692 * storage class is...
4694 errorf(HERE, "typename may not have a storage class");
4697 type_t *result = parse_abstract_declarator(specifiers.type);
4705 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4706 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4707 expression_t *left);
4709 typedef struct expression_parser_function_t expression_parser_function_t;
4710 struct expression_parser_function_t {
4711 unsigned precedence;
4712 parse_expression_function parser;
4713 unsigned infix_precedence;
4714 parse_expression_infix_function infix_parser;
4717 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4720 * Prints an error message if an expression was expected but not read
4722 static expression_t *expected_expression_error(void)
4724 /* skip the error message if the error token was read */
4725 if (token.type != T_ERROR) {
4726 errorf(HERE, "expected expression, got token '%K'", &token);
4730 return create_invalid_expression();
4734 * Parse a string constant.
4736 static expression_t *parse_string_const(void)
4739 if (token.type == T_STRING_LITERAL) {
4740 string_t res = token.v.string;
4742 while (token.type == T_STRING_LITERAL) {
4743 res = concat_strings(&res, &token.v.string);
4746 if (token.type != T_WIDE_STRING_LITERAL) {
4747 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4748 /* note: that we use type_char_ptr here, which is already the
4749 * automatic converted type. revert_automatic_type_conversion
4750 * will construct the array type */
4751 cnst->base.type = type_char_ptr;
4752 cnst->string.value = res;
4756 wres = concat_string_wide_string(&res, &token.v.wide_string);
4758 wres = token.v.wide_string;
4763 switch (token.type) {
4764 case T_WIDE_STRING_LITERAL:
4765 wres = concat_wide_strings(&wres, &token.v.wide_string);
4768 case T_STRING_LITERAL:
4769 wres = concat_wide_string_string(&wres, &token.v.string);
4773 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4774 cnst->base.type = type_wchar_t_ptr;
4775 cnst->wide_string.value = wres;
4784 * Parse an integer constant.
4786 static expression_t *parse_int_const(void)
4788 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4789 cnst->base.source_position = *HERE;
4790 cnst->base.type = token.datatype;
4791 cnst->conste.v.int_value = token.v.intvalue;
4799 * Parse a character constant.
4801 static expression_t *parse_character_constant(void)
4803 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4805 cnst->base.source_position = *HERE;
4806 cnst->base.type = token.datatype;
4807 cnst->conste.v.character = token.v.string;
4809 if (cnst->conste.v.character.size != 1) {
4810 if (warning.multichar && (c_mode & _GNUC)) {
4812 warningf(HERE, "multi-character character constant");
4814 errorf(HERE, "more than 1 characters in character constant");
4823 * Parse a wide character constant.
4825 static expression_t *parse_wide_character_constant(void)
4827 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4829 cnst->base.source_position = *HERE;
4830 cnst->base.type = token.datatype;
4831 cnst->conste.v.wide_character = token.v.wide_string;
4833 if (cnst->conste.v.wide_character.size != 1) {
4834 if (warning.multichar && (c_mode & _GNUC)) {
4836 warningf(HERE, "multi-character character constant");
4838 errorf(HERE, "more than 1 characters in character constant");
4847 * Parse a float constant.
4849 static expression_t *parse_float_const(void)
4851 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4852 cnst->base.type = token.datatype;
4853 cnst->conste.v.float_value = token.v.floatvalue;
4860 static declaration_t *create_implicit_function(symbol_t *symbol,
4861 const source_position_t *source_position)
4863 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4864 ntype->function.return_type = type_int;
4865 ntype->function.unspecified_parameters = true;
4867 type_t *type = typehash_insert(ntype);
4872 declaration_t *const declaration = allocate_declaration_zero();
4873 declaration->storage_class = STORAGE_CLASS_EXTERN;
4874 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4875 declaration->type = type;
4876 declaration->symbol = symbol;
4877 declaration->source_position = *source_position;
4879 bool strict_prototypes_old = warning.strict_prototypes;
4880 warning.strict_prototypes = false;
4881 record_declaration(declaration);
4882 warning.strict_prototypes = strict_prototypes_old;
4888 * Creates a return_type (func)(argument_type) function type if not
4891 * @param return_type the return type
4892 * @param argument_type the argument type
4894 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4896 function_parameter_t *parameter
4897 = obstack_alloc(type_obst, sizeof(parameter[0]));
4898 memset(parameter, 0, sizeof(parameter[0]));
4899 parameter->type = argument_type;
4901 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4902 type->function.return_type = return_type;
4903 type->function.parameters = parameter;
4905 type_t *result = typehash_insert(type);
4906 if(result != type) {
4913 static type_t *make_function_0_type(type_t *return_type)
4915 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4916 type->function.return_type = return_type;
4917 type->function.parameters = NULL;
4919 type_t *result = typehash_insert(type);
4920 if(result != type) {
4928 * Creates a function type for some function like builtins.
4930 * @param symbol the symbol describing the builtin
4932 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4934 switch(symbol->ID) {
4935 case T___builtin_alloca:
4936 return make_function_1_type(type_void_ptr, type_size_t);
4937 case T___builtin_huge_val:
4938 return make_function_0_type(type_double);
4939 case T___builtin_nan:
4940 return make_function_1_type(type_double, type_char_ptr);
4941 case T___builtin_nanf:
4942 return make_function_1_type(type_float, type_char_ptr);
4943 case T___builtin_nand:
4944 return make_function_1_type(type_long_double, type_char_ptr);
4945 case T___builtin_va_end:
4946 return make_function_1_type(type_void, type_valist);
4948 internal_errorf(HERE, "not implemented builtin symbol found");
4953 * Performs automatic type cast as described in § 6.3.2.1.
4955 * @param orig_type the original type
4957 static type_t *automatic_type_conversion(type_t *orig_type)
4959 type_t *type = skip_typeref(orig_type);
4960 if(is_type_array(type)) {
4961 array_type_t *array_type = &type->array;
4962 type_t *element_type = array_type->element_type;
4963 unsigned qualifiers = array_type->base.qualifiers;
4965 return make_pointer_type(element_type, qualifiers);
4968 if(is_type_function(type)) {
4969 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4976 * reverts the automatic casts of array to pointer types and function
4977 * to function-pointer types as defined § 6.3.2.1
4979 type_t *revert_automatic_type_conversion(const expression_t *expression)
4981 switch (expression->kind) {
4982 case EXPR_REFERENCE: return expression->reference.declaration->type;
4983 case EXPR_SELECT: return expression->select.compound_entry->type;
4985 case EXPR_UNARY_DEREFERENCE: {
4986 const expression_t *const value = expression->unary.value;
4987 type_t *const type = skip_typeref(value->base.type);
4988 assert(is_type_pointer(type));
4989 return type->pointer.points_to;
4992 case EXPR_BUILTIN_SYMBOL:
4993 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4995 case EXPR_ARRAY_ACCESS: {
4996 const expression_t *array_ref = expression->array_access.array_ref;
4997 type_t *type_left = skip_typeref(array_ref->base.type);
4998 if (!is_type_valid(type_left))
5000 assert(is_type_pointer(type_left));
5001 return type_left->pointer.points_to;
5004 case EXPR_STRING_LITERAL: {
5005 size_t size = expression->string.value.size;
5006 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5009 case EXPR_WIDE_STRING_LITERAL: {
5010 size_t size = expression->wide_string.value.size;
5011 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5014 case EXPR_COMPOUND_LITERAL:
5015 return expression->compound_literal.type;
5020 return expression->base.type;
5023 static expression_t *parse_reference(void)
5025 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5027 reference_expression_t *ref = &expression->reference;
5028 symbol_t *const symbol = token.v.symbol;
5030 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5032 source_position_t source_position = token.source_position;
5035 if(declaration == NULL) {
5036 if (! strict_mode && token.type == '(') {
5037 /* an implicitly defined function */
5038 if (warning.implicit_function_declaration) {
5039 warningf(HERE, "implicit declaration of function '%Y'",
5043 declaration = create_implicit_function(symbol,
5046 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5047 return create_invalid_expression();
5051 type_t *type = declaration->type;
5053 /* we always do the auto-type conversions; the & and sizeof parser contains
5054 * code to revert this! */
5055 type = automatic_type_conversion(type);
5057 ref->declaration = declaration;
5058 ref->base.type = type;
5060 /* this declaration is used */
5061 declaration->used = true;
5063 /* check for deprecated functions */
5064 if(declaration->deprecated != 0) {
5065 const char *prefix = "";
5066 if (is_type_function(declaration->type))
5067 prefix = "function ";
5069 if (declaration->deprecated_string != NULL) {
5070 warningf(&source_position,
5071 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5072 declaration->deprecated_string);
5074 warningf(&source_position,
5075 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5082 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5086 /* TODO check if explicit cast is allowed and issue warnings/errors */
5089 static expression_t *parse_compound_literal(type_t *type)
5091 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5093 parse_initializer_env_t env;
5095 env.declaration = NULL;
5096 env.must_be_constant = false;
5097 initializer_t *initializer = parse_initializer(&env);
5100 expression->compound_literal.initializer = initializer;
5101 expression->compound_literal.type = type;
5102 expression->base.type = automatic_type_conversion(type);
5108 * Parse a cast expression.
5110 static expression_t *parse_cast(void)
5112 source_position_t source_position = token.source_position;
5114 type_t *type = parse_typename();
5116 /* matching add_anchor_token() is at call site */
5117 rem_anchor_token(')');
5120 if(token.type == '{') {
5121 return parse_compound_literal(type);
5124 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5125 cast->base.source_position = source_position;
5127 expression_t *value = parse_sub_expression(20);
5129 check_cast_allowed(value, type);
5131 cast->base.type = type;
5132 cast->unary.value = value;
5136 return create_invalid_expression();
5140 * Parse a statement expression.
5142 static expression_t *parse_statement_expression(void)
5144 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5146 statement_t *statement = parse_compound_statement(true);
5147 expression->statement.statement = statement;
5148 expression->base.source_position = statement->base.source_position;
5150 /* find last statement and use its type */
5151 type_t *type = type_void;
5152 const statement_t *stmt = statement->compound.statements;
5154 while (stmt->base.next != NULL)
5155 stmt = stmt->base.next;
5157 if (stmt->kind == STATEMENT_EXPRESSION) {
5158 type = stmt->expression.expression->base.type;
5161 warningf(&expression->base.source_position, "empty statement expression ({})");
5163 expression->base.type = type;
5169 return create_invalid_expression();
5173 * Parse a braced expression.
5175 static expression_t *parse_brace_expression(void)
5178 add_anchor_token(')');
5180 switch(token.type) {
5182 /* gcc extension: a statement expression */
5183 return parse_statement_expression();
5187 return parse_cast();
5189 if(is_typedef_symbol(token.v.symbol)) {
5190 return parse_cast();
5194 expression_t *result = parse_expression();
5195 rem_anchor_token(')');
5200 return create_invalid_expression();
5203 static expression_t *parse_function_keyword(void)
5208 if (current_function == NULL) {
5209 errorf(HERE, "'__func__' used outside of a function");
5212 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5213 expression->base.type = type_char_ptr;
5214 expression->funcname.kind = FUNCNAME_FUNCTION;
5219 static expression_t *parse_pretty_function_keyword(void)
5221 eat(T___PRETTY_FUNCTION__);
5223 if (current_function == NULL) {
5224 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5227 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5228 expression->base.type = type_char_ptr;
5229 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5234 static expression_t *parse_funcsig_keyword(void)
5238 if (current_function == NULL) {
5239 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5242 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5243 expression->base.type = type_char_ptr;
5244 expression->funcname.kind = FUNCNAME_FUNCSIG;
5249 static expression_t *parse_funcdname_keyword(void)
5251 eat(T___FUNCDNAME__);
5253 if (current_function == NULL) {
5254 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5257 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5258 expression->base.type = type_char_ptr;
5259 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5264 static designator_t *parse_designator(void)
5266 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5267 result->source_position = *HERE;
5269 if(token.type != T_IDENTIFIER) {
5270 parse_error_expected("while parsing member designator",
5271 T_IDENTIFIER, NULL);
5274 result->symbol = token.v.symbol;
5277 designator_t *last_designator = result;
5279 if(token.type == '.') {
5281 if(token.type != T_IDENTIFIER) {
5282 parse_error_expected("while parsing member designator",
5283 T_IDENTIFIER, NULL);
5286 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5287 designator->source_position = *HERE;
5288 designator->symbol = token.v.symbol;
5291 last_designator->next = designator;
5292 last_designator = designator;
5295 if(token.type == '[') {
5297 add_anchor_token(']');
5298 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5299 designator->source_position = *HERE;
5300 designator->array_index = parse_expression();
5301 rem_anchor_token(']');
5303 if(designator->array_index == NULL) {
5307 last_designator->next = designator;
5308 last_designator = designator;
5320 * Parse the __builtin_offsetof() expression.
5322 static expression_t *parse_offsetof(void)
5324 eat(T___builtin_offsetof);
5326 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5327 expression->base.type = type_size_t;
5330 add_anchor_token(',');
5331 type_t *type = parse_typename();
5332 rem_anchor_token(',');
5334 add_anchor_token(')');
5335 designator_t *designator = parse_designator();
5336 rem_anchor_token(')');
5339 expression->offsetofe.type = type;
5340 expression->offsetofe.designator = designator;
5343 memset(&path, 0, sizeof(path));
5344 path.top_type = type;
5345 path.path = NEW_ARR_F(type_path_entry_t, 0);
5347 descend_into_subtype(&path);
5349 if(!walk_designator(&path, designator, true)) {
5350 return create_invalid_expression();
5353 DEL_ARR_F(path.path);
5357 return create_invalid_expression();
5361 * Parses a _builtin_va_start() expression.
5363 static expression_t *parse_va_start(void)
5365 eat(T___builtin_va_start);
5367 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5370 add_anchor_token(',');
5371 expression->va_starte.ap = parse_assignment_expression();
5372 rem_anchor_token(',');
5374 expression_t *const expr = parse_assignment_expression();
5375 if (expr->kind == EXPR_REFERENCE) {
5376 declaration_t *const decl = expr->reference.declaration;
5378 return create_invalid_expression();
5379 if (decl->parent_scope == ¤t_function->scope &&
5380 decl->next == NULL) {
5381 expression->va_starte.parameter = decl;
5386 errorf(&expr->base.source_position,
5387 "second argument of 'va_start' must be last parameter of the current function");
5389 return create_invalid_expression();
5393 * Parses a _builtin_va_arg() expression.
5395 static expression_t *parse_va_arg(void)
5397 eat(T___builtin_va_arg);
5399 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5402 expression->va_arge.ap = parse_assignment_expression();
5404 expression->base.type = parse_typename();
5409 return create_invalid_expression();
5412 static expression_t *parse_builtin_symbol(void)
5414 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5416 symbol_t *symbol = token.v.symbol;
5418 expression->builtin_symbol.symbol = symbol;
5421 type_t *type = get_builtin_symbol_type(symbol);
5422 type = automatic_type_conversion(type);
5424 expression->base.type = type;
5429 * Parses a __builtin_constant() expression.
5431 static expression_t *parse_builtin_constant(void)
5433 eat(T___builtin_constant_p);
5435 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5438 add_anchor_token(')');
5439 expression->builtin_constant.value = parse_assignment_expression();
5440 rem_anchor_token(')');
5442 expression->base.type = type_int;
5446 return create_invalid_expression();
5450 * Parses a __builtin_prefetch() expression.
5452 static expression_t *parse_builtin_prefetch(void)
5454 eat(T___builtin_prefetch);
5456 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5459 add_anchor_token(')');
5460 expression->builtin_prefetch.adr = parse_assignment_expression();
5461 if (token.type == ',') {
5463 expression->builtin_prefetch.rw = parse_assignment_expression();
5465 if (token.type == ',') {
5467 expression->builtin_prefetch.locality = parse_assignment_expression();
5469 rem_anchor_token(')');
5471 expression->base.type = type_void;
5475 return create_invalid_expression();
5479 * Parses a __builtin_is_*() compare expression.
5481 static expression_t *parse_compare_builtin(void)
5483 expression_t *expression;
5485 switch(token.type) {
5486 case T___builtin_isgreater:
5487 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5489 case T___builtin_isgreaterequal:
5490 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5492 case T___builtin_isless:
5493 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5495 case T___builtin_islessequal:
5496 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5498 case T___builtin_islessgreater:
5499 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5501 case T___builtin_isunordered:
5502 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5505 internal_errorf(HERE, "invalid compare builtin found");
5508 expression->base.source_position = *HERE;
5512 expression->binary.left = parse_assignment_expression();
5514 expression->binary.right = parse_assignment_expression();
5517 type_t *const orig_type_left = expression->binary.left->base.type;
5518 type_t *const orig_type_right = expression->binary.right->base.type;
5520 type_t *const type_left = skip_typeref(orig_type_left);
5521 type_t *const type_right = skip_typeref(orig_type_right);
5522 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5523 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5524 type_error_incompatible("invalid operands in comparison",
5525 &expression->base.source_position, orig_type_left, orig_type_right);
5528 semantic_comparison(&expression->binary);
5533 return create_invalid_expression();
5537 * Parses a __builtin_expect() expression.
5539 static expression_t *parse_builtin_expect(void)
5541 eat(T___builtin_expect);
5543 expression_t *expression
5544 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5547 expression->binary.left = parse_assignment_expression();
5549 expression->binary.right = parse_constant_expression();
5552 expression->base.type = expression->binary.left->base.type;
5556 return create_invalid_expression();
5560 * Parses a MS assume() expression.
5562 static expression_t *parse_assume(void) {
5565 expression_t *expression
5566 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5569 add_anchor_token(')');
5570 expression->unary.value = parse_assignment_expression();
5571 rem_anchor_token(')');
5574 expression->base.type = type_void;
5577 return create_invalid_expression();
5581 * Parse a microsoft __noop expression.
5583 static expression_t *parse_noop_expression(void) {
5584 source_position_t source_position = *HERE;
5587 if (token.type == '(') {
5588 /* parse arguments */
5590 add_anchor_token(')');
5591 add_anchor_token(',');
5593 if(token.type != ')') {
5595 (void)parse_assignment_expression();
5596 if(token.type != ',')
5602 rem_anchor_token(',');
5603 rem_anchor_token(')');
5606 /* the result is a (int)0 */
5607 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5608 cnst->base.source_position = source_position;
5609 cnst->base.type = type_int;
5610 cnst->conste.v.int_value = 0;
5611 cnst->conste.is_ms_noop = true;
5616 return create_invalid_expression();
5620 * Parses a primary expression.
5622 static expression_t *parse_primary_expression(void)
5624 switch (token.type) {
5625 case T_INTEGER: return parse_int_const();
5626 case T_CHARACTER_CONSTANT: return parse_character_constant();
5627 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5628 case T_FLOATINGPOINT: return parse_float_const();
5629 case T_STRING_LITERAL:
5630 case T_WIDE_STRING_LITERAL: return parse_string_const();
5631 case T_IDENTIFIER: return parse_reference();
5632 case T___FUNCTION__:
5633 case T___func__: return parse_function_keyword();
5634 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5635 case T___FUNCSIG__: return parse_funcsig_keyword();
5636 case T___FUNCDNAME__: return parse_funcdname_keyword();
5637 case T___builtin_offsetof: return parse_offsetof();
5638 case T___builtin_va_start: return parse_va_start();
5639 case T___builtin_va_arg: return parse_va_arg();
5640 case T___builtin_expect: return parse_builtin_expect();
5641 case T___builtin_alloca:
5642 case T___builtin_nan:
5643 case T___builtin_nand:
5644 case T___builtin_nanf:
5645 case T___builtin_huge_val:
5646 case T___builtin_va_end: return parse_builtin_symbol();
5647 case T___builtin_isgreater:
5648 case T___builtin_isgreaterequal:
5649 case T___builtin_isless:
5650 case T___builtin_islessequal:
5651 case T___builtin_islessgreater:
5652 case T___builtin_isunordered: return parse_compare_builtin();
5653 case T___builtin_constant_p: return parse_builtin_constant();
5654 case T___builtin_prefetch: return parse_builtin_prefetch();
5655 case T__assume: return parse_assume();
5657 case '(': return parse_brace_expression();
5658 case T___noop: return parse_noop_expression();
5661 errorf(HERE, "unexpected token %K, expected an expression", &token);
5662 return create_invalid_expression();
5666 * Check if the expression has the character type and issue a warning then.
5668 static void check_for_char_index_type(const expression_t *expression) {
5669 type_t *const type = expression->base.type;
5670 const type_t *const base_type = skip_typeref(type);
5672 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5673 warning.char_subscripts) {
5674 warningf(&expression->base.source_position,
5675 "array subscript has type '%T'", type);
5679 static expression_t *parse_array_expression(unsigned precedence,
5685 add_anchor_token(']');
5687 expression_t *inside = parse_expression();
5689 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5691 array_access_expression_t *array_access = &expression->array_access;
5693 type_t *const orig_type_left = left->base.type;
5694 type_t *const orig_type_inside = inside->base.type;
5696 type_t *const type_left = skip_typeref(orig_type_left);
5697 type_t *const type_inside = skip_typeref(orig_type_inside);
5699 type_t *return_type;
5700 if (is_type_pointer(type_left)) {
5701 return_type = type_left->pointer.points_to;
5702 array_access->array_ref = left;
5703 array_access->index = inside;
5704 check_for_char_index_type(inside);
5705 } else if (is_type_pointer(type_inside)) {
5706 return_type = type_inside->pointer.points_to;
5707 array_access->array_ref = inside;
5708 array_access->index = left;
5709 array_access->flipped = true;
5710 check_for_char_index_type(left);
5712 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5714 "array access on object with non-pointer types '%T', '%T'",
5715 orig_type_left, orig_type_inside);
5717 return_type = type_error_type;
5718 array_access->array_ref = create_invalid_expression();
5721 rem_anchor_token(']');
5722 if(token.type != ']') {
5723 parse_error_expected("Problem while parsing array access", ']', NULL);
5728 return_type = automatic_type_conversion(return_type);
5729 expression->base.type = return_type;
5734 static expression_t *parse_typeprop(expression_kind_t const kind,
5735 source_position_t const pos,
5736 unsigned const precedence)
5738 expression_t *tp_expression = allocate_expression_zero(kind);
5739 tp_expression->base.type = type_size_t;
5740 tp_expression->base.source_position = pos;
5742 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5744 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5746 add_anchor_token(')');
5747 type_t* const orig_type = parse_typename();
5748 tp_expression->typeprop.type = orig_type;
5750 type_t const* const type = skip_typeref(orig_type);
5751 char const* const wrong_type =
5752 is_type_incomplete(type) ? "incomplete" :
5753 type->kind == TYPE_FUNCTION ? "function designator" :
5754 type->kind == TYPE_BITFIELD ? "bitfield" :
5756 if (wrong_type != NULL) {
5757 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5758 what, wrong_type, type);
5761 rem_anchor_token(')');
5764 expression_t *expression = parse_sub_expression(precedence);
5766 type_t* const orig_type = revert_automatic_type_conversion(expression);
5767 expression->base.type = orig_type;
5769 type_t const* const type = skip_typeref(orig_type);
5770 char const* const wrong_type =
5771 is_type_incomplete(type) ? "incomplete" :
5772 type->kind == TYPE_FUNCTION ? "function designator" :
5773 type->kind == TYPE_BITFIELD ? "bitfield" :
5775 if (wrong_type != NULL) {
5776 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5779 tp_expression->typeprop.type = expression->base.type;
5780 tp_expression->typeprop.tp_expression = expression;
5783 return tp_expression;
5785 return create_invalid_expression();
5788 static expression_t *parse_sizeof(unsigned precedence)
5790 source_position_t pos = *HERE;
5792 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5795 static expression_t *parse_alignof(unsigned precedence)
5797 source_position_t pos = *HERE;
5799 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5802 static expression_t *parse_select_expression(unsigned precedence,
5803 expression_t *compound)
5806 assert(token.type == '.' || token.type == T_MINUSGREATER);
5808 bool is_pointer = (token.type == T_MINUSGREATER);
5811 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5812 select->select.compound = compound;
5814 if (token.type != T_IDENTIFIER) {
5815 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5818 symbol_t *symbol = token.v.symbol;
5819 select->select.symbol = symbol;
5822 type_t *const orig_type = compound->base.type;
5823 type_t *const type = skip_typeref(orig_type);
5825 type_t *type_left = type;
5827 if (!is_type_pointer(type)) {
5828 if (is_type_valid(type)) {
5829 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5831 return create_invalid_expression();
5833 type_left = type->pointer.points_to;
5835 type_left = skip_typeref(type_left);
5837 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5838 type_left->kind != TYPE_COMPOUND_UNION) {
5839 if (is_type_valid(type_left)) {
5840 errorf(HERE, "request for member '%Y' in something not a struct or "
5841 "union, but '%T'", symbol, type_left);
5843 return create_invalid_expression();
5846 declaration_t *const declaration = type_left->compound.declaration;
5848 if (!declaration->init.complete) {
5849 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5851 return create_invalid_expression();
5854 declaration_t *iter = find_compound_entry(declaration, symbol);
5856 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5857 return create_invalid_expression();
5860 /* we always do the auto-type conversions; the & and sizeof parser contains
5861 * code to revert this! */
5862 type_t *expression_type = automatic_type_conversion(iter->type);
5864 select->select.compound_entry = iter;
5865 select->base.type = expression_type;
5867 type_t *skipped = skip_typeref(iter->type);
5868 if (skipped->kind == TYPE_BITFIELD) {
5869 select->base.type = skipped->bitfield.base_type;
5876 * Parse a call expression, ie. expression '( ... )'.
5878 * @param expression the function address
5880 static expression_t *parse_call_expression(unsigned precedence,
5881 expression_t *expression)
5884 expression_t *result = allocate_expression_zero(EXPR_CALL);
5885 result->base.source_position = expression->base.source_position;
5887 call_expression_t *call = &result->call;
5888 call->function = expression;
5890 type_t *const orig_type = expression->base.type;
5891 type_t *const type = skip_typeref(orig_type);
5893 function_type_t *function_type = NULL;
5894 if (is_type_pointer(type)) {
5895 type_t *const to_type = skip_typeref(type->pointer.points_to);
5897 if (is_type_function(to_type)) {
5898 function_type = &to_type->function;
5899 call->base.type = function_type->return_type;
5903 if (function_type == NULL && is_type_valid(type)) {
5904 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5907 /* parse arguments */
5909 add_anchor_token(')');
5910 add_anchor_token(',');
5912 if(token.type != ')') {
5913 call_argument_t *last_argument = NULL;
5916 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5918 argument->expression = parse_assignment_expression();
5919 if(last_argument == NULL) {
5920 call->arguments = argument;
5922 last_argument->next = argument;
5924 last_argument = argument;
5926 if(token.type != ',')
5931 rem_anchor_token(',');
5932 rem_anchor_token(')');
5935 if(function_type == NULL)
5938 function_parameter_t *parameter = function_type->parameters;
5939 call_argument_t *argument = call->arguments;
5940 if (!function_type->unspecified_parameters) {
5941 for( ; parameter != NULL && argument != NULL;
5942 parameter = parameter->next, argument = argument->next) {
5943 type_t *expected_type = parameter->type;
5944 /* TODO report scope in error messages */
5945 expression_t *const arg_expr = argument->expression;
5946 type_t *const res_type = semantic_assign(expected_type, arg_expr,
5948 &arg_expr->base.source_position);
5949 if (res_type == NULL) {
5950 /* TODO improve error message */
5951 errorf(&arg_expr->base.source_position,
5952 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5953 arg_expr, arg_expr->base.type, expected_type);
5955 argument->expression = create_implicit_cast(argument->expression, expected_type);
5959 if (parameter != NULL) {
5960 errorf(HERE, "too few arguments to function '%E'", expression);
5961 } else if (argument != NULL && !function_type->variadic) {
5962 errorf(HERE, "too many arguments to function '%E'", expression);
5966 /* do default promotion */
5967 for( ; argument != NULL; argument = argument->next) {
5968 type_t *type = argument->expression->base.type;
5970 type = get_default_promoted_type(type);
5972 argument->expression
5973 = create_implicit_cast(argument->expression, type);
5976 check_format(&result->call);
5980 return create_invalid_expression();
5983 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5985 static bool same_compound_type(const type_t *type1, const type_t *type2)
5988 is_type_compound(type1) &&
5989 type1->kind == type2->kind &&
5990 type1->compound.declaration == type2->compound.declaration;
5994 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5996 * @param expression the conditional expression
5998 static expression_t *parse_conditional_expression(unsigned precedence,
5999 expression_t *expression)
6002 add_anchor_token(':');
6004 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6006 conditional_expression_t *conditional = &result->conditional;
6007 conditional->condition = expression;
6010 type_t *const condition_type_orig = expression->base.type;
6011 type_t *const condition_type = skip_typeref(condition_type_orig);
6012 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6013 type_error("expected a scalar type in conditional condition",
6014 &expression->base.source_position, condition_type_orig);
6017 expression_t *true_expression = parse_expression();
6018 rem_anchor_token(':');
6020 expression_t *false_expression = parse_sub_expression(precedence);
6022 type_t *const orig_true_type = true_expression->base.type;
6023 type_t *const orig_false_type = false_expression->base.type;
6024 type_t *const true_type = skip_typeref(orig_true_type);
6025 type_t *const false_type = skip_typeref(orig_false_type);
6028 type_t *result_type;
6029 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6030 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6031 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6032 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6033 warningf(&expression->base.source_position,
6034 "ISO C forbids conditional expression with only one void side");
6036 result_type = type_void;
6037 } else if (is_type_arithmetic(true_type)
6038 && is_type_arithmetic(false_type)) {
6039 result_type = semantic_arithmetic(true_type, false_type);
6041 true_expression = create_implicit_cast(true_expression, result_type);
6042 false_expression = create_implicit_cast(false_expression, result_type);
6044 conditional->true_expression = true_expression;
6045 conditional->false_expression = false_expression;
6046 conditional->base.type = result_type;
6047 } else if (same_compound_type(true_type, false_type)) {
6048 /* just take 1 of the 2 types */
6049 result_type = true_type;
6050 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6051 type_t *pointer_type;
6053 expression_t *other_expression;
6054 if (is_type_pointer(true_type)) {
6055 pointer_type = true_type;
6056 other_type = false_type;
6057 other_expression = false_expression;
6059 pointer_type = false_type;
6060 other_type = true_type;
6061 other_expression = true_expression;
6064 if(is_type_pointer(other_type)) {
6065 if(!pointers_compatible(true_type, false_type)) {
6066 warningf(&expression->base.source_position,
6067 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
6069 result_type = true_type;
6070 } else if(is_null_pointer_constant(other_expression)) {
6071 result_type = pointer_type;
6072 } else if(is_type_integer(other_type)) {
6073 warningf(&expression->base.source_position,
6074 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6075 result_type = pointer_type;
6077 type_error_incompatible("while parsing conditional",
6078 &expression->base.source_position, true_type, false_type);
6079 result_type = type_error_type;
6082 /* TODO: one pointer to void*, other some pointer */
6084 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6085 type_error_incompatible("while parsing conditional",
6086 &expression->base.source_position, true_type,
6089 result_type = type_error_type;
6092 conditional->true_expression
6093 = create_implicit_cast(true_expression, result_type);
6094 conditional->false_expression
6095 = create_implicit_cast(false_expression, result_type);
6096 conditional->base.type = result_type;
6099 return create_invalid_expression();
6103 * Parse an extension expression.
6105 static expression_t *parse_extension(unsigned precedence)
6107 eat(T___extension__);
6109 /* TODO enable extensions */
6110 expression_t *expression = parse_sub_expression(precedence);
6111 /* TODO disable extensions */
6116 * Parse a __builtin_classify_type() expression.
6118 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6120 eat(T___builtin_classify_type);
6122 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6123 result->base.type = type_int;
6126 add_anchor_token(')');
6127 expression_t *expression = parse_sub_expression(precedence);
6128 rem_anchor_token(')');
6130 result->classify_type.type_expression = expression;
6134 return create_invalid_expression();
6137 static void check_pointer_arithmetic(const source_position_t *source_position,
6138 type_t *pointer_type,
6139 type_t *orig_pointer_type)
6141 type_t *points_to = pointer_type->pointer.points_to;
6142 points_to = skip_typeref(points_to);
6144 if (is_type_incomplete(points_to) &&
6146 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6147 errorf(source_position,
6148 "arithmetic with pointer to incomplete type '%T' not allowed",
6150 } else if (is_type_function(points_to)) {
6151 errorf(source_position,
6152 "arithmetic with pointer to function type '%T' not allowed",
6157 static void semantic_incdec(unary_expression_t *expression)
6159 type_t *const orig_type = expression->value->base.type;
6160 type_t *const type = skip_typeref(orig_type);
6161 if (is_type_pointer(type)) {
6162 check_pointer_arithmetic(&expression->base.source_position,
6164 } else if (!is_type_real(type) && is_type_valid(type)) {
6165 /* TODO: improve error message */
6166 errorf(HERE, "operation needs an arithmetic or pointer type");
6168 expression->base.type = orig_type;
6171 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6173 type_t *const orig_type = expression->value->base.type;
6174 type_t *const type = skip_typeref(orig_type);
6175 if(!is_type_arithmetic(type)) {
6176 if (is_type_valid(type)) {
6177 /* TODO: improve error message */
6178 errorf(HERE, "operation needs an arithmetic type");
6183 expression->base.type = orig_type;
6186 static void semantic_unexpr_scalar(unary_expression_t *expression)
6188 type_t *const orig_type = expression->value->base.type;
6189 type_t *const type = skip_typeref(orig_type);
6190 if (!is_type_scalar(type)) {
6191 if (is_type_valid(type)) {
6192 errorf(HERE, "operand of ! must be of scalar type");
6197 expression->base.type = orig_type;
6200 static void semantic_unexpr_integer(unary_expression_t *expression)
6202 type_t *const orig_type = expression->value->base.type;
6203 type_t *const type = skip_typeref(orig_type);
6204 if (!is_type_integer(type)) {
6205 if (is_type_valid(type)) {
6206 errorf(HERE, "operand of ~ must be of integer type");
6211 expression->base.type = orig_type;
6214 static void semantic_dereference(unary_expression_t *expression)
6216 type_t *const orig_type = expression->value->base.type;
6217 type_t *const type = skip_typeref(orig_type);
6218 if(!is_type_pointer(type)) {
6219 if (is_type_valid(type)) {
6220 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6225 type_t *result_type = type->pointer.points_to;
6226 result_type = automatic_type_conversion(result_type);
6227 expression->base.type = result_type;
6231 * Check the semantic of the address taken expression.
6233 static void semantic_take_addr(unary_expression_t *expression)
6235 expression_t *value = expression->value;
6236 value->base.type = revert_automatic_type_conversion(value);
6238 type_t *orig_type = value->base.type;
6239 if(!is_type_valid(orig_type))
6242 if(value->kind == EXPR_REFERENCE) {
6243 declaration_t *const declaration = value->reference.declaration;
6244 if(declaration != NULL) {
6245 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6246 errorf(&expression->base.source_position,
6247 "address of register variable '%Y' requested",
6248 declaration->symbol);
6250 declaration->address_taken = 1;
6254 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6257 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6258 static expression_t *parse_##unexpression_type(unsigned precedence) \
6262 expression_t *unary_expression \
6263 = allocate_expression_zero(unexpression_type); \
6264 unary_expression->base.source_position = *HERE; \
6265 unary_expression->unary.value = parse_sub_expression(precedence); \
6267 sfunc(&unary_expression->unary); \
6269 return unary_expression; \
6272 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6273 semantic_unexpr_arithmetic)
6274 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6275 semantic_unexpr_arithmetic)
6276 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6277 semantic_unexpr_scalar)
6278 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6279 semantic_dereference)
6280 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6282 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6283 semantic_unexpr_integer)
6284 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6286 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6289 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6291 static expression_t *parse_##unexpression_type(unsigned precedence, \
6292 expression_t *left) \
6294 (void) precedence; \
6297 expression_t *unary_expression \
6298 = allocate_expression_zero(unexpression_type); \
6299 unary_expression->unary.value = left; \
6301 sfunc(&unary_expression->unary); \
6303 return unary_expression; \
6306 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6307 EXPR_UNARY_POSTFIX_INCREMENT,
6309 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6310 EXPR_UNARY_POSTFIX_DECREMENT,
6313 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6315 /* TODO: handle complex + imaginary types */
6317 /* § 6.3.1.8 Usual arithmetic conversions */
6318 if(type_left == type_long_double || type_right == type_long_double) {
6319 return type_long_double;
6320 } else if(type_left == type_double || type_right == type_double) {
6322 } else if(type_left == type_float || type_right == type_float) {
6326 type_right = promote_integer(type_right);
6327 type_left = promote_integer(type_left);
6329 if(type_left == type_right)
6332 bool signed_left = is_type_signed(type_left);
6333 bool signed_right = is_type_signed(type_right);
6334 int rank_left = get_rank(type_left);
6335 int rank_right = get_rank(type_right);
6336 if(rank_left < rank_right) {
6337 if(signed_left == signed_right || !signed_right) {
6343 if(signed_left == signed_right || !signed_left) {
6352 * Check the semantic restrictions for a binary expression.
6354 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6356 expression_t *const left = expression->left;
6357 expression_t *const right = expression->right;
6358 type_t *const orig_type_left = left->base.type;
6359 type_t *const orig_type_right = right->base.type;
6360 type_t *const type_left = skip_typeref(orig_type_left);
6361 type_t *const type_right = skip_typeref(orig_type_right);
6363 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6364 /* TODO: improve error message */
6365 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6366 errorf(HERE, "operation needs arithmetic types");
6371 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6372 expression->left = create_implicit_cast(left, arithmetic_type);
6373 expression->right = create_implicit_cast(right, arithmetic_type);
6374 expression->base.type = arithmetic_type;
6377 static void semantic_shift_op(binary_expression_t *expression)
6379 expression_t *const left = expression->left;
6380 expression_t *const right = expression->right;
6381 type_t *const orig_type_left = left->base.type;
6382 type_t *const orig_type_right = right->base.type;
6383 type_t * type_left = skip_typeref(orig_type_left);
6384 type_t * type_right = skip_typeref(orig_type_right);
6386 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6387 /* TODO: improve error message */
6388 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6389 errorf(HERE, "operation needs integer types");
6394 type_left = promote_integer(type_left);
6395 type_right = promote_integer(type_right);
6397 expression->left = create_implicit_cast(left, type_left);
6398 expression->right = create_implicit_cast(right, type_right);
6399 expression->base.type = type_left;
6402 static void semantic_add(binary_expression_t *expression)
6404 expression_t *const left = expression->left;
6405 expression_t *const right = expression->right;
6406 type_t *const orig_type_left = left->base.type;
6407 type_t *const orig_type_right = right->base.type;
6408 type_t *const type_left = skip_typeref(orig_type_left);
6409 type_t *const type_right = skip_typeref(orig_type_right);
6412 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6413 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6414 expression->left = create_implicit_cast(left, arithmetic_type);
6415 expression->right = create_implicit_cast(right, arithmetic_type);
6416 expression->base.type = arithmetic_type;
6418 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6419 check_pointer_arithmetic(&expression->base.source_position,
6420 type_left, orig_type_left);
6421 expression->base.type = type_left;
6422 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6423 check_pointer_arithmetic(&expression->base.source_position,
6424 type_right, orig_type_right);
6425 expression->base.type = type_right;
6426 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6427 errorf(&expression->base.source_position,
6428 "invalid operands to binary + ('%T', '%T')",
6429 orig_type_left, orig_type_right);
6433 static void semantic_sub(binary_expression_t *expression)
6435 expression_t *const left = expression->left;
6436 expression_t *const right = expression->right;
6437 type_t *const orig_type_left = left->base.type;
6438 type_t *const orig_type_right = right->base.type;
6439 type_t *const type_left = skip_typeref(orig_type_left);
6440 type_t *const type_right = skip_typeref(orig_type_right);
6443 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6444 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6445 expression->left = create_implicit_cast(left, arithmetic_type);
6446 expression->right = create_implicit_cast(right, arithmetic_type);
6447 expression->base.type = arithmetic_type;
6449 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6450 check_pointer_arithmetic(&expression->base.source_position,
6451 type_left, orig_type_left);
6452 expression->base.type = type_left;
6453 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6454 if(!pointers_compatible(type_left, type_right)) {
6456 "pointers to incompatible objects to binary '-' ('%T', '%T')",
6457 orig_type_left, orig_type_right);
6459 expression->base.type = type_ptrdiff_t;
6461 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6462 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6463 orig_type_left, orig_type_right);
6468 * Check the semantics of comparison expressions.
6470 * @param expression The expression to check.
6472 static void semantic_comparison(binary_expression_t *expression)
6474 expression_t *left = expression->left;
6475 expression_t *right = expression->right;
6476 type_t *orig_type_left = left->base.type;
6477 type_t *orig_type_right = right->base.type;
6479 type_t *type_left = skip_typeref(orig_type_left);
6480 type_t *type_right = skip_typeref(orig_type_right);
6482 /* TODO non-arithmetic types */
6483 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6484 /* test for signed vs unsigned compares */
6485 if (warning.sign_compare &&
6486 (expression->base.kind != EXPR_BINARY_EQUAL &&
6487 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6488 (is_type_signed(type_left) != is_type_signed(type_right))) {
6490 /* check if 1 of the operands is a constant, in this case we just
6491 * check wether we can safely represent the resulting constant in
6492 * the type of the other operand. */
6493 expression_t *const_expr = NULL;
6494 expression_t *other_expr = NULL;
6496 if(is_constant_expression(left)) {
6499 } else if(is_constant_expression(right)) {
6504 if(const_expr != NULL) {
6505 type_t *other_type = skip_typeref(other_expr->base.type);
6506 long val = fold_constant(const_expr);
6507 /* TODO: check if val can be represented by other_type */
6511 warningf(&expression->base.source_position,
6512 "comparison between signed and unsigned");
6514 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6515 expression->left = create_implicit_cast(left, arithmetic_type);
6516 expression->right = create_implicit_cast(right, arithmetic_type);
6517 expression->base.type = arithmetic_type;
6518 if (warning.float_equal &&
6519 (expression->base.kind == EXPR_BINARY_EQUAL ||
6520 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6521 is_type_float(arithmetic_type)) {
6522 warningf(&expression->base.source_position,
6523 "comparing floating point with == or != is unsafe");
6525 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6526 /* TODO check compatibility */
6527 } else if (is_type_pointer(type_left)) {
6528 expression->right = create_implicit_cast(right, type_left);
6529 } else if (is_type_pointer(type_right)) {
6530 expression->left = create_implicit_cast(left, type_right);
6531 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6532 type_error_incompatible("invalid operands in comparison",
6533 &expression->base.source_position,
6534 type_left, type_right);
6536 expression->base.type = type_int;
6540 * Checks if a compound type has constant fields.
6542 static bool has_const_fields(const compound_type_t *type)
6544 const scope_t *scope = &type->declaration->scope;
6545 const declaration_t *declaration = scope->declarations;
6547 for (; declaration != NULL; declaration = declaration->next) {
6548 if (declaration->namespc != NAMESPACE_NORMAL)
6551 const type_t *decl_type = skip_typeref(declaration->type);
6552 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6559 static bool is_lvalue(const expression_t *expression)
6561 switch (expression->kind) {
6562 case EXPR_REFERENCE:
6563 case EXPR_ARRAY_ACCESS:
6565 case EXPR_UNARY_DEREFERENCE:
6573 static bool is_valid_assignment_lhs(expression_t const* const left)
6575 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6576 type_t *const type_left = skip_typeref(orig_type_left);
6578 if (!is_lvalue(left)) {
6579 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6584 if (is_type_array(type_left)) {
6585 errorf(HERE, "cannot assign to arrays ('%E')", left);
6588 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6589 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6593 if (is_type_incomplete(type_left)) {
6594 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6595 left, orig_type_left);
6598 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6599 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6600 left, orig_type_left);
6607 static void semantic_arithmetic_assign(binary_expression_t *expression)
6609 expression_t *left = expression->left;
6610 expression_t *right = expression->right;
6611 type_t *orig_type_left = left->base.type;
6612 type_t *orig_type_right = right->base.type;
6614 if (!is_valid_assignment_lhs(left))
6617 type_t *type_left = skip_typeref(orig_type_left);
6618 type_t *type_right = skip_typeref(orig_type_right);
6620 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6621 /* TODO: improve error message */
6622 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6623 errorf(HERE, "operation needs arithmetic types");
6628 /* combined instructions are tricky. We can't create an implicit cast on
6629 * the left side, because we need the uncasted form for the store.
6630 * The ast2firm pass has to know that left_type must be right_type
6631 * for the arithmetic operation and create a cast by itself */
6632 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6633 expression->right = create_implicit_cast(right, arithmetic_type);
6634 expression->base.type = type_left;
6637 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6639 expression_t *const left = expression->left;
6640 expression_t *const right = expression->right;
6641 type_t *const orig_type_left = left->base.type;
6642 type_t *const orig_type_right = right->base.type;
6643 type_t *const type_left = skip_typeref(orig_type_left);
6644 type_t *const type_right = skip_typeref(orig_type_right);
6646 if (!is_valid_assignment_lhs(left))
6649 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6650 /* combined instructions are tricky. We can't create an implicit cast on
6651 * the left side, because we need the uncasted form for the store.
6652 * The ast2firm pass has to know that left_type must be right_type
6653 * for the arithmetic operation and create a cast by itself */
6654 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6655 expression->right = create_implicit_cast(right, arithmetic_type);
6656 expression->base.type = type_left;
6657 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6658 check_pointer_arithmetic(&expression->base.source_position,
6659 type_left, orig_type_left);
6660 expression->base.type = type_left;
6661 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6662 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6667 * Check the semantic restrictions of a logical expression.
6669 static void semantic_logical_op(binary_expression_t *expression)
6671 expression_t *const left = expression->left;
6672 expression_t *const right = expression->right;
6673 type_t *const orig_type_left = left->base.type;
6674 type_t *const orig_type_right = right->base.type;
6675 type_t *const type_left = skip_typeref(orig_type_left);
6676 type_t *const type_right = skip_typeref(orig_type_right);
6678 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6679 /* TODO: improve error message */
6680 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6681 errorf(HERE, "operation needs scalar types");
6686 expression->base.type = type_int;
6690 * Check the semantic restrictions of a binary assign expression.
6692 static void semantic_binexpr_assign(binary_expression_t *expression)
6694 expression_t *left = expression->left;
6695 type_t *orig_type_left = left->base.type;
6697 type_t *type_left = revert_automatic_type_conversion(left);
6698 type_left = skip_typeref(orig_type_left);
6700 if (!is_valid_assignment_lhs(left))
6703 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6704 "assignment", &left->base.source_position);
6705 if (res_type == NULL) {
6706 errorf(&expression->base.source_position,
6707 "cannot assign to '%T' from '%T'",
6708 orig_type_left, expression->right->base.type);
6710 expression->right = create_implicit_cast(expression->right, res_type);
6713 expression->base.type = orig_type_left;
6717 * Determine if the outermost operation (or parts thereof) of the given
6718 * expression has no effect in order to generate a warning about this fact.
6719 * Therefore in some cases this only examines some of the operands of the
6720 * expression (see comments in the function and examples below).
6722 * f() + 23; // warning, because + has no effect
6723 * x || f(); // no warning, because x controls execution of f()
6724 * x ? y : f(); // warning, because y has no effect
6725 * (void)x; // no warning to be able to suppress the warning
6726 * This function can NOT be used for an "expression has definitely no effect"-
6728 static bool expression_has_effect(const expression_t *const expr)
6730 switch (expr->kind) {
6731 case EXPR_UNKNOWN: break;
6732 case EXPR_INVALID: return true; /* do NOT warn */
6733 case EXPR_REFERENCE: return false;
6734 /* suppress the warning for microsoft __noop operations */
6735 case EXPR_CONST: return expr->conste.is_ms_noop;
6736 case EXPR_CHARACTER_CONSTANT: return false;
6737 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6738 case EXPR_STRING_LITERAL: return false;
6739 case EXPR_WIDE_STRING_LITERAL: return false;
6742 const call_expression_t *const call = &expr->call;
6743 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6746 switch (call->function->builtin_symbol.symbol->ID) {
6747 case T___builtin_va_end: return true;
6748 default: return false;
6752 /* Generate the warning if either the left or right hand side of a
6753 * conditional expression has no effect */
6754 case EXPR_CONDITIONAL: {
6755 const conditional_expression_t *const cond = &expr->conditional;
6757 expression_has_effect(cond->true_expression) &&
6758 expression_has_effect(cond->false_expression);
6761 case EXPR_SELECT: return false;
6762 case EXPR_ARRAY_ACCESS: return false;
6763 case EXPR_SIZEOF: return false;
6764 case EXPR_CLASSIFY_TYPE: return false;
6765 case EXPR_ALIGNOF: return false;
6767 case EXPR_FUNCNAME: return false;
6768 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6769 case EXPR_BUILTIN_CONSTANT_P: return false;
6770 case EXPR_BUILTIN_PREFETCH: return true;
6771 case EXPR_OFFSETOF: return false;
6772 case EXPR_VA_START: return true;
6773 case EXPR_VA_ARG: return true;
6774 case EXPR_STATEMENT: return true; // TODO
6775 case EXPR_COMPOUND_LITERAL: return false;
6777 case EXPR_UNARY_NEGATE: return false;
6778 case EXPR_UNARY_PLUS: return false;
6779 case EXPR_UNARY_BITWISE_NEGATE: return false;
6780 case EXPR_UNARY_NOT: return false;
6781 case EXPR_UNARY_DEREFERENCE: return false;
6782 case EXPR_UNARY_TAKE_ADDRESS: return false;
6783 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6784 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6785 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6786 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6788 /* Treat void casts as if they have an effect in order to being able to
6789 * suppress the warning */
6790 case EXPR_UNARY_CAST: {
6791 type_t *const type = skip_typeref(expr->base.type);
6792 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6795 case EXPR_UNARY_CAST_IMPLICIT: return true;
6796 case EXPR_UNARY_ASSUME: return true;
6798 case EXPR_BINARY_ADD: return false;
6799 case EXPR_BINARY_SUB: return false;
6800 case EXPR_BINARY_MUL: return false;
6801 case EXPR_BINARY_DIV: return false;
6802 case EXPR_BINARY_MOD: return false;
6803 case EXPR_BINARY_EQUAL: return false;
6804 case EXPR_BINARY_NOTEQUAL: return false;
6805 case EXPR_BINARY_LESS: return false;
6806 case EXPR_BINARY_LESSEQUAL: return false;
6807 case EXPR_BINARY_GREATER: return false;
6808 case EXPR_BINARY_GREATEREQUAL: return false;
6809 case EXPR_BINARY_BITWISE_AND: return false;
6810 case EXPR_BINARY_BITWISE_OR: return false;
6811 case EXPR_BINARY_BITWISE_XOR: return false;
6812 case EXPR_BINARY_SHIFTLEFT: return false;
6813 case EXPR_BINARY_SHIFTRIGHT: return false;
6814 case EXPR_BINARY_ASSIGN: return true;
6815 case EXPR_BINARY_MUL_ASSIGN: return true;
6816 case EXPR_BINARY_DIV_ASSIGN: return true;
6817 case EXPR_BINARY_MOD_ASSIGN: return true;
6818 case EXPR_BINARY_ADD_ASSIGN: return true;
6819 case EXPR_BINARY_SUB_ASSIGN: return true;
6820 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6821 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6822 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6823 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6824 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6826 /* Only examine the right hand side of && and ||, because the left hand
6827 * side already has the effect of controlling the execution of the right
6829 case EXPR_BINARY_LOGICAL_AND:
6830 case EXPR_BINARY_LOGICAL_OR:
6831 /* Only examine the right hand side of a comma expression, because the left
6832 * hand side has a separate warning */
6833 case EXPR_BINARY_COMMA:
6834 return expression_has_effect(expr->binary.right);
6836 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6837 case EXPR_BINARY_ISGREATER: return false;
6838 case EXPR_BINARY_ISGREATEREQUAL: return false;
6839 case EXPR_BINARY_ISLESS: return false;
6840 case EXPR_BINARY_ISLESSEQUAL: return false;
6841 case EXPR_BINARY_ISLESSGREATER: return false;
6842 case EXPR_BINARY_ISUNORDERED: return false;
6845 internal_errorf(HERE, "unexpected expression");
6848 static void semantic_comma(binary_expression_t *expression)
6850 if (warning.unused_value) {
6851 const expression_t *const left = expression->left;
6852 if (!expression_has_effect(left)) {
6853 warningf(&left->base.source_position,
6854 "left-hand operand of comma expression has no effect");
6857 expression->base.type = expression->right->base.type;
6860 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6861 static expression_t *parse_##binexpression_type(unsigned precedence, \
6862 expression_t *left) \
6865 source_position_t pos = *HERE; \
6867 expression_t *right = parse_sub_expression(precedence + lr); \
6869 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6870 binexpr->base.source_position = pos; \
6871 binexpr->binary.left = left; \
6872 binexpr->binary.right = right; \
6873 sfunc(&binexpr->binary); \
6878 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6879 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6880 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6881 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6882 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6883 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6884 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6885 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6886 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6888 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6889 semantic_comparison, 1)
6890 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6891 semantic_comparison, 1)
6892 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6893 semantic_comparison, 1)
6894 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6895 semantic_comparison, 1)
6897 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6898 semantic_binexpr_arithmetic, 1)
6899 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6900 semantic_binexpr_arithmetic, 1)
6901 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6902 semantic_binexpr_arithmetic, 1)
6903 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6904 semantic_logical_op, 1)
6905 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6906 semantic_logical_op, 1)
6907 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6908 semantic_shift_op, 1)
6909 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6910 semantic_shift_op, 1)
6911 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6912 semantic_arithmetic_addsubb_assign, 0)
6913 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6914 semantic_arithmetic_addsubb_assign, 0)
6915 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6916 semantic_arithmetic_assign, 0)
6917 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6918 semantic_arithmetic_assign, 0)
6919 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6920 semantic_arithmetic_assign, 0)
6921 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6922 semantic_arithmetic_assign, 0)
6923 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6924 semantic_arithmetic_assign, 0)
6925 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6926 semantic_arithmetic_assign, 0)
6927 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6928 semantic_arithmetic_assign, 0)
6929 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6930 semantic_arithmetic_assign, 0)
6932 static expression_t *parse_sub_expression(unsigned precedence)
6934 if(token.type < 0) {
6935 return expected_expression_error();
6938 expression_parser_function_t *parser
6939 = &expression_parsers[token.type];
6940 source_position_t source_position = token.source_position;
6943 if(parser->parser != NULL) {
6944 left = parser->parser(parser->precedence);
6946 left = parse_primary_expression();
6948 assert(left != NULL);
6949 left->base.source_position = source_position;
6952 if(token.type < 0) {
6953 return expected_expression_error();
6956 parser = &expression_parsers[token.type];
6957 if(parser->infix_parser == NULL)
6959 if(parser->infix_precedence < precedence)
6962 left = parser->infix_parser(parser->infix_precedence, left);
6964 assert(left != NULL);
6965 assert(left->kind != EXPR_UNKNOWN);
6966 left->base.source_position = source_position;
6973 * Parse an expression.
6975 static expression_t *parse_expression(void)
6977 return parse_sub_expression(1);
6981 * Register a parser for a prefix-like operator with given precedence.
6983 * @param parser the parser function
6984 * @param token_type the token type of the prefix token
6985 * @param precedence the precedence of the operator
6987 static void register_expression_parser(parse_expression_function parser,
6988 int token_type, unsigned precedence)
6990 expression_parser_function_t *entry = &expression_parsers[token_type];
6992 if(entry->parser != NULL) {
6993 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6994 panic("trying to register multiple expression parsers for a token");
6996 entry->parser = parser;
6997 entry->precedence = precedence;
7001 * Register a parser for an infix operator with given precedence.
7003 * @param parser the parser function
7004 * @param token_type the token type of the infix operator
7005 * @param precedence the precedence of the operator
7007 static void register_infix_parser(parse_expression_infix_function parser,
7008 int token_type, unsigned precedence)
7010 expression_parser_function_t *entry = &expression_parsers[token_type];
7012 if(entry->infix_parser != NULL) {
7013 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7014 panic("trying to register multiple infix expression parsers for a "
7017 entry->infix_parser = parser;
7018 entry->infix_precedence = precedence;
7022 * Initialize the expression parsers.
7024 static void init_expression_parsers(void)
7026 memset(&expression_parsers, 0, sizeof(expression_parsers));
7028 register_infix_parser(parse_array_expression, '[', 30);
7029 register_infix_parser(parse_call_expression, '(', 30);
7030 register_infix_parser(parse_select_expression, '.', 30);
7031 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7032 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7034 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7037 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7038 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7039 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7040 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7041 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7042 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7043 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7044 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7045 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7046 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7047 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7048 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7049 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7050 T_EXCLAMATIONMARKEQUAL, 13);
7051 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7052 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7053 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7054 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7055 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7056 register_infix_parser(parse_conditional_expression, '?', 7);
7057 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7058 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7059 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7060 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7061 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7062 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7063 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7064 T_LESSLESSEQUAL, 2);
7065 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7066 T_GREATERGREATEREQUAL, 2);
7067 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7069 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7071 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7074 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7076 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7077 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7078 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7079 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7080 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7081 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7082 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7084 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7086 register_expression_parser(parse_sizeof, T_sizeof, 25);
7087 register_expression_parser(parse_alignof, T___alignof__, 25);
7088 register_expression_parser(parse_extension, T___extension__, 25);
7089 register_expression_parser(parse_builtin_classify_type,
7090 T___builtin_classify_type, 25);
7094 * Parse a asm statement arguments specification.
7096 static asm_argument_t *parse_asm_arguments(bool is_out)
7098 asm_argument_t *result = NULL;
7099 asm_argument_t *last = NULL;
7101 while(token.type == T_STRING_LITERAL || token.type == '[') {
7102 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7103 memset(argument, 0, sizeof(argument[0]));
7105 if(token.type == '[') {
7107 if(token.type != T_IDENTIFIER) {
7108 parse_error_expected("while parsing asm argument",
7109 T_IDENTIFIER, NULL);
7112 argument->symbol = token.v.symbol;
7117 argument->constraints = parse_string_literals();
7119 argument->expression = parse_expression();
7120 if (is_out && !is_lvalue(argument->expression)) {
7121 errorf(&argument->expression->base.source_position,
7122 "asm output argument is not an lvalue");
7127 last->next = argument;
7133 if(token.type != ',')
7144 * Parse a asm statement clobber specification.
7146 static asm_clobber_t *parse_asm_clobbers(void)
7148 asm_clobber_t *result = NULL;
7149 asm_clobber_t *last = NULL;
7151 while(token.type == T_STRING_LITERAL) {
7152 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7153 clobber->clobber = parse_string_literals();
7156 last->next = clobber;
7162 if(token.type != ',')
7171 * Parse an asm statement.
7173 static statement_t *parse_asm_statement(void)
7177 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7178 statement->base.source_position = token.source_position;
7180 asm_statement_t *asm_statement = &statement->asms;
7182 if(token.type == T_volatile) {
7184 asm_statement->is_volatile = true;
7188 add_anchor_token(')');
7189 add_anchor_token(':');
7190 asm_statement->asm_text = parse_string_literals();
7192 if(token.type != ':') {
7193 rem_anchor_token(':');
7198 asm_statement->outputs = parse_asm_arguments(true);
7199 if(token.type != ':') {
7200 rem_anchor_token(':');
7205 asm_statement->inputs = parse_asm_arguments(false);
7206 if(token.type != ':') {
7207 rem_anchor_token(':');
7210 rem_anchor_token(':');
7213 asm_statement->clobbers = parse_asm_clobbers();
7216 rem_anchor_token(')');
7221 return create_invalid_statement();
7225 * Parse a case statement.
7227 static statement_t *parse_case_statement(void)
7231 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7233 statement->base.source_position = token.source_position;
7234 statement->case_label.expression = parse_expression();
7236 if (c_mode & _GNUC) {
7237 if (token.type == T_DOTDOTDOT) {
7239 statement->case_label.end_range = parse_expression();
7245 if (! is_constant_expression(statement->case_label.expression)) {
7246 errorf(&statement->base.source_position,
7247 "case label does not reduce to an integer constant");
7249 /* TODO: check if the case label is already known */
7250 if (current_switch != NULL) {
7251 /* link all cases into the switch statement */
7252 if (current_switch->last_case == NULL) {
7253 current_switch->first_case =
7254 current_switch->last_case = &statement->case_label;
7256 current_switch->last_case->next = &statement->case_label;
7259 errorf(&statement->base.source_position,
7260 "case label not within a switch statement");
7263 statement->case_label.statement = parse_statement();
7267 return create_invalid_statement();
7271 * Finds an existing default label of a switch statement.
7273 static case_label_statement_t *
7274 find_default_label(const switch_statement_t *statement)
7276 case_label_statement_t *label = statement->first_case;
7277 for ( ; label != NULL; label = label->next) {
7278 if (label->expression == NULL)
7285 * Parse a default statement.
7287 static statement_t *parse_default_statement(void)
7291 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7293 statement->base.source_position = token.source_position;
7296 if (current_switch != NULL) {
7297 const case_label_statement_t *def_label = find_default_label(current_switch);
7298 if (def_label != NULL) {
7299 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7300 &def_label->base.source_position);
7302 /* link all cases into the switch statement */
7303 if (current_switch->last_case == NULL) {
7304 current_switch->first_case =
7305 current_switch->last_case = &statement->case_label;
7307 current_switch->last_case->next = &statement->case_label;
7311 errorf(&statement->base.source_position,
7312 "'default' label not within a switch statement");
7314 statement->case_label.statement = parse_statement();
7318 return create_invalid_statement();
7322 * Return the declaration for a given label symbol or create a new one.
7324 static declaration_t *get_label(symbol_t *symbol)
7326 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7327 assert(current_function != NULL);
7328 /* if we found a label in the same function, then we already created the
7330 if(candidate != NULL
7331 && candidate->parent_scope == ¤t_function->scope) {
7335 /* otherwise we need to create a new one */
7336 declaration_t *const declaration = allocate_declaration_zero();
7337 declaration->namespc = NAMESPACE_LABEL;
7338 declaration->symbol = symbol;
7340 label_push(declaration);
7346 * Parse a label statement.
7348 static statement_t *parse_label_statement(void)
7350 assert(token.type == T_IDENTIFIER);
7351 symbol_t *symbol = token.v.symbol;
7354 declaration_t *label = get_label(symbol);
7356 /* if source position is already set then the label is defined twice,
7357 * otherwise it was just mentioned in a goto so far */
7358 if(label->source_position.input_name != NULL) {
7359 errorf(HERE, "duplicate label '%Y' (declared %P)",
7360 symbol, &label->source_position);
7362 label->source_position = token.source_position;
7365 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7367 statement->base.source_position = token.source_position;
7368 statement->label.label = label;
7372 if(token.type == '}') {
7373 /* TODO only warn? */
7375 warningf(HERE, "label at end of compound statement");
7376 statement->label.statement = create_empty_statement();
7378 errorf(HERE, "label at end of compound statement");
7379 statement->label.statement = create_invalid_statement();
7383 if (token.type == ';') {
7384 /* eat an empty statement here, to avoid the warning about an empty
7385 * after a label. label:; is commonly used to have a label before
7387 statement->label.statement = create_empty_statement();
7390 statement->label.statement = parse_statement();
7394 /* remember the labels's in a list for later checking */
7395 if (label_last == NULL) {
7396 label_first = &statement->label;
7398 label_last->next = &statement->label;
7400 label_last = &statement->label;
7406 * Parse an if statement.
7408 static statement_t *parse_if(void)
7412 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7413 statement->base.source_position = token.source_position;
7416 add_anchor_token(')');
7417 statement->ifs.condition = parse_expression();
7418 rem_anchor_token(')');
7421 add_anchor_token(T_else);
7422 statement->ifs.true_statement = parse_statement();
7423 rem_anchor_token(T_else);
7425 if(token.type == T_else) {
7427 statement->ifs.false_statement = parse_statement();
7432 return create_invalid_statement();
7436 * Parse a switch statement.
7438 static statement_t *parse_switch(void)
7442 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7443 statement->base.source_position = token.source_position;
7446 expression_t *const expr = parse_expression();
7447 type_t * type = skip_typeref(expr->base.type);
7448 if (is_type_integer(type)) {
7449 type = promote_integer(type);
7450 } else if (is_type_valid(type)) {
7451 errorf(&expr->base.source_position,
7452 "switch quantity is not an integer, but '%T'", type);
7453 type = type_error_type;
7455 statement->switchs.expression = create_implicit_cast(expr, type);
7458 switch_statement_t *rem = current_switch;
7459 current_switch = &statement->switchs;
7460 statement->switchs.body = parse_statement();
7461 current_switch = rem;
7463 if(warning.switch_default &&
7464 find_default_label(&statement->switchs) == NULL) {
7465 warningf(&statement->base.source_position, "switch has no default case");
7470 return create_invalid_statement();
7473 static statement_t *parse_loop_body(statement_t *const loop)
7475 statement_t *const rem = current_loop;
7476 current_loop = loop;
7478 statement_t *const body = parse_statement();
7485 * Parse a while statement.
7487 static statement_t *parse_while(void)
7491 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7492 statement->base.source_position = token.source_position;
7495 add_anchor_token(')');
7496 statement->whiles.condition = parse_expression();
7497 rem_anchor_token(')');
7500 statement->whiles.body = parse_loop_body(statement);
7504 return create_invalid_statement();
7508 * Parse a do statement.
7510 static statement_t *parse_do(void)
7514 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7516 statement->base.source_position = token.source_position;
7518 add_anchor_token(T_while);
7519 statement->do_while.body = parse_loop_body(statement);
7520 rem_anchor_token(T_while);
7524 add_anchor_token(')');
7525 statement->do_while.condition = parse_expression();
7526 rem_anchor_token(')');
7532 return create_invalid_statement();
7536 * Parse a for statement.
7538 static statement_t *parse_for(void)
7542 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7543 statement->base.source_position = token.source_position;
7545 int top = environment_top();
7546 scope_t *last_scope = scope;
7547 set_scope(&statement->fors.scope);
7550 add_anchor_token(')');
7552 if(token.type != ';') {
7553 if(is_declaration_specifier(&token, false)) {
7554 parse_declaration(record_declaration);
7556 add_anchor_token(';');
7557 expression_t *const init = parse_expression();
7558 statement->fors.initialisation = init;
7559 if (warning.unused_value && !expression_has_effect(init)) {
7560 warningf(&init->base.source_position,
7561 "initialisation of 'for'-statement has no effect");
7563 rem_anchor_token(';');
7570 if(token.type != ';') {
7571 add_anchor_token(';');
7572 statement->fors.condition = parse_expression();
7573 rem_anchor_token(';');
7576 if(token.type != ')') {
7577 expression_t *const step = parse_expression();
7578 statement->fors.step = step;
7579 if (warning.unused_value && !expression_has_effect(step)) {
7580 warningf(&step->base.source_position,
7581 "step of 'for'-statement has no effect");
7584 rem_anchor_token(')');
7586 statement->fors.body = parse_loop_body(statement);
7588 assert(scope == &statement->fors.scope);
7589 set_scope(last_scope);
7590 environment_pop_to(top);
7595 rem_anchor_token(')');
7596 assert(scope == &statement->fors.scope);
7597 set_scope(last_scope);
7598 environment_pop_to(top);
7600 return create_invalid_statement();
7604 * Parse a goto statement.
7606 static statement_t *parse_goto(void)
7610 if(token.type != T_IDENTIFIER) {
7611 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7615 symbol_t *symbol = token.v.symbol;
7618 declaration_t *label = get_label(symbol);
7620 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7621 statement->base.source_position = token.source_position;
7623 statement->gotos.label = label;
7625 /* remember the goto's in a list for later checking */
7626 if (goto_last == NULL) {
7627 goto_first = &statement->gotos;
7629 goto_last->next = &statement->gotos;
7631 goto_last = &statement->gotos;
7637 return create_invalid_statement();
7641 * Parse a continue statement.
7643 static statement_t *parse_continue(void)
7645 statement_t *statement;
7646 if (current_loop == NULL) {
7647 errorf(HERE, "continue statement not within loop");
7648 statement = create_invalid_statement();
7650 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7652 statement->base.source_position = token.source_position;
7660 return create_invalid_statement();
7664 * Parse a break statement.
7666 static statement_t *parse_break(void)
7668 statement_t *statement;
7669 if (current_switch == NULL && current_loop == NULL) {
7670 errorf(HERE, "break statement not within loop or switch");
7671 statement = create_invalid_statement();
7673 statement = allocate_statement_zero(STATEMENT_BREAK);
7675 statement->base.source_position = token.source_position;
7683 return create_invalid_statement();
7687 * Parse a __leave statement.
7689 static statement_t *parse_leave(void)
7691 statement_t *statement;
7692 if (current_try == NULL) {
7693 errorf(HERE, "__leave statement not within __try");
7694 statement = create_invalid_statement();
7696 statement = allocate_statement_zero(STATEMENT_LEAVE);
7698 statement->base.source_position = token.source_position;
7706 return create_invalid_statement();
7710 * Check if a given declaration represents a local variable.
7712 static bool is_local_var_declaration(const declaration_t *declaration) {
7713 switch ((storage_class_tag_t) declaration->storage_class) {
7714 case STORAGE_CLASS_AUTO:
7715 case STORAGE_CLASS_REGISTER: {
7716 const type_t *type = skip_typeref(declaration->type);
7717 if(is_type_function(type)) {
7729 * Check if a given declaration represents a variable.
7731 static bool is_var_declaration(const declaration_t *declaration) {
7732 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7735 const type_t *type = skip_typeref(declaration->type);
7736 return !is_type_function(type);
7740 * Check if a given expression represents a local variable.
7742 static bool is_local_variable(const expression_t *expression)
7744 if (expression->base.kind != EXPR_REFERENCE) {
7747 const declaration_t *declaration = expression->reference.declaration;
7748 return is_local_var_declaration(declaration);
7752 * Check if a given expression represents a local variable and
7753 * return its declaration then, else return NULL.
7755 declaration_t *expr_is_variable(const expression_t *expression)
7757 if (expression->base.kind != EXPR_REFERENCE) {
7760 declaration_t *declaration = expression->reference.declaration;
7761 if (is_var_declaration(declaration))
7767 * Parse a return statement.
7769 static statement_t *parse_return(void)
7771 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7772 statement->base.source_position = token.source_position;
7776 expression_t *return_value = NULL;
7777 if(token.type != ';') {
7778 return_value = parse_expression();
7782 const type_t *const func_type = current_function->type;
7783 assert(is_type_function(func_type));
7784 type_t *const return_type = skip_typeref(func_type->function.return_type);
7786 if(return_value != NULL) {
7787 type_t *return_value_type = skip_typeref(return_value->base.type);
7789 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7790 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7791 warningf(&statement->base.source_position,
7792 "'return' with a value, in function returning void");
7793 return_value = NULL;
7795 type_t *const res_type = semantic_assign(return_type,
7796 return_value, "'return'", &statement->base.source_position);
7797 if (res_type == NULL) {
7798 errorf(&statement->base.source_position,
7799 "cannot return something of type '%T' in function returning '%T'",
7800 return_value->base.type, return_type);
7802 return_value = create_implicit_cast(return_value, res_type);
7805 /* check for returning address of a local var */
7806 if (return_value != NULL &&
7807 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7808 const expression_t *expression = return_value->unary.value;
7809 if (is_local_variable(expression)) {
7810 warningf(&statement->base.source_position,
7811 "function returns address of local variable");
7815 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7816 warningf(&statement->base.source_position,
7817 "'return' without value, in function returning non-void");
7820 statement->returns.value = return_value;
7824 return create_invalid_statement();
7828 * Parse a declaration statement.
7830 static statement_t *parse_declaration_statement(void)
7832 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7834 statement->base.source_position = token.source_position;
7836 declaration_t *before = last_declaration;
7837 parse_declaration(record_declaration);
7839 if(before == NULL) {
7840 statement->declaration.declarations_begin = scope->declarations;
7842 statement->declaration.declarations_begin = before->next;
7844 statement->declaration.declarations_end = last_declaration;
7850 * Parse an expression statement, ie. expr ';'.
7852 static statement_t *parse_expression_statement(void)
7854 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7856 statement->base.source_position = token.source_position;
7857 expression_t *const expr = parse_expression();
7858 statement->expression.expression = expr;
7864 return create_invalid_statement();
7868 * Parse a microsoft __try { } __finally { } or
7869 * __try{ } __except() { }
7871 static statement_t *parse_ms_try_statment(void) {
7872 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
7874 statement->base.source_position = token.source_position;
7877 ms_try_statement_t *rem = current_try;
7878 current_try = &statement->ms_try;
7879 statement->ms_try.try_statement = parse_compound_statement(false);
7882 if(token.type == T___except) {
7885 add_anchor_token(')');
7886 expression_t *const expr = parse_expression();
7887 type_t * type = skip_typeref(expr->base.type);
7888 if (is_type_integer(type)) {
7889 type = promote_integer(type);
7890 } else if (is_type_valid(type)) {
7891 errorf(&expr->base.source_position,
7892 "__expect expression is not an integer, but '%T'", type);
7893 type = type_error_type;
7895 statement->ms_try.except_expression = create_implicit_cast(expr, type);
7896 rem_anchor_token(')');
7898 statement->ms_try.final_statement = parse_compound_statement(false);
7899 } else if(token.type == T__finally) {
7901 statement->ms_try.final_statement = parse_compound_statement(false);
7903 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
7904 return create_invalid_statement();
7908 return create_invalid_statement();
7912 * Parse a statement.
7913 * There's also parse_statement() which additionally checks for
7914 * "statement has no effect" warnings
7916 static statement_t *intern_parse_statement(void)
7918 statement_t *statement = NULL;
7920 /* declaration or statement */
7921 add_anchor_token(';');
7922 switch(token.type) {
7924 statement = parse_asm_statement();
7928 statement = parse_case_statement();
7932 statement = parse_default_statement();
7936 statement = parse_compound_statement(false);
7940 statement = parse_if();
7944 statement = parse_switch();
7948 statement = parse_while();
7952 statement = parse_do();
7956 statement = parse_for();
7960 statement = parse_goto();
7964 statement = parse_continue();
7968 statement = parse_break();
7972 statement = parse_leave();
7976 statement = parse_return();
7980 if(warning.empty_statement) {
7981 warningf(HERE, "statement is empty");
7983 statement = create_empty_statement();
7988 if(look_ahead(1)->type == ':') {
7989 statement = parse_label_statement();
7993 if(is_typedef_symbol(token.v.symbol)) {
7994 statement = parse_declaration_statement();
7998 statement = parse_expression_statement();
8001 case T___extension__:
8002 /* this can be a prefix to a declaration or an expression statement */
8003 /* we simply eat it now and parse the rest with tail recursion */
8006 } while(token.type == T___extension__);
8007 statement = parse_statement();
8011 statement = parse_declaration_statement();
8015 statement = parse_ms_try_statment();
8019 statement = parse_expression_statement();
8022 rem_anchor_token(';');
8024 assert(statement != NULL
8025 && statement->base.source_position.input_name != NULL);
8031 * parse a statement and emits "statement has no effect" warning if needed
8032 * (This is really a wrapper around intern_parse_statement with check for 1
8033 * single warning. It is needed, because for statement expressions we have
8034 * to avoid the warning on the last statement)
8036 static statement_t *parse_statement(void)
8038 statement_t *statement = intern_parse_statement();
8040 if(statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8041 expression_t *expression = statement->expression.expression;
8042 if(!expression_has_effect(expression)) {
8043 warningf(&expression->base.source_position,
8044 "statement has no effect");
8052 * Parse a compound statement.
8054 static statement_t *parse_compound_statement(bool inside_expression_statement)
8056 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8058 statement->base.source_position = token.source_position;
8061 add_anchor_token('}');
8063 int top = environment_top();
8064 scope_t *last_scope = scope;
8065 set_scope(&statement->compound.scope);
8067 statement_t *last_statement = NULL;
8069 while(token.type != '}' && token.type != T_EOF) {
8070 statement_t *sub_statement = intern_parse_statement();
8071 if(is_invalid_statement(sub_statement)) {
8072 /* an error occurred. if we are at an anchor, return */
8078 if(last_statement != NULL) {
8079 last_statement->base.next = sub_statement;
8081 statement->compound.statements = sub_statement;
8084 while(sub_statement->base.next != NULL)
8085 sub_statement = sub_statement->base.next;
8087 last_statement = sub_statement;
8090 if(token.type == '}') {
8093 errorf(&statement->base.source_position,
8094 "end of file while looking for closing '}'");
8097 /* look over all statements again to produce no effect warnings */
8098 if(warning.unused_value) {
8099 statement_t *sub_statement = statement->compound.statements;
8100 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8101 if(sub_statement->kind != STATEMENT_EXPRESSION)
8103 /* don't emit a warning for the last expression in an expression
8104 * statement as it has always an effect */
8105 if(inside_expression_statement && sub_statement->base.next == NULL)
8108 expression_t *expression = sub_statement->expression.expression;
8109 if(!expression_has_effect(expression)) {
8110 warningf(&expression->base.source_position,
8111 "statement has no effect");
8117 rem_anchor_token('}');
8118 assert(scope == &statement->compound.scope);
8119 set_scope(last_scope);
8120 environment_pop_to(top);
8126 * Initialize builtin types.
8128 static void initialize_builtin_types(void)
8130 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8131 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8132 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8133 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8134 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8135 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8136 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8137 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8139 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8140 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8141 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8142 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8146 * Check for unused global static functions and variables
8148 static void check_unused_globals(void)
8150 if (!warning.unused_function && !warning.unused_variable)
8153 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8154 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
8157 type_t *const type = decl->type;
8159 if (is_type_function(skip_typeref(type))) {
8160 if (!warning.unused_function || decl->is_inline)
8163 s = (decl->init.statement != NULL ? "defined" : "declared");
8165 if (!warning.unused_variable)
8171 warningf(&decl->source_position, "'%#T' %s but not used",
8172 type, decl->symbol, s);
8177 * Parse a translation unit.
8179 static void parse_translation_unit(void)
8181 while(token.type != T_EOF) {
8182 if (token.type == ';') {
8183 /* TODO error in strict mode */
8184 warningf(HERE, "stray ';' outside of function");
8187 parse_external_declaration();
8195 * @return the translation unit or NULL if errors occurred.
8197 void start_parsing(void)
8199 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8200 label_stack = NEW_ARR_F(stack_entry_t, 0);
8201 diagnostic_count = 0;
8205 type_set_output(stderr);
8206 ast_set_output(stderr);
8208 assert(unit == NULL);
8209 unit = allocate_ast_zero(sizeof(unit[0]));
8211 assert(global_scope == NULL);
8212 global_scope = &unit->scope;
8214 assert(scope == NULL);
8215 set_scope(&unit->scope);
8217 initialize_builtin_types();
8220 translation_unit_t *finish_parsing(void)
8222 assert(scope == &unit->scope);
8224 last_declaration = NULL;
8226 assert(global_scope == &unit->scope);
8227 check_unused_globals();
8228 global_scope = NULL;
8230 DEL_ARR_F(environment_stack);
8231 DEL_ARR_F(label_stack);
8233 translation_unit_t *result = unit;
8240 lookahead_bufpos = 0;
8241 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8244 parse_translation_unit();
8248 * Initialize the parser.
8250 void init_parser(void)
8253 /* add predefined symbols for extended-decl-modifier */
8254 sym_align = symbol_table_insert("align");
8255 sym_allocate = symbol_table_insert("allocate");
8256 sym_dllimport = symbol_table_insert("dllimport");
8257 sym_dllexport = symbol_table_insert("dllexport");
8258 sym_naked = symbol_table_insert("naked");
8259 sym_noinline = symbol_table_insert("noinline");
8260 sym_noreturn = symbol_table_insert("noreturn");
8261 sym_nothrow = symbol_table_insert("nothrow");
8262 sym_novtable = symbol_table_insert("novtable");
8263 sym_property = symbol_table_insert("property");
8264 sym_get = symbol_table_insert("get");
8265 sym_put = symbol_table_insert("put");
8266 sym_selectany = symbol_table_insert("selectany");
8267 sym_thread = symbol_table_insert("thread");
8268 sym_uuid = symbol_table_insert("uuid");
8269 sym_deprecated = symbol_table_insert("deprecated");
8270 sym_restrict = symbol_table_insert("restrict");
8271 sym_noalias = symbol_table_insert("noalias");
8273 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8275 init_expression_parsers();
8276 obstack_init(&temp_obst);
8278 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8279 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8283 * Terminate the parser.
8285 void exit_parser(void)
8287 obstack_free(&temp_obst, NULL);