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 decl_modifiers; /**< MS __declspec extended modifier mask */
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;
1315 * Parse one GNU attribute.
1317 * Note that attribute names can be specified WITH or WITHOUT
1318 * double underscores, ie const or __const__.
1320 * The following attributes are parsed without arguments
1345 * no_instrument_function
1346 * warn_unused_result
1363 * externally_visible
1371 * The following attributes are parsed with arguments
1372 * aligned( const expression )
1373 * alias( string literal )
1374 * section( string literal )
1375 * format( identifier, const expression, const expression )
1376 * format_arg( const expression )
1377 * tls_model( string literal )
1378 * visibility( string literal )
1379 * regparm( const expression )
1380 * model( string leteral )
1381 * trap_exit( const expression )
1382 * sp_switch( string literal )
1384 * The following attributes might have arguments
1385 * weak_ref( string literal )
1386 * non_null( const expression // ',' )
1387 * interrupt( string literal )
1388 * sentinel( constant expression )
1390 static void parse_gnu_attribute(gnu_attribute_t **attributes)
1392 gnu_attribute_t *head = *attributes;
1393 gnu_attribute_t *last = *attributes;
1394 gnu_attribute_t *attribute;
1396 eat(T___attribute__);
1400 if(token.type != ')') {
1401 /* find the end of the list */
1403 while(last->next != NULL)
1407 /* non-empty attribute list */
1410 if(token.type == T_const) {
1412 } else if(token.type == T_volatile) {
1414 } else if(token.type == T_cdecl) {
1415 /* __attribute__((cdecl)), WITH ms mode */
1417 } else if(token.type != T_IDENTIFIER) {
1418 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1421 const symbol_t *sym = token.v.symbol;
1426 for(i = 0; i < GNU_AK_LAST; ++i) {
1427 if(strcmp_underscore(gnu_attribute_names[i], name) == 0)
1430 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1433 if(kind == GNU_AK_LAST) {
1434 if(warning.attribute)
1435 warningf(HERE, "'%s' attribute directive ignored", name);
1437 /* skip possible arguments */
1438 if(token.type == '(') {
1439 eat_until_matching_token(')');
1442 /* check for arguments */
1443 attribute = allocate_gnu_attribute(kind);
1444 if(token.type == '(') {
1446 if(token.type == ')') {
1447 /* empty args are allowed */
1450 attribute->have_arguments = true;
1455 case GNU_AK_VOLATILE:
1457 case GNU_AK_STDCALL:
1458 case GNU_AK_FASTCALL:
1459 case GNU_AK_DEPRECATED:
1460 case GNU_AK_NOINLINE:
1461 case GNU_AK_NORETURN:
1464 case GNU_AK_ALWAYS_INLINE:
1467 case GNU_AK_CONSTRUCTOR:
1468 case GNU_AK_DESTRUCTOR:
1469 case GNU_AK_NOTHROW:
1470 case GNU_AK_TRANSPARENT_UNION:
1472 case GNU_AK_NOCOMMON:
1475 case GNU_AK_NOTSHARED:
1478 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1479 case GNU_AK_WARN_UNUSED_RESULT:
1480 case GNU_AK_LONGCALL:
1481 case GNU_AK_SHORTCALL:
1482 case GNU_AK_LONG_CALL:
1483 case GNU_AK_SHORT_CALL:
1484 case GNU_AK_FUNCTION_VECTOR:
1485 case GNU_AK_INTERRUPT_HANDLER:
1486 case GNU_AK_NMI_HANDLER:
1487 case GNU_AK_NESTING:
1491 case GNU_AK_EIGTHBIT_DATA:
1492 case GNU_AK_TINY_DATA:
1493 case GNU_AK_SAVEALL:
1494 case GNU_AK_FLATTEN:
1495 case GNU_AK_SSEREGPARM:
1496 case GNU_AK_EXTERNALLY_VISIBLE:
1497 case GNU_AK_RETURN_TWICE:
1498 case GNU_AK_MAY_ALIAS:
1499 case GNU_AK_MS_STRUCT:
1500 case GNU_AK_GCC_STRUCT:
1501 case GNU_AK_DLLIMPORT:
1502 case GNU_AK_DLLEXPORT:
1503 if(attribute->have_arguments) {
1504 /* should have no arguments */
1505 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1506 eat_until_matching_token('(');
1507 /* we have already consumed '(', so we stop before ')', eat it */
1509 attribute->invalid = true;
1513 case GNU_AK_ALIGNED:
1514 case GNU_AK_FORMAT_ARG:
1515 case GNU_AK_REGPARM:
1516 case GNU_AK_TRAP_EXIT:
1517 if(!attribute->have_arguments) {
1518 /* should have arguments */
1519 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1520 attribute->invalid = true;
1522 parse_gnu_attribute_const_arg(attribute);
1525 case GNU_AK_SECTION:
1526 case GNU_AK_SP_SWITCH:
1527 if(!attribute->have_arguments) {
1528 /* should have arguments */
1529 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1530 attribute->invalid = true;
1532 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1535 if(!attribute->have_arguments) {
1536 /* should have arguments */
1537 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1538 attribute->invalid = true;
1540 parse_gnu_attribute_format_args(attribute);
1542 case GNU_AK_WEAKREF:
1543 /* may have one string argument */
1544 if(attribute->have_arguments)
1545 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1547 case GNU_AK_NONNULL:
1548 if(attribute->have_arguments)
1549 parse_gnu_attribute_const_arg_list(attribute);
1551 case GNU_AK_TLS_MODEL:
1552 if(!attribute->have_arguments) {
1553 /* should have arguments */
1554 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1556 parse_gnu_attribute_tls_model_arg(attribute);
1558 case GNU_AK_VISIBILITY:
1559 if(!attribute->have_arguments) {
1560 /* should have arguments */
1561 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1563 parse_gnu_attribute_visibility_arg(attribute);
1566 if(!attribute->have_arguments) {
1567 /* should have arguments */
1568 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1570 parse_gnu_attribute_model_arg(attribute);
1574 if(!attribute->have_arguments) {
1575 /* should have arguments */
1576 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1578 parse_gnu_attribute_mode_arg(attribute);
1581 case GNU_AK_INTERRUPT:
1582 /* may have one string argument */
1583 if(attribute->have_arguments)
1584 parse_gnu_attribute_interrupt_arg(attribute);
1586 case GNU_AK_SENTINEL:
1587 /* may have one string argument */
1588 if(attribute->have_arguments)
1589 parse_gnu_attribute_const_arg(attribute);
1592 /* already handled */
1596 if(attribute != NULL) {
1598 last->next = attribute;
1601 head = last = attribute;
1605 if(token.type != ',')
1617 * Parse GNU attributes.
1619 static void parse_attributes(gnu_attribute_t **attributes)
1622 switch(token.type) {
1623 case T___attribute__: {
1624 parse_gnu_attribute(attributes);
1630 if(token.type != T_STRING_LITERAL) {
1631 parse_error_expected("while parsing assembler attribute",
1632 T_STRING_LITERAL, NULL);
1633 eat_until_matching_token('(');
1636 parse_string_literals();
1641 goto attributes_finished;
1645 attributes_finished:
1650 static designator_t *parse_designation(void)
1652 designator_t *result = NULL;
1653 designator_t *last = NULL;
1656 designator_t *designator;
1657 switch(token.type) {
1659 designator = allocate_ast_zero(sizeof(designator[0]));
1660 designator->source_position = token.source_position;
1662 add_anchor_token(']');
1663 designator->array_index = parse_constant_expression();
1664 rem_anchor_token(']');
1668 designator = allocate_ast_zero(sizeof(designator[0]));
1669 designator->source_position = token.source_position;
1671 if(token.type != T_IDENTIFIER) {
1672 parse_error_expected("while parsing designator",
1673 T_IDENTIFIER, NULL);
1676 designator->symbol = token.v.symbol;
1684 assert(designator != NULL);
1686 last->next = designator;
1688 result = designator;
1696 static initializer_t *initializer_from_string(array_type_t *type,
1697 const string_t *const string)
1699 /* TODO: check len vs. size of array type */
1702 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1703 initializer->string.string = *string;
1708 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1709 wide_string_t *const string)
1711 /* TODO: check len vs. size of array type */
1714 initializer_t *const initializer =
1715 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1716 initializer->wide_string.string = *string;
1722 * Build an initializer from a given expression.
1724 static initializer_t *initializer_from_expression(type_t *orig_type,
1725 expression_t *expression)
1727 /* TODO check that expression is a constant expression */
1729 /* § 6.7.8.14/15 char array may be initialized by string literals */
1730 type_t *type = skip_typeref(orig_type);
1731 type_t *expr_type_orig = expression->base.type;
1732 type_t *expr_type = skip_typeref(expr_type_orig);
1733 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1734 array_type_t *const array_type = &type->array;
1735 type_t *const element_type = skip_typeref(array_type->element_type);
1737 if (element_type->kind == TYPE_ATOMIC) {
1738 atomic_type_kind_t akind = element_type->atomic.akind;
1739 switch (expression->kind) {
1740 case EXPR_STRING_LITERAL:
1741 if (akind == ATOMIC_TYPE_CHAR
1742 || akind == ATOMIC_TYPE_SCHAR
1743 || akind == ATOMIC_TYPE_UCHAR) {
1744 return initializer_from_string(array_type,
1745 &expression->string.value);
1748 case EXPR_WIDE_STRING_LITERAL: {
1749 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1750 if (get_unqualified_type(element_type) == bare_wchar_type) {
1751 return initializer_from_wide_string(array_type,
1752 &expression->wide_string.value);
1762 type_t *const res_type = semantic_assign(type, expression, "initializer",
1763 &expression->base.source_position);
1764 if (res_type == NULL)
1767 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1768 result->value.value = create_implicit_cast(expression, res_type);
1774 * Checks if a given expression can be used as an constant initializer.
1776 static bool is_initializer_constant(const expression_t *expression)
1778 return is_constant_expression(expression)
1779 || is_address_constant(expression);
1783 * Parses an scalar initializer.
1785 * § 6.7.8.11; eat {} without warning
1787 static initializer_t *parse_scalar_initializer(type_t *type,
1788 bool must_be_constant)
1790 /* there might be extra {} hierarchies */
1792 while(token.type == '{') {
1795 warningf(HERE, "extra curly braces around scalar initializer");
1800 expression_t *expression = parse_assignment_expression();
1801 if(must_be_constant && !is_initializer_constant(expression)) {
1802 errorf(&expression->base.source_position,
1803 "Initialisation expression '%E' is not constant\n",
1807 initializer_t *initializer = initializer_from_expression(type, expression);
1809 if(initializer == NULL) {
1810 errorf(&expression->base.source_position,
1811 "expression '%E' (type '%T') doesn't match expected type '%T'",
1812 expression, expression->base.type, type);
1817 bool additional_warning_displayed = false;
1819 if(token.type == ',') {
1822 if(token.type != '}') {
1823 if(!additional_warning_displayed) {
1824 warningf(HERE, "additional elements in scalar initializer");
1825 additional_warning_displayed = true;
1836 * An entry in the type path.
1838 typedef struct type_path_entry_t type_path_entry_t;
1839 struct type_path_entry_t {
1840 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1842 size_t index; /**< For array types: the current index. */
1843 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1848 * A type path expression a position inside compound or array types.
1850 typedef struct type_path_t type_path_t;
1851 struct type_path_t {
1852 type_path_entry_t *path; /**< An flexible array containing the current path. */
1853 type_t *top_type; /**< type of the element the path points */
1854 size_t max_index; /**< largest index in outermost array */
1858 * Prints a type path for debugging.
1860 static __attribute__((unused)) void debug_print_type_path(
1861 const type_path_t *path)
1863 size_t len = ARR_LEN(path->path);
1865 for(size_t i = 0; i < len; ++i) {
1866 const type_path_entry_t *entry = & path->path[i];
1868 type_t *type = skip_typeref(entry->type);
1869 if(is_type_compound(type)) {
1870 /* in gcc mode structs can have no members */
1871 if(entry->v.compound_entry == NULL) {
1875 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1876 } else if(is_type_array(type)) {
1877 fprintf(stderr, "[%zd]", entry->v.index);
1879 fprintf(stderr, "-INVALID-");
1882 if(path->top_type != NULL) {
1883 fprintf(stderr, " (");
1884 print_type(path->top_type);
1885 fprintf(stderr, ")");
1890 * Return the top type path entry, ie. in a path
1891 * (type).a.b returns the b.
1893 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1895 size_t len = ARR_LEN(path->path);
1897 return &path->path[len-1];
1901 * Enlarge the type path by an (empty) element.
1903 static type_path_entry_t *append_to_type_path(type_path_t *path)
1905 size_t len = ARR_LEN(path->path);
1906 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1908 type_path_entry_t *result = & path->path[len];
1909 memset(result, 0, sizeof(result[0]));
1914 * Descending into a sub-type. Enter the scope of the current
1917 static void descend_into_subtype(type_path_t *path)
1919 type_t *orig_top_type = path->top_type;
1920 type_t *top_type = skip_typeref(orig_top_type);
1922 assert(is_type_compound(top_type) || is_type_array(top_type));
1924 type_path_entry_t *top = append_to_type_path(path);
1925 top->type = top_type;
1927 if(is_type_compound(top_type)) {
1928 declaration_t *declaration = top_type->compound.declaration;
1929 declaration_t *entry = declaration->scope.declarations;
1930 top->v.compound_entry = entry;
1933 path->top_type = entry->type;
1935 path->top_type = NULL;
1938 assert(is_type_array(top_type));
1941 path->top_type = top_type->array.element_type;
1946 * Pop an entry from the given type path, ie. returning from
1947 * (type).a.b to (type).a
1949 static void ascend_from_subtype(type_path_t *path)
1951 type_path_entry_t *top = get_type_path_top(path);
1953 path->top_type = top->type;
1955 size_t len = ARR_LEN(path->path);
1956 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1960 * Pop entries from the given type path until the given
1961 * path level is reached.
1963 static void ascend_to(type_path_t *path, size_t top_path_level)
1965 size_t len = ARR_LEN(path->path);
1967 while(len > top_path_level) {
1968 ascend_from_subtype(path);
1969 len = ARR_LEN(path->path);
1973 static bool walk_designator(type_path_t *path, const designator_t *designator,
1974 bool used_in_offsetof)
1976 for( ; designator != NULL; designator = designator->next) {
1977 type_path_entry_t *top = get_type_path_top(path);
1978 type_t *orig_type = top->type;
1980 type_t *type = skip_typeref(orig_type);
1982 if(designator->symbol != NULL) {
1983 symbol_t *symbol = designator->symbol;
1984 if(!is_type_compound(type)) {
1985 if(is_type_valid(type)) {
1986 errorf(&designator->source_position,
1987 "'.%Y' designator used for non-compound type '%T'",
1993 declaration_t *declaration = type->compound.declaration;
1994 declaration_t *iter = declaration->scope.declarations;
1995 for( ; iter != NULL; iter = iter->next) {
1996 if(iter->symbol == symbol) {
2001 errorf(&designator->source_position,
2002 "'%T' has no member named '%Y'", orig_type, symbol);
2005 if(used_in_offsetof) {
2006 type_t *real_type = skip_typeref(iter->type);
2007 if(real_type->kind == TYPE_BITFIELD) {
2008 errorf(&designator->source_position,
2009 "offsetof designator '%Y' may not specify bitfield",
2015 top->type = orig_type;
2016 top->v.compound_entry = iter;
2017 orig_type = iter->type;
2019 expression_t *array_index = designator->array_index;
2020 assert(designator->array_index != NULL);
2022 if(!is_type_array(type)) {
2023 if(is_type_valid(type)) {
2024 errorf(&designator->source_position,
2025 "[%E] designator used for non-array type '%T'",
2026 array_index, orig_type);
2030 if(!is_type_valid(array_index->base.type)) {
2034 long index = fold_constant(array_index);
2035 if(!used_in_offsetof) {
2037 errorf(&designator->source_position,
2038 "array index [%E] must be positive", array_index);
2041 if(type->array.size_constant == true) {
2042 long array_size = type->array.size;
2043 if(index >= array_size) {
2044 errorf(&designator->source_position,
2045 "designator [%E] (%d) exceeds array size %d",
2046 array_index, index, array_size);
2052 top->type = orig_type;
2053 top->v.index = (size_t) index;
2054 orig_type = type->array.element_type;
2056 path->top_type = orig_type;
2058 if(designator->next != NULL) {
2059 descend_into_subtype(path);
2068 static void advance_current_object(type_path_t *path, size_t top_path_level)
2070 type_path_entry_t *top = get_type_path_top(path);
2072 type_t *type = skip_typeref(top->type);
2073 if(is_type_union(type)) {
2074 /* in unions only the first element is initialized */
2075 top->v.compound_entry = NULL;
2076 } else if(is_type_struct(type)) {
2077 declaration_t *entry = top->v.compound_entry;
2079 entry = entry->next;
2080 top->v.compound_entry = entry;
2082 path->top_type = entry->type;
2086 assert(is_type_array(type));
2090 if(!type->array.size_constant || top->v.index < type->array.size) {
2095 /* we're past the last member of the current sub-aggregate, try if we
2096 * can ascend in the type hierarchy and continue with another subobject */
2097 size_t len = ARR_LEN(path->path);
2099 if(len > top_path_level) {
2100 ascend_from_subtype(path);
2101 advance_current_object(path, top_path_level);
2103 path->top_type = NULL;
2108 * skip until token is found.
2110 static void skip_until(int type) {
2111 while(token.type != type) {
2112 if(token.type == T_EOF)
2119 * skip any {...} blocks until a closing bracket is reached.
2121 static void skip_initializers(void)
2123 if(token.type == '{')
2126 while(token.type != '}') {
2127 if(token.type == T_EOF)
2129 if(token.type == '{') {
2137 static initializer_t *create_empty_initializer(void)
2139 static initializer_t empty_initializer
2140 = { .list = { { INITIALIZER_LIST }, 0 } };
2141 return &empty_initializer;
2145 * Parse a part of an initialiser for a struct or union,
2147 static initializer_t *parse_sub_initializer(type_path_t *path,
2148 type_t *outer_type, size_t top_path_level,
2149 parse_initializer_env_t *env)
2151 if(token.type == '}') {
2152 /* empty initializer */
2153 return create_empty_initializer();
2156 type_t *orig_type = path->top_type;
2157 type_t *type = NULL;
2159 if (orig_type == NULL) {
2160 /* We are initializing an empty compound. */
2162 type = skip_typeref(orig_type);
2164 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2165 * initializers in this case. */
2166 if(!is_type_valid(type)) {
2167 skip_initializers();
2168 return create_empty_initializer();
2172 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2175 designator_t *designator = NULL;
2176 if(token.type == '.' || token.type == '[') {
2177 designator = parse_designation();
2179 /* reset path to toplevel, evaluate designator from there */
2180 ascend_to(path, top_path_level);
2181 if(!walk_designator(path, designator, false)) {
2182 /* can't continue after designation error */
2186 initializer_t *designator_initializer
2187 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2188 designator_initializer->designator.designator = designator;
2189 ARR_APP1(initializer_t*, initializers, designator_initializer);
2191 orig_type = path->top_type;
2192 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2197 if(token.type == '{') {
2198 if(type != NULL && is_type_scalar(type)) {
2199 sub = parse_scalar_initializer(type, env->must_be_constant);
2203 if (env->declaration != NULL)
2204 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2205 env->declaration->symbol);
2207 errorf(HERE, "extra brace group at end of initializer");
2209 descend_into_subtype(path);
2211 add_anchor_token('}');
2212 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2214 rem_anchor_token('}');
2217 ascend_from_subtype(path);
2221 goto error_parse_next;
2225 /* must be an expression */
2226 expression_t *expression = parse_assignment_expression();
2228 if(env->must_be_constant && !is_initializer_constant(expression)) {
2229 errorf(&expression->base.source_position,
2230 "Initialisation expression '%E' is not constant\n",
2235 /* we are already outside, ... */
2239 /* handle { "string" } special case */
2240 if((expression->kind == EXPR_STRING_LITERAL
2241 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2242 && outer_type != NULL) {
2243 sub = initializer_from_expression(outer_type, expression);
2245 if(token.type == ',') {
2248 if(token.type != '}') {
2249 warningf(HERE, "excessive elements in initializer for type '%T'",
2252 /* TODO: eat , ... */
2257 /* descend into subtypes until expression matches type */
2259 orig_type = path->top_type;
2260 type = skip_typeref(orig_type);
2262 sub = initializer_from_expression(orig_type, expression);
2266 if(!is_type_valid(type)) {
2269 if(is_type_scalar(type)) {
2270 errorf(&expression->base.source_position,
2271 "expression '%E' doesn't match expected type '%T'",
2272 expression, orig_type);
2276 descend_into_subtype(path);
2280 /* update largest index of top array */
2281 const type_path_entry_t *first = &path->path[0];
2282 type_t *first_type = first->type;
2283 first_type = skip_typeref(first_type);
2284 if(is_type_array(first_type)) {
2285 size_t index = first->v.index;
2286 if(index > path->max_index)
2287 path->max_index = index;
2291 /* append to initializers list */
2292 ARR_APP1(initializer_t*, initializers, sub);
2295 if(env->declaration != NULL)
2296 warningf(HERE, "excess elements in struct initializer for '%Y'",
2297 env->declaration->symbol);
2299 warningf(HERE, "excess elements in struct initializer");
2303 if(token.type == '}') {
2307 if(token.type == '}') {
2312 /* advance to the next declaration if we are not at the end */
2313 advance_current_object(path, top_path_level);
2314 orig_type = path->top_type;
2315 if(orig_type != NULL)
2316 type = skip_typeref(orig_type);
2322 size_t len = ARR_LEN(initializers);
2323 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2324 initializer_t *result = allocate_ast_zero(size);
2325 result->kind = INITIALIZER_LIST;
2326 result->list.len = len;
2327 memcpy(&result->list.initializers, initializers,
2328 len * sizeof(initializers[0]));
2330 DEL_ARR_F(initializers);
2331 ascend_to(path, top_path_level+1);
2336 skip_initializers();
2337 DEL_ARR_F(initializers);
2338 ascend_to(path, top_path_level+1);
2343 * Parses an initializer. Parsers either a compound literal
2344 * (env->declaration == NULL) or an initializer of a declaration.
2346 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2348 type_t *type = skip_typeref(env->type);
2349 initializer_t *result = NULL;
2352 if(is_type_scalar(type)) {
2353 result = parse_scalar_initializer(type, env->must_be_constant);
2354 } else if(token.type == '{') {
2358 memset(&path, 0, sizeof(path));
2359 path.top_type = env->type;
2360 path.path = NEW_ARR_F(type_path_entry_t, 0);
2362 descend_into_subtype(&path);
2364 add_anchor_token('}');
2365 result = parse_sub_initializer(&path, env->type, 1, env);
2366 rem_anchor_token('}');
2368 max_index = path.max_index;
2369 DEL_ARR_F(path.path);
2373 /* parse_scalar_initializer() also works in this case: we simply
2374 * have an expression without {} around it */
2375 result = parse_scalar_initializer(type, env->must_be_constant);
2378 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2379 * the array type size */
2380 if(is_type_array(type) && type->array.size_expression == NULL
2381 && result != NULL) {
2383 switch (result->kind) {
2384 case INITIALIZER_LIST:
2385 size = max_index + 1;
2388 case INITIALIZER_STRING:
2389 size = result->string.string.size;
2392 case INITIALIZER_WIDE_STRING:
2393 size = result->wide_string.string.size;
2397 internal_errorf(HERE, "invalid initializer type");
2400 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2401 cnst->base.type = type_size_t;
2402 cnst->conste.v.int_value = size;
2404 type_t *new_type = duplicate_type(type);
2406 new_type->array.size_expression = cnst;
2407 new_type->array.size_constant = true;
2408 new_type->array.size = size;
2409 env->type = new_type;
2417 static declaration_t *append_declaration(declaration_t *declaration);
2419 static declaration_t *parse_compound_type_specifier(bool is_struct)
2421 gnu_attribute_t *attributes = NULL;
2428 symbol_t *symbol = NULL;
2429 declaration_t *declaration = NULL;
2431 if (token.type == T___attribute__) {
2432 parse_attributes(&attributes);
2435 if(token.type == T_IDENTIFIER) {
2436 symbol = token.v.symbol;
2440 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2442 declaration = get_declaration(symbol, NAMESPACE_UNION);
2444 } else if(token.type != '{') {
2446 parse_error_expected("while parsing struct type specifier",
2447 T_IDENTIFIER, '{', NULL);
2449 parse_error_expected("while parsing union type specifier",
2450 T_IDENTIFIER, '{', NULL);
2456 if(declaration == NULL) {
2457 declaration = allocate_declaration_zero();
2458 declaration->namespc =
2459 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2460 declaration->source_position = token.source_position;
2461 declaration->symbol = symbol;
2462 declaration->parent_scope = scope;
2463 if (symbol != NULL) {
2464 environment_push(declaration);
2466 append_declaration(declaration);
2469 if(token.type == '{') {
2470 if (declaration->init.complete) {
2471 assert(symbol != NULL);
2472 errorf(HERE, "multiple definitions of '%s %Y'",
2473 is_struct ? "struct" : "union", symbol);
2474 declaration->scope.declarations = NULL;
2476 declaration->init.complete = true;
2478 parse_compound_type_entries(declaration);
2479 parse_attributes(&attributes);
2485 static void parse_enum_entries(type_t *const enum_type)
2489 if(token.type == '}') {
2491 errorf(HERE, "empty enum not allowed");
2495 add_anchor_token('}');
2497 if(token.type != T_IDENTIFIER) {
2498 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2500 rem_anchor_token('}');
2504 declaration_t *const entry = allocate_declaration_zero();
2505 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2506 entry->type = enum_type;
2507 entry->symbol = token.v.symbol;
2508 entry->source_position = token.source_position;
2511 if(token.type == '=') {
2513 expression_t *value = parse_constant_expression();
2515 value = create_implicit_cast(value, enum_type);
2516 entry->init.enum_value = value;
2521 record_declaration(entry);
2523 if(token.type != ',')
2526 } while(token.type != '}');
2527 rem_anchor_token('}');
2535 static type_t *parse_enum_specifier(void)
2537 gnu_attribute_t *attributes = NULL;
2538 declaration_t *declaration;
2542 if(token.type == T_IDENTIFIER) {
2543 symbol = token.v.symbol;
2546 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2547 } else if(token.type != '{') {
2548 parse_error_expected("while parsing enum type specifier",
2549 T_IDENTIFIER, '{', NULL);
2556 if(declaration == NULL) {
2557 declaration = allocate_declaration_zero();
2558 declaration->namespc = NAMESPACE_ENUM;
2559 declaration->source_position = token.source_position;
2560 declaration->symbol = symbol;
2561 declaration->parent_scope = scope;
2564 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2565 type->enumt.declaration = declaration;
2567 if(token.type == '{') {
2568 if(declaration->init.complete) {
2569 errorf(HERE, "multiple definitions of enum %Y", symbol);
2571 if (symbol != NULL) {
2572 environment_push(declaration);
2574 append_declaration(declaration);
2575 declaration->init.complete = true;
2577 parse_enum_entries(type);
2578 parse_attributes(&attributes);
2585 * if a symbol is a typedef to another type, return true
2587 static bool is_typedef_symbol(symbol_t *symbol)
2589 const declaration_t *const declaration =
2590 get_declaration(symbol, NAMESPACE_NORMAL);
2592 declaration != NULL &&
2593 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2596 static type_t *parse_typeof(void)
2603 add_anchor_token(')');
2605 expression_t *expression = NULL;
2608 switch(token.type) {
2609 case T___extension__:
2610 /* this can be a prefix to a typename or an expression */
2611 /* we simply eat it now. */
2614 } while(token.type == T___extension__);
2618 if(is_typedef_symbol(token.v.symbol)) {
2619 type = parse_typename();
2621 expression = parse_expression();
2622 type = expression->base.type;
2627 type = parse_typename();
2631 expression = parse_expression();
2632 type = expression->base.type;
2636 rem_anchor_token(')');
2639 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2640 typeof_type->typeoft.expression = expression;
2641 typeof_type->typeoft.typeof_type = type;
2649 SPECIFIER_SIGNED = 1 << 0,
2650 SPECIFIER_UNSIGNED = 1 << 1,
2651 SPECIFIER_LONG = 1 << 2,
2652 SPECIFIER_INT = 1 << 3,
2653 SPECIFIER_DOUBLE = 1 << 4,
2654 SPECIFIER_CHAR = 1 << 5,
2655 SPECIFIER_SHORT = 1 << 6,
2656 SPECIFIER_LONG_LONG = 1 << 7,
2657 SPECIFIER_FLOAT = 1 << 8,
2658 SPECIFIER_BOOL = 1 << 9,
2659 SPECIFIER_VOID = 1 << 10,
2660 SPECIFIER_INT8 = 1 << 11,
2661 SPECIFIER_INT16 = 1 << 12,
2662 SPECIFIER_INT32 = 1 << 13,
2663 SPECIFIER_INT64 = 1 << 14,
2664 SPECIFIER_INT128 = 1 << 15,
2665 SPECIFIER_COMPLEX = 1 << 16,
2666 SPECIFIER_IMAGINARY = 1 << 17,
2669 static type_t *create_builtin_type(symbol_t *const symbol,
2670 type_t *const real_type)
2672 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2673 type->builtin.symbol = symbol;
2674 type->builtin.real_type = real_type;
2676 type_t *result = typehash_insert(type);
2677 if(type != result) {
2684 static type_t *get_typedef_type(symbol_t *symbol)
2686 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2687 if(declaration == NULL ||
2688 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2691 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2692 type->typedeft.declaration = declaration;
2698 * check for the allowed MS alignment values.
2700 static bool check_elignment_value(long long intvalue) {
2701 if(intvalue < 1 || intvalue > 8192) {
2702 errorf(HERE, "illegal alignment value");
2705 unsigned v = (unsigned)intvalue;
2706 for(unsigned i = 1; i <= 8192; i += i) {
2710 errorf(HERE, "alignment must be power of two");
2714 #define DET_MOD(name, tag) do { \
2715 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2716 *modifiers |= tag; \
2719 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2721 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2724 if(token.type == T_restrict) {
2726 DET_MOD(restrict, DM_RESTRICT);
2728 } else if(token.type != T_IDENTIFIER)
2730 symbol_t *symbol = token.v.symbol;
2731 if(symbol == sym_align) {
2734 if(token.type != T_INTEGER)
2736 if(check_elignment_value(token.v.intvalue)) {
2737 if(specifiers->alignment != 0)
2738 warningf(HERE, "align used more than once");
2739 specifiers->alignment = (unsigned char)token.v.intvalue;
2743 } else if(symbol == sym_allocate) {
2746 if(token.type != T_IDENTIFIER)
2748 (void)token.v.symbol;
2750 } else if(symbol == sym_dllimport) {
2752 DET_MOD(dllimport, DM_DLLIMPORT);
2753 } else if(symbol == sym_dllexport) {
2755 DET_MOD(dllexport, DM_DLLEXPORT);
2756 } else if(symbol == sym_thread) {
2758 DET_MOD(thread, DM_THREAD);
2759 } else if(symbol == sym_naked) {
2761 DET_MOD(naked, DM_NAKED);
2762 } else if(symbol == sym_noinline) {
2764 DET_MOD(noinline, DM_NOINLINE);
2765 } else if(symbol == sym_noreturn) {
2767 DET_MOD(noreturn, DM_NORETURN);
2768 } else if(symbol == sym_nothrow) {
2770 DET_MOD(nothrow, DM_NOTHROW);
2771 } else if(symbol == sym_novtable) {
2773 DET_MOD(novtable, DM_NOVTABLE);
2774 } else if(symbol == sym_property) {
2778 bool is_get = false;
2779 if(token.type != T_IDENTIFIER)
2781 if(token.v.symbol == sym_get) {
2783 } else if(token.v.symbol == sym_put) {
2785 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2790 if(token.type != T_IDENTIFIER)
2793 if(specifiers->get_property_sym != NULL) {
2794 errorf(HERE, "get property name already specified");
2796 specifiers->get_property_sym = token.v.symbol;
2799 if(specifiers->put_property_sym != NULL) {
2800 errorf(HERE, "put property name already specified");
2802 specifiers->put_property_sym = token.v.symbol;
2806 if(token.type == ',') {
2813 } else if(symbol == sym_selectany) {
2815 DET_MOD(selectany, DM_SELECTANY);
2816 } else if(symbol == sym_uuid) {
2819 if(token.type != T_STRING_LITERAL)
2823 } else if(symbol == sym_deprecated) {
2825 if(specifiers->deprecated != 0)
2826 warningf(HERE, "deprecated used more than once");
2827 specifiers->deprecated = 1;
2828 if(token.type == '(') {
2830 if(token.type == T_STRING_LITERAL) {
2831 specifiers->deprecated_string = token.v.string.begin;
2834 errorf(HERE, "string literal expected");
2838 } else if(symbol == sym_noalias) {
2840 DET_MOD(noalias, DM_NOALIAS);
2842 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2844 if(token.type == '(')
2848 if (token.type == ',')
2855 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2857 type_t *type = NULL;
2858 unsigned type_qualifiers = 0;
2859 unsigned type_specifiers = 0;
2862 specifiers->source_position = token.source_position;
2865 switch(token.type) {
2868 #define MATCH_STORAGE_CLASS(token, class) \
2870 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2871 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2873 specifiers->declared_storage_class = class; \
2877 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2878 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2879 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2880 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2881 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2886 add_anchor_token(')');
2887 parse_microsoft_extended_decl_modifier(specifiers);
2888 rem_anchor_token(')');
2893 switch (specifiers->declared_storage_class) {
2894 case STORAGE_CLASS_NONE:
2895 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2898 case STORAGE_CLASS_EXTERN:
2899 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2902 case STORAGE_CLASS_STATIC:
2903 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2907 errorf(HERE, "multiple storage classes in declaration specifiers");
2913 /* type qualifiers */
2914 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2916 type_qualifiers |= qualifier; \
2920 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2921 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2922 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2923 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2924 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2925 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2926 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2927 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2929 case T___extension__:
2934 /* type specifiers */
2935 #define MATCH_SPECIFIER(token, specifier, name) \
2938 if(type_specifiers & specifier) { \
2939 errorf(HERE, "multiple " name " type specifiers given"); \
2941 type_specifiers |= specifier; \
2945 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2946 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2947 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2948 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2949 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2950 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2951 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2952 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2953 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2954 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2955 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2956 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2957 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2958 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2959 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2960 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2962 case T__forceinline:
2963 /* only in microsoft mode */
2964 specifiers->decl_modifiers |= DM_FORCEINLINE;
2968 specifiers->is_inline = true;
2973 if(type_specifiers & SPECIFIER_LONG_LONG) {
2974 errorf(HERE, "multiple type specifiers given");
2975 } else if(type_specifiers & SPECIFIER_LONG) {
2976 type_specifiers |= SPECIFIER_LONG_LONG;
2978 type_specifiers |= SPECIFIER_LONG;
2983 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2985 type->compound.declaration = parse_compound_type_specifier(true);
2989 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2991 type->compound.declaration = parse_compound_type_specifier(false);
2995 type = parse_enum_specifier();
2998 type = parse_typeof();
3000 case T___builtin_va_list:
3001 type = duplicate_type(type_valist);
3005 case T___attribute__:
3006 parse_attributes(&specifiers->gnu_attributes);
3009 case T_IDENTIFIER: {
3010 /* only parse identifier if we haven't found a type yet */
3011 if(type != NULL || type_specifiers != 0)
3012 goto finish_specifiers;
3014 type_t *typedef_type = get_typedef_type(token.v.symbol);
3016 if(typedef_type == NULL)
3017 goto finish_specifiers;
3020 type = typedef_type;
3024 /* function specifier */
3026 goto finish_specifiers;
3033 atomic_type_kind_t atomic_type;
3035 /* match valid basic types */
3036 switch(type_specifiers) {
3037 case SPECIFIER_VOID:
3038 atomic_type = ATOMIC_TYPE_VOID;
3040 case SPECIFIER_CHAR:
3041 atomic_type = ATOMIC_TYPE_CHAR;
3043 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3044 atomic_type = ATOMIC_TYPE_SCHAR;
3046 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3047 atomic_type = ATOMIC_TYPE_UCHAR;
3049 case SPECIFIER_SHORT:
3050 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3051 case SPECIFIER_SHORT | SPECIFIER_INT:
3052 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3053 atomic_type = ATOMIC_TYPE_SHORT;
3055 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3056 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3057 atomic_type = ATOMIC_TYPE_USHORT;
3060 case SPECIFIER_SIGNED:
3061 case SPECIFIER_SIGNED | SPECIFIER_INT:
3062 atomic_type = ATOMIC_TYPE_INT;
3064 case SPECIFIER_UNSIGNED:
3065 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3066 atomic_type = ATOMIC_TYPE_UINT;
3068 case SPECIFIER_LONG:
3069 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3070 case SPECIFIER_LONG | SPECIFIER_INT:
3071 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3072 atomic_type = ATOMIC_TYPE_LONG;
3074 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3075 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3076 atomic_type = ATOMIC_TYPE_ULONG;
3078 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3079 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3080 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3081 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3083 atomic_type = ATOMIC_TYPE_LONGLONG;
3085 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3086 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3088 atomic_type = ATOMIC_TYPE_ULONGLONG;
3091 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3092 atomic_type = unsigned_int8_type_kind;
3095 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3096 atomic_type = unsigned_int16_type_kind;
3099 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3100 atomic_type = unsigned_int32_type_kind;
3103 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3104 atomic_type = unsigned_int64_type_kind;
3107 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3108 atomic_type = unsigned_int128_type_kind;
3111 case SPECIFIER_INT8:
3112 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3113 atomic_type = int8_type_kind;
3116 case SPECIFIER_INT16:
3117 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3118 atomic_type = int16_type_kind;
3121 case SPECIFIER_INT32:
3122 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3123 atomic_type = int32_type_kind;
3126 case SPECIFIER_INT64:
3127 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3128 atomic_type = int64_type_kind;
3131 case SPECIFIER_INT128:
3132 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3133 atomic_type = int128_type_kind;
3136 case SPECIFIER_FLOAT:
3137 atomic_type = ATOMIC_TYPE_FLOAT;
3139 case SPECIFIER_DOUBLE:
3140 atomic_type = ATOMIC_TYPE_DOUBLE;
3142 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3143 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3145 case SPECIFIER_BOOL:
3146 atomic_type = ATOMIC_TYPE_BOOL;
3148 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3149 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3150 atomic_type = ATOMIC_TYPE_FLOAT;
3152 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3153 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3154 atomic_type = ATOMIC_TYPE_DOUBLE;
3156 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3157 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3158 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3161 /* invalid specifier combination, give an error message */
3162 if(type_specifiers == 0) {
3163 if (! strict_mode) {
3164 if (warning.implicit_int) {
3165 warningf(HERE, "no type specifiers in declaration, using 'int'");
3167 atomic_type = ATOMIC_TYPE_INT;
3170 errorf(HERE, "no type specifiers given in declaration");
3172 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3173 (type_specifiers & SPECIFIER_UNSIGNED)) {
3174 errorf(HERE, "signed and unsigned specifiers gives");
3175 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3176 errorf(HERE, "only integer types can be signed or unsigned");
3178 errorf(HERE, "multiple datatypes in declaration");
3180 atomic_type = ATOMIC_TYPE_INVALID;
3183 if(type_specifiers & SPECIFIER_COMPLEX &&
3184 atomic_type != ATOMIC_TYPE_INVALID) {
3185 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3186 type->complex.akind = atomic_type;
3187 } else if(type_specifiers & SPECIFIER_IMAGINARY &&
3188 atomic_type != ATOMIC_TYPE_INVALID) {
3189 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3190 type->imaginary.akind = atomic_type;
3192 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3193 type->atomic.akind = atomic_type;
3197 if(type_specifiers != 0) {
3198 errorf(HERE, "multiple datatypes in declaration");
3202 type->base.qualifiers = type_qualifiers;
3203 /* FIXME: check type qualifiers here */
3205 type_t *result = typehash_insert(type);
3206 if(newtype && result != type) {
3210 specifiers->type = result;
3215 static type_qualifiers_t parse_type_qualifiers(void)
3217 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3220 switch(token.type) {
3221 /* type qualifiers */
3222 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3223 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3224 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3225 /* microsoft extended type modifiers */
3226 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3227 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3228 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3229 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3230 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3233 return type_qualifiers;
3238 static declaration_t *parse_identifier_list(void)
3240 declaration_t *declarations = NULL;
3241 declaration_t *last_declaration = NULL;
3243 declaration_t *const declaration = allocate_declaration_zero();
3244 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3245 declaration->source_position = token.source_position;
3246 declaration->symbol = token.v.symbol;
3249 if(last_declaration != NULL) {
3250 last_declaration->next = declaration;
3252 declarations = declaration;
3254 last_declaration = declaration;
3256 if (token.type != ',') {
3260 } while(token.type == T_IDENTIFIER);
3262 return declarations;
3265 static void semantic_parameter(declaration_t *declaration)
3267 /* TODO: improve error messages */
3269 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3270 errorf(HERE, "typedef not allowed in parameter list");
3271 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3272 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3273 errorf(HERE, "parameter may only have none or register storage class");
3276 type_t *const orig_type = declaration->type;
3277 type_t * type = skip_typeref(orig_type);
3279 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3280 * into a pointer. § 6.7.5.3 (7) */
3281 if (is_type_array(type)) {
3282 type_t *const element_type = type->array.element_type;
3284 type = make_pointer_type(element_type, type->base.qualifiers);
3286 declaration->type = type;
3289 if(is_type_incomplete(type)) {
3290 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3291 orig_type, declaration->symbol);
3295 static declaration_t *parse_parameter(void)
3297 declaration_specifiers_t specifiers;
3298 memset(&specifiers, 0, sizeof(specifiers));
3300 parse_declaration_specifiers(&specifiers);
3302 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3304 semantic_parameter(declaration);
3309 static declaration_t *parse_parameters(function_type_t *type)
3311 declaration_t *declarations = NULL;
3314 add_anchor_token(')');
3315 int saved_comma_state = save_and_reset_anchor_state(',');
3317 if(token.type == T_IDENTIFIER) {
3318 symbol_t *symbol = token.v.symbol;
3319 if(!is_typedef_symbol(symbol)) {
3320 type->kr_style_parameters = true;
3321 declarations = parse_identifier_list();
3322 goto parameters_finished;
3326 if(token.type == ')') {
3327 type->unspecified_parameters = 1;
3328 goto parameters_finished;
3330 if(token.type == T_void && look_ahead(1)->type == ')') {
3332 goto parameters_finished;
3335 declaration_t *declaration;
3336 declaration_t *last_declaration = NULL;
3337 function_parameter_t *parameter;
3338 function_parameter_t *last_parameter = NULL;
3341 switch(token.type) {
3345 goto parameters_finished;
3348 case T___extension__:
3350 declaration = parse_parameter();
3352 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3353 memset(parameter, 0, sizeof(parameter[0]));
3354 parameter->type = declaration->type;
3356 if(last_parameter != NULL) {
3357 last_declaration->next = declaration;
3358 last_parameter->next = parameter;
3360 type->parameters = parameter;
3361 declarations = declaration;
3363 last_parameter = parameter;
3364 last_declaration = declaration;
3368 goto parameters_finished;
3370 if (token.type != ',') {
3371 goto parameters_finished;
3377 parameters_finished:
3378 rem_anchor_token(')');
3381 restore_anchor_state(',', saved_comma_state);
3382 return declarations;
3385 restore_anchor_state(',', saved_comma_state);
3394 } construct_type_kind_t;
3396 typedef struct construct_type_t construct_type_t;
3397 struct construct_type_t {
3398 construct_type_kind_t kind;
3399 construct_type_t *next;
3402 typedef struct parsed_pointer_t parsed_pointer_t;
3403 struct parsed_pointer_t {
3404 construct_type_t construct_type;
3405 type_qualifiers_t type_qualifiers;
3408 typedef struct construct_function_type_t construct_function_type_t;
3409 struct construct_function_type_t {
3410 construct_type_t construct_type;
3411 type_t *function_type;
3414 typedef struct parsed_array_t parsed_array_t;
3415 struct parsed_array_t {
3416 construct_type_t construct_type;
3417 type_qualifiers_t type_qualifiers;
3423 typedef struct construct_base_type_t construct_base_type_t;
3424 struct construct_base_type_t {
3425 construct_type_t construct_type;
3429 static construct_type_t *parse_pointer_declarator(void)
3433 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3434 memset(pointer, 0, sizeof(pointer[0]));
3435 pointer->construct_type.kind = CONSTRUCT_POINTER;
3436 pointer->type_qualifiers = parse_type_qualifiers();
3438 return (construct_type_t*) pointer;
3441 static construct_type_t *parse_array_declarator(void)
3444 add_anchor_token(']');
3446 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3447 memset(array, 0, sizeof(array[0]));
3448 array->construct_type.kind = CONSTRUCT_ARRAY;
3450 if(token.type == T_static) {
3451 array->is_static = true;
3455 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3456 if(type_qualifiers != 0) {
3457 if(token.type == T_static) {
3458 array->is_static = true;
3462 array->type_qualifiers = type_qualifiers;
3464 if(token.type == '*' && look_ahead(1)->type == ']') {
3465 array->is_variable = true;
3467 } else if(token.type != ']') {
3468 array->size = parse_assignment_expression();
3471 rem_anchor_token(']');
3474 return (construct_type_t*) array;
3479 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3482 if(declaration != NULL) {
3483 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3485 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3488 declaration_t *parameters = parse_parameters(&type->function);
3489 if(declaration != NULL) {
3490 declaration->scope.declarations = parameters;
3493 construct_function_type_t *construct_function_type =
3494 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3495 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3496 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3497 construct_function_type->function_type = type;
3499 return (construct_type_t*) construct_function_type;
3502 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3503 bool may_be_abstract)
3505 /* construct a single linked list of construct_type_t's which describe
3506 * how to construct the final declarator type */
3507 construct_type_t *first = NULL;
3508 construct_type_t *last = NULL;
3509 gnu_attribute_t *attributes = NULL;
3512 while(token.type == '*') {
3513 construct_type_t *type = parse_pointer_declarator();
3524 /* TODO: find out if this is correct */
3525 parse_attributes(&attributes);
3527 construct_type_t *inner_types = NULL;
3529 switch(token.type) {
3531 if(declaration == NULL) {
3532 errorf(HERE, "no identifier expected in typename");
3534 declaration->symbol = token.v.symbol;
3535 declaration->source_position = token.source_position;
3541 add_anchor_token(')');
3542 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3543 rem_anchor_token(')');
3549 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3550 /* avoid a loop in the outermost scope, because eat_statement doesn't
3552 if(token.type == '}' && current_function == NULL) {
3560 construct_type_t *p = last;
3563 construct_type_t *type;
3564 switch(token.type) {
3566 type = parse_function_declarator(declaration);
3569 type = parse_array_declarator();
3572 goto declarator_finished;
3575 /* insert in the middle of the list (behind p) */
3577 type->next = p->next;
3588 declarator_finished:
3589 parse_attributes(&attributes);
3591 /* append inner_types at the end of the list, we don't to set last anymore
3592 * as it's not needed anymore */
3594 assert(first == NULL);
3595 first = inner_types;
3597 last->next = inner_types;
3605 static type_t *construct_declarator_type(construct_type_t *construct_list,
3608 construct_type_t *iter = construct_list;
3609 for( ; iter != NULL; iter = iter->next) {
3610 switch(iter->kind) {
3611 case CONSTRUCT_INVALID:
3612 internal_errorf(HERE, "invalid type construction found");
3613 case CONSTRUCT_FUNCTION: {
3614 construct_function_type_t *construct_function_type
3615 = (construct_function_type_t*) iter;
3617 type_t *function_type = construct_function_type->function_type;
3619 function_type->function.return_type = type;
3621 type_t *skipped_return_type = skip_typeref(type);
3622 if (is_type_function(skipped_return_type)) {
3623 errorf(HERE, "function returning function is not allowed");
3624 type = type_error_type;
3625 } else if (is_type_array(skipped_return_type)) {
3626 errorf(HERE, "function returning array is not allowed");
3627 type = type_error_type;
3629 type = function_type;
3634 case CONSTRUCT_POINTER: {
3635 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3636 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3637 pointer_type->pointer.points_to = type;
3638 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3640 type = pointer_type;
3644 case CONSTRUCT_ARRAY: {
3645 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3646 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3648 expression_t *size_expression = parsed_array->size;
3649 if(size_expression != NULL) {
3651 = create_implicit_cast(size_expression, type_size_t);
3654 array_type->base.qualifiers = parsed_array->type_qualifiers;
3655 array_type->array.element_type = type;
3656 array_type->array.is_static = parsed_array->is_static;
3657 array_type->array.is_variable = parsed_array->is_variable;
3658 array_type->array.size_expression = size_expression;
3660 if(size_expression != NULL) {
3661 if(is_constant_expression(size_expression)) {
3662 array_type->array.size_constant = true;
3663 array_type->array.size
3664 = fold_constant(size_expression);
3666 array_type->array.is_vla = true;
3670 type_t *skipped_type = skip_typeref(type);
3671 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3672 errorf(HERE, "array of void is not allowed");
3673 type = type_error_type;
3681 type_t *hashed_type = typehash_insert(type);
3682 if(hashed_type != type) {
3683 /* the function type was constructed earlier freeing it here will
3684 * destroy other types... */
3685 if(iter->kind != CONSTRUCT_FUNCTION) {
3695 static declaration_t *parse_declarator(
3696 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3698 declaration_t *const declaration = allocate_declaration_zero();
3699 declaration->declared_storage_class = specifiers->declared_storage_class;
3700 declaration->decl_modifiers = specifiers->decl_modifiers;
3701 declaration->deprecated = specifiers->deprecated;
3702 declaration->deprecated_string = specifiers->deprecated_string;
3703 declaration->get_property_sym = specifiers->get_property_sym;
3704 declaration->put_property_sym = specifiers->put_property_sym;
3705 declaration->is_inline = specifiers->is_inline;
3707 declaration->storage_class = specifiers->declared_storage_class;
3708 if(declaration->storage_class == STORAGE_CLASS_NONE
3709 && scope != global_scope) {
3710 declaration->storage_class = STORAGE_CLASS_AUTO;
3713 if(specifiers->alignment != 0) {
3714 /* TODO: add checks here */
3715 declaration->alignment = specifiers->alignment;
3718 construct_type_t *construct_type
3719 = parse_inner_declarator(declaration, may_be_abstract);
3720 type_t *const type = specifiers->type;
3721 declaration->type = construct_declarator_type(construct_type, type);
3723 if(construct_type != NULL) {
3724 obstack_free(&temp_obst, construct_type);
3730 static type_t *parse_abstract_declarator(type_t *base_type)
3732 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3734 type_t *result = construct_declarator_type(construct_type, base_type);
3735 if(construct_type != NULL) {
3736 obstack_free(&temp_obst, construct_type);
3742 static declaration_t *append_declaration(declaration_t* const declaration)
3744 if (last_declaration != NULL) {
3745 last_declaration->next = declaration;
3747 scope->declarations = declaration;
3749 last_declaration = declaration;
3754 * Check if the declaration of main is suspicious. main should be a
3755 * function with external linkage, returning int, taking either zero
3756 * arguments, two, or three arguments of appropriate types, ie.
3758 * int main([ int argc, char **argv [, char **env ] ]).
3760 * @param decl the declaration to check
3761 * @param type the function type of the declaration
3763 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3765 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3766 warningf(&decl->source_position,
3767 "'main' is normally a non-static function");
3769 if (skip_typeref(func_type->return_type) != type_int) {
3770 warningf(&decl->source_position,
3771 "return type of 'main' should be 'int', but is '%T'",
3772 func_type->return_type);
3774 const function_parameter_t *parm = func_type->parameters;
3776 type_t *const first_type = parm->type;
3777 if (!types_compatible(skip_typeref(first_type), type_int)) {
3778 warningf(&decl->source_position,
3779 "first argument of 'main' should be 'int', but is '%T'", first_type);
3783 type_t *const second_type = parm->type;
3784 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3785 warningf(&decl->source_position,
3786 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3790 type_t *const third_type = parm->type;
3791 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3792 warningf(&decl->source_position,
3793 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3797 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3801 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3807 * Check if a symbol is the equal to "main".
3809 static bool is_sym_main(const symbol_t *const sym)
3811 return strcmp(sym->string, "main") == 0;
3814 static declaration_t *internal_record_declaration(
3815 declaration_t *const declaration,
3816 const bool is_function_definition)
3818 const symbol_t *const symbol = declaration->symbol;
3819 const namespace_t namespc = (namespace_t)declaration->namespc;
3821 assert(declaration->symbol != NULL);
3822 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3824 type_t *const orig_type = declaration->type;
3825 type_t *const type = skip_typeref(orig_type);
3826 if (is_type_function(type) &&
3827 type->function.unspecified_parameters &&
3828 warning.strict_prototypes &&
3829 previous_declaration == NULL) {
3830 warningf(&declaration->source_position,
3831 "function declaration '%#T' is not a prototype",
3832 orig_type, declaration->symbol);
3835 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3836 check_type_of_main(declaration, &type->function);
3839 assert(declaration != previous_declaration);
3840 if (previous_declaration != NULL
3841 && previous_declaration->parent_scope == scope) {
3842 /* can happen for K&R style declarations */
3843 if (previous_declaration->type == NULL) {
3844 previous_declaration->type = declaration->type;
3847 const type_t *prev_type = skip_typeref(previous_declaration->type);
3848 if (!types_compatible(type, prev_type)) {
3849 errorf(&declaration->source_position,
3850 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3851 orig_type, symbol, previous_declaration->type, symbol,
3852 &previous_declaration->source_position);
3854 unsigned old_storage_class = previous_declaration->storage_class;
3855 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3856 errorf(&declaration->source_position,
3857 "redeclaration of enum entry '%Y' (declared %P)",
3858 symbol, &previous_declaration->source_position);
3859 return previous_declaration;
3862 unsigned new_storage_class = declaration->storage_class;
3864 if (is_type_incomplete(prev_type)) {
3865 previous_declaration->type = type;
3869 /* pretend no storage class means extern for function
3870 * declarations (except if the previous declaration is neither
3871 * none nor extern) */
3872 if (is_type_function(type)) {
3873 if (prev_type->function.unspecified_parameters) {
3874 previous_declaration->type = type;
3878 switch (old_storage_class) {
3879 case STORAGE_CLASS_NONE:
3880 old_storage_class = STORAGE_CLASS_EXTERN;
3882 case STORAGE_CLASS_EXTERN:
3883 if (is_function_definition) {
3884 if (warning.missing_prototypes &&
3885 prev_type->function.unspecified_parameters &&
3886 !is_sym_main(symbol)) {
3887 warningf(&declaration->source_position,
3888 "no previous prototype for '%#T'",
3891 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3892 new_storage_class = STORAGE_CLASS_EXTERN;
3901 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3902 new_storage_class == STORAGE_CLASS_EXTERN) {
3903 warn_redundant_declaration:
3904 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
3905 warningf(&declaration->source_position,
3906 "redundant declaration for '%Y' (declared %P)",
3907 symbol, &previous_declaration->source_position);
3909 } else if (current_function == NULL) {
3910 if (old_storage_class != STORAGE_CLASS_STATIC &&
3911 new_storage_class == STORAGE_CLASS_STATIC) {
3912 errorf(&declaration->source_position,
3913 "static declaration of '%Y' follows non-static declaration (declared %P)",
3914 symbol, &previous_declaration->source_position);
3915 } else if (old_storage_class != STORAGE_CLASS_EXTERN
3916 && !is_function_definition) {
3917 goto warn_redundant_declaration;
3918 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3919 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3920 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3922 } else if (old_storage_class == new_storage_class) {
3923 errorf(&declaration->source_position,
3924 "redeclaration of '%Y' (declared %P)",
3925 symbol, &previous_declaration->source_position);
3927 errorf(&declaration->source_position,
3928 "redeclaration of '%Y' with different linkage (declared %P)",
3929 symbol, &previous_declaration->source_position);
3933 if (declaration->is_inline)
3934 previous_declaration->is_inline = true;
3935 return previous_declaration;
3936 } else if (is_function_definition) {
3937 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3938 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3939 warningf(&declaration->source_position,
3940 "no previous prototype for '%#T'", orig_type, symbol);
3941 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3942 warningf(&declaration->source_position,
3943 "no previous declaration for '%#T'", orig_type,
3947 } else if (warning.missing_declarations &&
3948 scope == global_scope &&
3949 !is_type_function(type) && (
3950 declaration->storage_class == STORAGE_CLASS_NONE ||
3951 declaration->storage_class == STORAGE_CLASS_THREAD
3953 warningf(&declaration->source_position,
3954 "no previous declaration for '%#T'", orig_type, symbol);
3957 assert(declaration->parent_scope == NULL);
3958 assert(scope != NULL);
3960 declaration->parent_scope = scope;
3962 environment_push(declaration);
3963 return append_declaration(declaration);
3966 static declaration_t *record_declaration(declaration_t *declaration)
3968 return internal_record_declaration(declaration, false);
3971 static declaration_t *record_function_definition(declaration_t *declaration)
3973 return internal_record_declaration(declaration, true);
3976 static void parser_error_multiple_definition(declaration_t *declaration,
3977 const source_position_t *source_position)
3979 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
3980 declaration->symbol, &declaration->source_position);
3983 static bool is_declaration_specifier(const token_t *token,
3984 bool only_specifiers_qualifiers)
3986 switch(token->type) {
3991 return is_typedef_symbol(token->v.symbol);
3993 case T___extension__:
3995 return !only_specifiers_qualifiers;
4002 static void parse_init_declarator_rest(declaration_t *declaration)
4006 type_t *orig_type = declaration->type;
4007 type_t *type = skip_typeref(orig_type);
4009 if(declaration->init.initializer != NULL) {
4010 parser_error_multiple_definition(declaration, HERE);
4013 bool must_be_constant = false;
4014 if(declaration->storage_class == STORAGE_CLASS_STATIC
4015 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4016 || declaration->parent_scope == global_scope) {
4017 must_be_constant = true;
4020 parse_initializer_env_t env;
4021 env.type = orig_type;
4022 env.must_be_constant = must_be_constant;
4023 env.declaration = declaration;
4025 initializer_t *initializer = parse_initializer(&env);
4027 if(env.type != orig_type) {
4028 orig_type = env.type;
4029 type = skip_typeref(orig_type);
4030 declaration->type = env.type;
4033 if(is_type_function(type)) {
4034 errorf(&declaration->source_position,
4035 "initializers not allowed for function types at declator '%Y' (type '%T')",
4036 declaration->symbol, orig_type);
4038 declaration->init.initializer = initializer;
4042 /* parse rest of a declaration without any declarator */
4043 static void parse_anonymous_declaration_rest(
4044 const declaration_specifiers_t *specifiers,
4045 parsed_declaration_func finished_declaration)
4049 declaration_t *const declaration = allocate_declaration_zero();
4050 declaration->type = specifiers->type;
4051 declaration->declared_storage_class = specifiers->declared_storage_class;
4052 declaration->source_position = specifiers->source_position;
4053 declaration->decl_modifiers = specifiers->decl_modifiers;
4055 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4056 warningf(&declaration->source_position,
4057 "useless storage class in empty declaration");
4059 declaration->storage_class = STORAGE_CLASS_NONE;
4061 type_t *type = declaration->type;
4062 switch (type->kind) {
4063 case TYPE_COMPOUND_STRUCT:
4064 case TYPE_COMPOUND_UNION: {
4065 if (type->compound.declaration->symbol == NULL) {
4066 warningf(&declaration->source_position,
4067 "unnamed struct/union that defines no instances");
4076 warningf(&declaration->source_position, "empty declaration");
4080 finished_declaration(declaration);
4083 static void parse_declaration_rest(declaration_t *ndeclaration,
4084 const declaration_specifiers_t *specifiers,
4085 parsed_declaration_func finished_declaration)
4087 add_anchor_token(';');
4088 add_anchor_token('=');
4089 add_anchor_token(',');
4091 declaration_t *declaration = finished_declaration(ndeclaration);
4093 type_t *orig_type = declaration->type;
4094 type_t *type = skip_typeref(orig_type);
4096 if (type->kind != TYPE_FUNCTION &&
4097 declaration->is_inline &&
4098 is_type_valid(type)) {
4099 warningf(&declaration->source_position,
4100 "variable '%Y' declared 'inline'\n", declaration->symbol);
4103 if(token.type == '=') {
4104 parse_init_declarator_rest(declaration);
4107 if(token.type != ',')
4111 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4116 rem_anchor_token(';');
4117 rem_anchor_token('=');
4118 rem_anchor_token(',');
4121 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4123 symbol_t *symbol = declaration->symbol;
4124 if(symbol == NULL) {
4125 errorf(HERE, "anonymous declaration not valid as function parameter");
4128 namespace_t namespc = (namespace_t) declaration->namespc;
4129 if(namespc != NAMESPACE_NORMAL) {
4130 return record_declaration(declaration);
4133 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4134 if(previous_declaration == NULL ||
4135 previous_declaration->parent_scope != scope) {
4136 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4141 if(previous_declaration->type == NULL) {
4142 previous_declaration->type = declaration->type;
4143 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4144 previous_declaration->storage_class = declaration->storage_class;
4145 previous_declaration->parent_scope = scope;
4146 return previous_declaration;
4148 return record_declaration(declaration);
4152 static void parse_declaration(parsed_declaration_func finished_declaration)
4154 declaration_specifiers_t specifiers;
4155 memset(&specifiers, 0, sizeof(specifiers));
4156 parse_declaration_specifiers(&specifiers);
4158 if(token.type == ';') {
4159 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4161 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4162 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4166 static type_t *get_default_promoted_type(type_t *orig_type)
4168 type_t *result = orig_type;
4170 type_t *type = skip_typeref(orig_type);
4171 if(is_type_integer(type)) {
4172 result = promote_integer(type);
4173 } else if(type == type_float) {
4174 result = type_double;
4180 static void parse_kr_declaration_list(declaration_t *declaration)
4182 type_t *type = skip_typeref(declaration->type);
4183 if (!is_type_function(type))
4186 if (!type->function.kr_style_parameters)
4189 /* push function parameters */
4190 int top = environment_top();
4191 scope_t *last_scope = scope;
4192 set_scope(&declaration->scope);
4194 declaration_t *parameter = declaration->scope.declarations;
4195 for ( ; parameter != NULL; parameter = parameter->next) {
4196 assert(parameter->parent_scope == NULL);
4197 parameter->parent_scope = scope;
4198 environment_push(parameter);
4201 /* parse declaration list */
4202 while (is_declaration_specifier(&token, false)) {
4203 parse_declaration(finished_kr_declaration);
4206 /* pop function parameters */
4207 assert(scope == &declaration->scope);
4208 set_scope(last_scope);
4209 environment_pop_to(top);
4211 /* update function type */
4212 type_t *new_type = duplicate_type(type);
4214 function_parameter_t *parameters = NULL;
4215 function_parameter_t *last_parameter = NULL;
4217 declaration_t *parameter_declaration = declaration->scope.declarations;
4218 for( ; parameter_declaration != NULL;
4219 parameter_declaration = parameter_declaration->next) {
4220 type_t *parameter_type = parameter_declaration->type;
4221 if(parameter_type == NULL) {
4223 errorf(HERE, "no type specified for function parameter '%Y'",
4224 parameter_declaration->symbol);
4226 if (warning.implicit_int) {
4227 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4228 parameter_declaration->symbol);
4230 parameter_type = type_int;
4231 parameter_declaration->type = parameter_type;
4235 semantic_parameter(parameter_declaration);
4236 parameter_type = parameter_declaration->type;
4239 * we need the default promoted types for the function type
4241 parameter_type = get_default_promoted_type(parameter_type);
4243 function_parameter_t *function_parameter
4244 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4245 memset(function_parameter, 0, sizeof(function_parameter[0]));
4247 function_parameter->type = parameter_type;
4248 if(last_parameter != NULL) {
4249 last_parameter->next = function_parameter;
4251 parameters = function_parameter;
4253 last_parameter = function_parameter;
4256 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4258 new_type->function.parameters = parameters;
4259 new_type->function.unspecified_parameters = true;
4261 type = typehash_insert(new_type);
4262 if(type != new_type) {
4263 obstack_free(type_obst, new_type);
4266 declaration->type = type;
4269 static bool first_err = true;
4272 * When called with first_err set, prints the name of the current function,
4275 static void print_in_function(void) {
4278 diagnosticf("%s: In function '%Y':\n",
4279 current_function->source_position.input_name,
4280 current_function->symbol);
4285 * Check if all labels are defined in the current function.
4286 * Check if all labels are used in the current function.
4288 static void check_labels(void)
4290 for (const goto_statement_t *goto_statement = goto_first;
4291 goto_statement != NULL;
4292 goto_statement = goto_statement->next) {
4293 declaration_t *label = goto_statement->label;
4296 if (label->source_position.input_name == NULL) {
4297 print_in_function();
4298 errorf(&goto_statement->base.source_position,
4299 "label '%Y' used but not defined", label->symbol);
4302 goto_first = goto_last = NULL;
4304 if (warning.unused_label) {
4305 for (const label_statement_t *label_statement = label_first;
4306 label_statement != NULL;
4307 label_statement = label_statement->next) {
4308 const declaration_t *label = label_statement->label;
4310 if (! label->used) {
4311 print_in_function();
4312 warningf(&label_statement->base.source_position,
4313 "label '%Y' defined but not used", label->symbol);
4317 label_first = label_last = NULL;
4321 * Check declarations of current_function for unused entities.
4323 static void check_declarations(void)
4325 if (warning.unused_parameter) {
4326 const scope_t *scope = ¤t_function->scope;
4328 const declaration_t *parameter = scope->declarations;
4329 for (; parameter != NULL; parameter = parameter->next) {
4330 if (! parameter->used) {
4331 print_in_function();
4332 warningf(¶meter->source_position,
4333 "unused parameter '%Y'", parameter->symbol);
4337 if (warning.unused_variable) {
4341 static void parse_external_declaration(void)
4343 /* function-definitions and declarations both start with declaration
4345 declaration_specifiers_t specifiers;
4346 memset(&specifiers, 0, sizeof(specifiers));
4348 add_anchor_token(';');
4349 parse_declaration_specifiers(&specifiers);
4350 rem_anchor_token(';');
4352 /* must be a declaration */
4353 if(token.type == ';') {
4354 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4358 add_anchor_token(',');
4359 add_anchor_token('=');
4360 rem_anchor_token(';');
4362 /* declarator is common to both function-definitions and declarations */
4363 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4365 rem_anchor_token(',');
4366 rem_anchor_token('=');
4367 rem_anchor_token(';');
4369 /* must be a declaration */
4370 if(token.type == ',' || token.type == '=' || token.type == ';') {
4371 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4375 /* must be a function definition */
4376 parse_kr_declaration_list(ndeclaration);
4378 if(token.type != '{') {
4379 parse_error_expected("while parsing function definition", '{', NULL);
4380 eat_until_matching_token(';');
4384 type_t *type = ndeclaration->type;
4386 /* note that we don't skip typerefs: the standard doesn't allow them here
4387 * (so we can't use is_type_function here) */
4388 if(type->kind != TYPE_FUNCTION) {
4389 if (is_type_valid(type)) {
4390 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4391 type, ndeclaration->symbol);
4397 /* § 6.7.5.3 (14) a function definition with () means no
4398 * parameters (and not unspecified parameters) */
4399 if(type->function.unspecified_parameters
4400 && type->function.parameters == NULL
4401 && !type->function.kr_style_parameters) {
4402 type_t *duplicate = duplicate_type(type);
4403 duplicate->function.unspecified_parameters = false;
4405 type = typehash_insert(duplicate);
4406 if(type != duplicate) {
4407 obstack_free(type_obst, duplicate);
4409 ndeclaration->type = type;
4412 declaration_t *const declaration = record_function_definition(ndeclaration);
4413 if(ndeclaration != declaration) {
4414 declaration->scope = ndeclaration->scope;
4416 type = skip_typeref(declaration->type);
4418 /* push function parameters and switch scope */
4419 int top = environment_top();
4420 scope_t *last_scope = scope;
4421 set_scope(&declaration->scope);
4423 declaration_t *parameter = declaration->scope.declarations;
4424 for( ; parameter != NULL; parameter = parameter->next) {
4425 if(parameter->parent_scope == &ndeclaration->scope) {
4426 parameter->parent_scope = scope;
4428 assert(parameter->parent_scope == NULL
4429 || parameter->parent_scope == scope);
4430 parameter->parent_scope = scope;
4431 environment_push(parameter);
4434 if(declaration->init.statement != NULL) {
4435 parser_error_multiple_definition(declaration, HERE);
4437 goto end_of_parse_external_declaration;
4439 /* parse function body */
4440 int label_stack_top = label_top();
4441 declaration_t *old_current_function = current_function;
4442 current_function = declaration;
4444 declaration->init.statement = parse_compound_statement(false);
4447 check_declarations();
4449 assert(current_function == declaration);
4450 current_function = old_current_function;
4451 label_pop_to(label_stack_top);
4454 end_of_parse_external_declaration:
4455 assert(scope == &declaration->scope);
4456 set_scope(last_scope);
4457 environment_pop_to(top);
4460 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4461 source_position_t *source_position)
4463 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4465 type->bitfield.base_type = base_type;
4466 type->bitfield.size = size;
4471 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4474 declaration_t *iter = compound_declaration->scope.declarations;
4475 for( ; iter != NULL; iter = iter->next) {
4476 if(iter->namespc != NAMESPACE_NORMAL)
4479 if(iter->symbol == NULL) {
4480 type_t *type = skip_typeref(iter->type);
4481 if(is_type_compound(type)) {
4482 declaration_t *result
4483 = find_compound_entry(type->compound.declaration, symbol);
4490 if(iter->symbol == symbol) {
4498 static void parse_compound_declarators(declaration_t *struct_declaration,
4499 const declaration_specifiers_t *specifiers)
4501 declaration_t *last_declaration = struct_declaration->scope.declarations;
4502 if(last_declaration != NULL) {
4503 while(last_declaration->next != NULL) {
4504 last_declaration = last_declaration->next;
4509 declaration_t *declaration;
4511 if(token.type == ':') {
4512 source_position_t source_position = *HERE;
4515 type_t *base_type = specifiers->type;
4516 expression_t *size = parse_constant_expression();
4518 if(!is_type_integer(skip_typeref(base_type))) {
4519 errorf(HERE, "bitfield base type '%T' is not an integer type",
4523 type_t *type = make_bitfield_type(base_type, size, &source_position);
4525 declaration = allocate_declaration_zero();
4526 declaration->namespc = NAMESPACE_NORMAL;
4527 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4528 declaration->storage_class = STORAGE_CLASS_NONE;
4529 declaration->source_position = source_position;
4530 declaration->decl_modifiers = specifiers->decl_modifiers;
4531 declaration->type = type;
4533 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4535 type_t *orig_type = declaration->type;
4536 type_t *type = skip_typeref(orig_type);
4538 if(token.type == ':') {
4539 source_position_t source_position = *HERE;
4541 expression_t *size = parse_constant_expression();
4543 if(!is_type_integer(type)) {
4544 errorf(HERE, "bitfield base type '%T' is not an "
4545 "integer type", orig_type);
4548 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4549 declaration->type = bitfield_type;
4551 /* TODO we ignore arrays for now... what is missing is a check
4552 * that they're at the end of the struct */
4553 if(is_type_incomplete(type) && !is_type_array(type)) {
4555 "compound member '%Y' has incomplete type '%T'",
4556 declaration->symbol, orig_type);
4557 } else if(is_type_function(type)) {
4558 errorf(HERE, "compound member '%Y' must not have function "
4559 "type '%T'", declaration->symbol, orig_type);
4564 /* make sure we don't define a symbol multiple times */
4565 symbol_t *symbol = declaration->symbol;
4566 if(symbol != NULL) {
4567 declaration_t *prev_decl
4568 = find_compound_entry(struct_declaration, symbol);
4570 if(prev_decl != NULL) {
4571 assert(prev_decl->symbol == symbol);
4572 errorf(&declaration->source_position,
4573 "multiple declarations of symbol '%Y' (declared %P)",
4574 symbol, &prev_decl->source_position);
4578 /* append declaration */
4579 if(last_declaration != NULL) {
4580 last_declaration->next = declaration;
4582 struct_declaration->scope.declarations = declaration;
4584 last_declaration = declaration;
4586 if(token.type != ',')
4596 static void parse_compound_type_entries(declaration_t *compound_declaration)
4599 add_anchor_token('}');
4601 while(token.type != '}' && token.type != T_EOF) {
4602 declaration_specifiers_t specifiers;
4603 memset(&specifiers, 0, sizeof(specifiers));
4604 parse_declaration_specifiers(&specifiers);
4606 parse_compound_declarators(compound_declaration, &specifiers);
4608 rem_anchor_token('}');
4610 if(token.type == T_EOF) {
4611 errorf(HERE, "EOF while parsing struct");
4616 static type_t *parse_typename(void)
4618 declaration_specifiers_t specifiers;
4619 memset(&specifiers, 0, sizeof(specifiers));
4620 parse_declaration_specifiers(&specifiers);
4621 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4622 /* TODO: improve error message, user does probably not know what a
4623 * storage class is...
4625 errorf(HERE, "typename may not have a storage class");
4628 type_t *result = parse_abstract_declarator(specifiers.type);
4636 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4637 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4638 expression_t *left);
4640 typedef struct expression_parser_function_t expression_parser_function_t;
4641 struct expression_parser_function_t {
4642 unsigned precedence;
4643 parse_expression_function parser;
4644 unsigned infix_precedence;
4645 parse_expression_infix_function infix_parser;
4648 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4651 * Prints an error message if an expression was expected but not read
4653 static expression_t *expected_expression_error(void)
4655 /* skip the error message if the error token was read */
4656 if (token.type != T_ERROR) {
4657 errorf(HERE, "expected expression, got token '%K'", &token);
4661 return create_invalid_expression();
4665 * Parse a string constant.
4667 static expression_t *parse_string_const(void)
4670 if (token.type == T_STRING_LITERAL) {
4671 string_t res = token.v.string;
4673 while (token.type == T_STRING_LITERAL) {
4674 res = concat_strings(&res, &token.v.string);
4677 if (token.type != T_WIDE_STRING_LITERAL) {
4678 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4679 /* note: that we use type_char_ptr here, which is already the
4680 * automatic converted type. revert_automatic_type_conversion
4681 * will construct the array type */
4682 cnst->base.type = type_char_ptr;
4683 cnst->string.value = res;
4687 wres = concat_string_wide_string(&res, &token.v.wide_string);
4689 wres = token.v.wide_string;
4694 switch (token.type) {
4695 case T_WIDE_STRING_LITERAL:
4696 wres = concat_wide_strings(&wres, &token.v.wide_string);
4699 case T_STRING_LITERAL:
4700 wres = concat_wide_string_string(&wres, &token.v.string);
4704 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4705 cnst->base.type = type_wchar_t_ptr;
4706 cnst->wide_string.value = wres;
4715 * Parse an integer constant.
4717 static expression_t *parse_int_const(void)
4719 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4720 cnst->base.source_position = *HERE;
4721 cnst->base.type = token.datatype;
4722 cnst->conste.v.int_value = token.v.intvalue;
4730 * Parse a character constant.
4732 static expression_t *parse_character_constant(void)
4734 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4736 cnst->base.source_position = *HERE;
4737 cnst->base.type = token.datatype;
4738 cnst->conste.v.character = token.v.string;
4740 if (cnst->conste.v.character.size != 1) {
4741 if (warning.multichar && (c_mode & _GNUC)) {
4743 warningf(HERE, "multi-character character constant");
4745 errorf(HERE, "more than 1 characters in character constant");
4754 * Parse a wide character constant.
4756 static expression_t *parse_wide_character_constant(void)
4758 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4760 cnst->base.source_position = *HERE;
4761 cnst->base.type = token.datatype;
4762 cnst->conste.v.wide_character = token.v.wide_string;
4764 if (cnst->conste.v.wide_character.size != 1) {
4765 if (warning.multichar && (c_mode & _GNUC)) {
4767 warningf(HERE, "multi-character character constant");
4769 errorf(HERE, "more than 1 characters in character constant");
4778 * Parse a float constant.
4780 static expression_t *parse_float_const(void)
4782 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4783 cnst->base.type = token.datatype;
4784 cnst->conste.v.float_value = token.v.floatvalue;
4791 static declaration_t *create_implicit_function(symbol_t *symbol,
4792 const source_position_t *source_position)
4794 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4795 ntype->function.return_type = type_int;
4796 ntype->function.unspecified_parameters = true;
4798 type_t *type = typehash_insert(ntype);
4803 declaration_t *const declaration = allocate_declaration_zero();
4804 declaration->storage_class = STORAGE_CLASS_EXTERN;
4805 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4806 declaration->type = type;
4807 declaration->symbol = symbol;
4808 declaration->source_position = *source_position;
4810 bool strict_prototypes_old = warning.strict_prototypes;
4811 warning.strict_prototypes = false;
4812 record_declaration(declaration);
4813 warning.strict_prototypes = strict_prototypes_old;
4819 * Creates a return_type (func)(argument_type) function type if not
4822 * @param return_type the return type
4823 * @param argument_type the argument type
4825 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4827 function_parameter_t *parameter
4828 = obstack_alloc(type_obst, sizeof(parameter[0]));
4829 memset(parameter, 0, sizeof(parameter[0]));
4830 parameter->type = argument_type;
4832 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4833 type->function.return_type = return_type;
4834 type->function.parameters = parameter;
4836 type_t *result = typehash_insert(type);
4837 if(result != type) {
4844 static type_t *make_function_0_type(type_t *return_type)
4846 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4847 type->function.return_type = return_type;
4848 type->function.parameters = NULL;
4850 type_t *result = typehash_insert(type);
4851 if(result != type) {
4859 * Creates a function type for some function like builtins.
4861 * @param symbol the symbol describing the builtin
4863 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4865 switch(symbol->ID) {
4866 case T___builtin_alloca:
4867 return make_function_1_type(type_void_ptr, type_size_t);
4868 case T___builtin_huge_val:
4869 return make_function_0_type(type_double);
4870 case T___builtin_nan:
4871 return make_function_1_type(type_double, type_char_ptr);
4872 case T___builtin_nanf:
4873 return make_function_1_type(type_float, type_char_ptr);
4874 case T___builtin_nand:
4875 return make_function_1_type(type_long_double, type_char_ptr);
4876 case T___builtin_va_end:
4877 return make_function_1_type(type_void, type_valist);
4879 internal_errorf(HERE, "not implemented builtin symbol found");
4884 * Performs automatic type cast as described in § 6.3.2.1.
4886 * @param orig_type the original type
4888 static type_t *automatic_type_conversion(type_t *orig_type)
4890 type_t *type = skip_typeref(orig_type);
4891 if(is_type_array(type)) {
4892 array_type_t *array_type = &type->array;
4893 type_t *element_type = array_type->element_type;
4894 unsigned qualifiers = array_type->base.qualifiers;
4896 return make_pointer_type(element_type, qualifiers);
4899 if(is_type_function(type)) {
4900 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4907 * reverts the automatic casts of array to pointer types and function
4908 * to function-pointer types as defined § 6.3.2.1
4910 type_t *revert_automatic_type_conversion(const expression_t *expression)
4912 switch (expression->kind) {
4913 case EXPR_REFERENCE: return expression->reference.declaration->type;
4914 case EXPR_SELECT: return expression->select.compound_entry->type;
4916 case EXPR_UNARY_DEREFERENCE: {
4917 const expression_t *const value = expression->unary.value;
4918 type_t *const type = skip_typeref(value->base.type);
4919 assert(is_type_pointer(type));
4920 return type->pointer.points_to;
4923 case EXPR_BUILTIN_SYMBOL:
4924 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4926 case EXPR_ARRAY_ACCESS: {
4927 const expression_t *array_ref = expression->array_access.array_ref;
4928 type_t *type_left = skip_typeref(array_ref->base.type);
4929 if (!is_type_valid(type_left))
4931 assert(is_type_pointer(type_left));
4932 return type_left->pointer.points_to;
4935 case EXPR_STRING_LITERAL: {
4936 size_t size = expression->string.value.size;
4937 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4940 case EXPR_WIDE_STRING_LITERAL: {
4941 size_t size = expression->wide_string.value.size;
4942 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4945 case EXPR_COMPOUND_LITERAL:
4946 return expression->compound_literal.type;
4951 return expression->base.type;
4954 static expression_t *parse_reference(void)
4956 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4958 reference_expression_t *ref = &expression->reference;
4959 symbol_t *const symbol = token.v.symbol;
4961 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
4963 source_position_t source_position = token.source_position;
4966 if(declaration == NULL) {
4967 if (! strict_mode && token.type == '(') {
4968 /* an implicitly defined function */
4969 if (warning.implicit_function_declaration) {
4970 warningf(HERE, "implicit declaration of function '%Y'",
4974 declaration = create_implicit_function(symbol,
4977 errorf(HERE, "unknown symbol '%Y' found.", symbol);
4978 return create_invalid_expression();
4982 type_t *type = declaration->type;
4984 /* we always do the auto-type conversions; the & and sizeof parser contains
4985 * code to revert this! */
4986 type = automatic_type_conversion(type);
4988 ref->declaration = declaration;
4989 ref->base.type = type;
4991 /* this declaration is used */
4992 declaration->used = true;
4994 /* check for deprecated functions */
4995 if(declaration->deprecated != 0) {
4996 const char *prefix = "";
4997 if (is_type_function(declaration->type))
4998 prefix = "function ";
5000 if (declaration->deprecated_string != NULL) {
5001 warningf(&source_position,
5002 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5003 declaration->deprecated_string);
5005 warningf(&source_position,
5006 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5013 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5017 /* TODO check if explicit cast is allowed and issue warnings/errors */
5020 static expression_t *parse_compound_literal(type_t *type)
5022 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5024 parse_initializer_env_t env;
5026 env.declaration = NULL;
5027 env.must_be_constant = false;
5028 initializer_t *initializer = parse_initializer(&env);
5031 expression->compound_literal.initializer = initializer;
5032 expression->compound_literal.type = type;
5033 expression->base.type = automatic_type_conversion(type);
5039 * Parse a cast expression.
5041 static expression_t *parse_cast(void)
5043 source_position_t source_position = token.source_position;
5045 type_t *type = parse_typename();
5047 /* matching add_anchor_token() is at call site */
5048 rem_anchor_token(')');
5051 if(token.type == '{') {
5052 return parse_compound_literal(type);
5055 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5056 cast->base.source_position = source_position;
5058 expression_t *value = parse_sub_expression(20);
5060 check_cast_allowed(value, type);
5062 cast->base.type = type;
5063 cast->unary.value = value;
5067 return create_invalid_expression();
5071 * Parse a statement expression.
5073 static expression_t *parse_statement_expression(void)
5075 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5077 statement_t *statement = parse_compound_statement(true);
5078 expression->statement.statement = statement;
5079 expression->base.source_position = statement->base.source_position;
5081 /* find last statement and use its type */
5082 type_t *type = type_void;
5083 const statement_t *stmt = statement->compound.statements;
5085 while (stmt->base.next != NULL)
5086 stmt = stmt->base.next;
5088 if (stmt->kind == STATEMENT_EXPRESSION) {
5089 type = stmt->expression.expression->base.type;
5092 warningf(&expression->base.source_position, "empty statement expression ({})");
5094 expression->base.type = type;
5100 return create_invalid_expression();
5104 * Parse a braced expression.
5106 static expression_t *parse_brace_expression(void)
5109 add_anchor_token(')');
5111 switch(token.type) {
5113 /* gcc extension: a statement expression */
5114 return parse_statement_expression();
5118 return parse_cast();
5120 if(is_typedef_symbol(token.v.symbol)) {
5121 return parse_cast();
5125 expression_t *result = parse_expression();
5126 rem_anchor_token(')');
5131 return create_invalid_expression();
5134 static expression_t *parse_function_keyword(void)
5139 if (current_function == NULL) {
5140 errorf(HERE, "'__func__' used outside of a function");
5143 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5144 expression->base.type = type_char_ptr;
5145 expression->funcname.kind = FUNCNAME_FUNCTION;
5150 static expression_t *parse_pretty_function_keyword(void)
5152 eat(T___PRETTY_FUNCTION__);
5154 if (current_function == NULL) {
5155 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5158 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5159 expression->base.type = type_char_ptr;
5160 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5165 static expression_t *parse_funcsig_keyword(void)
5169 if (current_function == NULL) {
5170 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5173 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5174 expression->base.type = type_char_ptr;
5175 expression->funcname.kind = FUNCNAME_FUNCSIG;
5180 static expression_t *parse_funcdname_keyword(void)
5182 eat(T___FUNCDNAME__);
5184 if (current_function == NULL) {
5185 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5188 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5189 expression->base.type = type_char_ptr;
5190 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5195 static designator_t *parse_designator(void)
5197 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5198 result->source_position = *HERE;
5200 if(token.type != T_IDENTIFIER) {
5201 parse_error_expected("while parsing member designator",
5202 T_IDENTIFIER, NULL);
5205 result->symbol = token.v.symbol;
5208 designator_t *last_designator = result;
5210 if(token.type == '.') {
5212 if(token.type != T_IDENTIFIER) {
5213 parse_error_expected("while parsing member designator",
5214 T_IDENTIFIER, NULL);
5217 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5218 designator->source_position = *HERE;
5219 designator->symbol = token.v.symbol;
5222 last_designator->next = designator;
5223 last_designator = designator;
5226 if(token.type == '[') {
5228 add_anchor_token(']');
5229 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5230 designator->source_position = *HERE;
5231 designator->array_index = parse_expression();
5232 rem_anchor_token(']');
5234 if(designator->array_index == NULL) {
5238 last_designator->next = designator;
5239 last_designator = designator;
5251 * Parse the __builtin_offsetof() expression.
5253 static expression_t *parse_offsetof(void)
5255 eat(T___builtin_offsetof);
5257 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5258 expression->base.type = type_size_t;
5261 add_anchor_token(',');
5262 type_t *type = parse_typename();
5263 rem_anchor_token(',');
5265 add_anchor_token(')');
5266 designator_t *designator = parse_designator();
5267 rem_anchor_token(')');
5270 expression->offsetofe.type = type;
5271 expression->offsetofe.designator = designator;
5274 memset(&path, 0, sizeof(path));
5275 path.top_type = type;
5276 path.path = NEW_ARR_F(type_path_entry_t, 0);
5278 descend_into_subtype(&path);
5280 if(!walk_designator(&path, designator, true)) {
5281 return create_invalid_expression();
5284 DEL_ARR_F(path.path);
5288 return create_invalid_expression();
5292 * Parses a _builtin_va_start() expression.
5294 static expression_t *parse_va_start(void)
5296 eat(T___builtin_va_start);
5298 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5301 add_anchor_token(',');
5302 expression->va_starte.ap = parse_assignment_expression();
5303 rem_anchor_token(',');
5305 expression_t *const expr = parse_assignment_expression();
5306 if (expr->kind == EXPR_REFERENCE) {
5307 declaration_t *const decl = expr->reference.declaration;
5309 return create_invalid_expression();
5310 if (decl->parent_scope == ¤t_function->scope &&
5311 decl->next == NULL) {
5312 expression->va_starte.parameter = decl;
5317 errorf(&expr->base.source_position,
5318 "second argument of 'va_start' must be last parameter of the current function");
5320 return create_invalid_expression();
5324 * Parses a _builtin_va_arg() expression.
5326 static expression_t *parse_va_arg(void)
5328 eat(T___builtin_va_arg);
5330 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5333 expression->va_arge.ap = parse_assignment_expression();
5335 expression->base.type = parse_typename();
5340 return create_invalid_expression();
5343 static expression_t *parse_builtin_symbol(void)
5345 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5347 symbol_t *symbol = token.v.symbol;
5349 expression->builtin_symbol.symbol = symbol;
5352 type_t *type = get_builtin_symbol_type(symbol);
5353 type = automatic_type_conversion(type);
5355 expression->base.type = type;
5360 * Parses a __builtin_constant() expression.
5362 static expression_t *parse_builtin_constant(void)
5364 eat(T___builtin_constant_p);
5366 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5369 add_anchor_token(')');
5370 expression->builtin_constant.value = parse_assignment_expression();
5371 rem_anchor_token(')');
5373 expression->base.type = type_int;
5377 return create_invalid_expression();
5381 * Parses a __builtin_prefetch() expression.
5383 static expression_t *parse_builtin_prefetch(void)
5385 eat(T___builtin_prefetch);
5387 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5390 add_anchor_token(')');
5391 expression->builtin_prefetch.adr = parse_assignment_expression();
5392 if (token.type == ',') {
5394 expression->builtin_prefetch.rw = parse_assignment_expression();
5396 if (token.type == ',') {
5398 expression->builtin_prefetch.locality = parse_assignment_expression();
5400 rem_anchor_token(')');
5402 expression->base.type = type_void;
5406 return create_invalid_expression();
5410 * Parses a __builtin_is_*() compare expression.
5412 static expression_t *parse_compare_builtin(void)
5414 expression_t *expression;
5416 switch(token.type) {
5417 case T___builtin_isgreater:
5418 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5420 case T___builtin_isgreaterequal:
5421 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5423 case T___builtin_isless:
5424 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5426 case T___builtin_islessequal:
5427 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5429 case T___builtin_islessgreater:
5430 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5432 case T___builtin_isunordered:
5433 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5436 internal_errorf(HERE, "invalid compare builtin found");
5439 expression->base.source_position = *HERE;
5443 expression->binary.left = parse_assignment_expression();
5445 expression->binary.right = parse_assignment_expression();
5448 type_t *const orig_type_left = expression->binary.left->base.type;
5449 type_t *const orig_type_right = expression->binary.right->base.type;
5451 type_t *const type_left = skip_typeref(orig_type_left);
5452 type_t *const type_right = skip_typeref(orig_type_right);
5453 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5454 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5455 type_error_incompatible("invalid operands in comparison",
5456 &expression->base.source_position, orig_type_left, orig_type_right);
5459 semantic_comparison(&expression->binary);
5464 return create_invalid_expression();
5468 * Parses a __builtin_expect() expression.
5470 static expression_t *parse_builtin_expect(void)
5472 eat(T___builtin_expect);
5474 expression_t *expression
5475 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5478 expression->binary.left = parse_assignment_expression();
5480 expression->binary.right = parse_constant_expression();
5483 expression->base.type = expression->binary.left->base.type;
5487 return create_invalid_expression();
5491 * Parses a MS assume() expression.
5493 static expression_t *parse_assume(void) {
5496 expression_t *expression
5497 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5500 add_anchor_token(')');
5501 expression->unary.value = parse_assignment_expression();
5502 rem_anchor_token(')');
5505 expression->base.type = type_void;
5508 return create_invalid_expression();
5512 * Parse a microsoft __noop expression.
5514 static expression_t *parse_noop_expression(void) {
5515 source_position_t source_position = *HERE;
5518 if (token.type == '(') {
5519 /* parse arguments */
5521 add_anchor_token(')');
5522 add_anchor_token(',');
5524 if(token.type != ')') {
5526 (void)parse_assignment_expression();
5527 if(token.type != ',')
5533 rem_anchor_token(',');
5534 rem_anchor_token(')');
5537 /* the result is a (int)0 */
5538 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5539 cnst->base.source_position = source_position;
5540 cnst->base.type = type_int;
5541 cnst->conste.v.int_value = 0;
5542 cnst->conste.is_ms_noop = true;
5547 return create_invalid_expression();
5551 * Parses a primary expression.
5553 static expression_t *parse_primary_expression(void)
5555 switch (token.type) {
5556 case T_INTEGER: return parse_int_const();
5557 case T_CHARACTER_CONSTANT: return parse_character_constant();
5558 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5559 case T_FLOATINGPOINT: return parse_float_const();
5560 case T_STRING_LITERAL:
5561 case T_WIDE_STRING_LITERAL: return parse_string_const();
5562 case T_IDENTIFIER: return parse_reference();
5563 case T___FUNCTION__:
5564 case T___func__: return parse_function_keyword();
5565 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5566 case T___FUNCSIG__: return parse_funcsig_keyword();
5567 case T___FUNCDNAME__: return parse_funcdname_keyword();
5568 case T___builtin_offsetof: return parse_offsetof();
5569 case T___builtin_va_start: return parse_va_start();
5570 case T___builtin_va_arg: return parse_va_arg();
5571 case T___builtin_expect: return parse_builtin_expect();
5572 case T___builtin_alloca:
5573 case T___builtin_nan:
5574 case T___builtin_nand:
5575 case T___builtin_nanf:
5576 case T___builtin_huge_val:
5577 case T___builtin_va_end: return parse_builtin_symbol();
5578 case T___builtin_isgreater:
5579 case T___builtin_isgreaterequal:
5580 case T___builtin_isless:
5581 case T___builtin_islessequal:
5582 case T___builtin_islessgreater:
5583 case T___builtin_isunordered: return parse_compare_builtin();
5584 case T___builtin_constant_p: return parse_builtin_constant();
5585 case T___builtin_prefetch: return parse_builtin_prefetch();
5586 case T__assume: return parse_assume();
5588 case '(': return parse_brace_expression();
5589 case T___noop: return parse_noop_expression();
5592 errorf(HERE, "unexpected token %K, expected an expression", &token);
5593 return create_invalid_expression();
5597 * Check if the expression has the character type and issue a warning then.
5599 static void check_for_char_index_type(const expression_t *expression) {
5600 type_t *const type = expression->base.type;
5601 const type_t *const base_type = skip_typeref(type);
5603 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5604 warning.char_subscripts) {
5605 warningf(&expression->base.source_position,
5606 "array subscript has type '%T'", type);
5610 static expression_t *parse_array_expression(unsigned precedence,
5616 add_anchor_token(']');
5618 expression_t *inside = parse_expression();
5620 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5622 array_access_expression_t *array_access = &expression->array_access;
5624 type_t *const orig_type_left = left->base.type;
5625 type_t *const orig_type_inside = inside->base.type;
5627 type_t *const type_left = skip_typeref(orig_type_left);
5628 type_t *const type_inside = skip_typeref(orig_type_inside);
5630 type_t *return_type;
5631 if (is_type_pointer(type_left)) {
5632 return_type = type_left->pointer.points_to;
5633 array_access->array_ref = left;
5634 array_access->index = inside;
5635 check_for_char_index_type(inside);
5636 } else if (is_type_pointer(type_inside)) {
5637 return_type = type_inside->pointer.points_to;
5638 array_access->array_ref = inside;
5639 array_access->index = left;
5640 array_access->flipped = true;
5641 check_for_char_index_type(left);
5643 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5645 "array access on object with non-pointer types '%T', '%T'",
5646 orig_type_left, orig_type_inside);
5648 return_type = type_error_type;
5649 array_access->array_ref = create_invalid_expression();
5652 rem_anchor_token(']');
5653 if(token.type != ']') {
5654 parse_error_expected("Problem while parsing array access", ']', NULL);
5659 return_type = automatic_type_conversion(return_type);
5660 expression->base.type = return_type;
5665 static expression_t *parse_typeprop(expression_kind_t const kind,
5666 source_position_t const pos,
5667 unsigned const precedence)
5669 expression_t *tp_expression = allocate_expression_zero(kind);
5670 tp_expression->base.type = type_size_t;
5671 tp_expression->base.source_position = pos;
5673 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5675 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5677 add_anchor_token(')');
5678 type_t* const orig_type = parse_typename();
5679 tp_expression->typeprop.type = orig_type;
5681 type_t const* const type = skip_typeref(orig_type);
5682 char const* const wrong_type =
5683 is_type_incomplete(type) ? "incomplete" :
5684 type->kind == TYPE_FUNCTION ? "function designator" :
5685 type->kind == TYPE_BITFIELD ? "bitfield" :
5687 if (wrong_type != NULL) {
5688 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5689 what, wrong_type, type);
5692 rem_anchor_token(')');
5695 expression_t *expression = parse_sub_expression(precedence);
5697 type_t* const orig_type = revert_automatic_type_conversion(expression);
5698 expression->base.type = orig_type;
5700 type_t const* const type = skip_typeref(orig_type);
5701 char const* const wrong_type =
5702 is_type_incomplete(type) ? "incomplete" :
5703 type->kind == TYPE_FUNCTION ? "function designator" :
5704 type->kind == TYPE_BITFIELD ? "bitfield" :
5706 if (wrong_type != NULL) {
5707 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5710 tp_expression->typeprop.type = expression->base.type;
5711 tp_expression->typeprop.tp_expression = expression;
5714 return tp_expression;
5716 return create_invalid_expression();
5719 static expression_t *parse_sizeof(unsigned precedence)
5721 source_position_t pos = *HERE;
5723 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5726 static expression_t *parse_alignof(unsigned precedence)
5728 source_position_t pos = *HERE;
5730 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5733 static expression_t *parse_select_expression(unsigned precedence,
5734 expression_t *compound)
5737 assert(token.type == '.' || token.type == T_MINUSGREATER);
5739 bool is_pointer = (token.type == T_MINUSGREATER);
5742 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5743 select->select.compound = compound;
5745 if (token.type != T_IDENTIFIER) {
5746 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5749 symbol_t *symbol = token.v.symbol;
5750 select->select.symbol = symbol;
5753 type_t *const orig_type = compound->base.type;
5754 type_t *const type = skip_typeref(orig_type);
5756 type_t *type_left = type;
5758 if (!is_type_pointer(type)) {
5759 if (is_type_valid(type)) {
5760 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5762 return create_invalid_expression();
5764 type_left = type->pointer.points_to;
5766 type_left = skip_typeref(type_left);
5768 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5769 type_left->kind != TYPE_COMPOUND_UNION) {
5770 if (is_type_valid(type_left)) {
5771 errorf(HERE, "request for member '%Y' in something not a struct or "
5772 "union, but '%T'", symbol, type_left);
5774 return create_invalid_expression();
5777 declaration_t *const declaration = type_left->compound.declaration;
5779 if (!declaration->init.complete) {
5780 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5782 return create_invalid_expression();
5785 declaration_t *iter = find_compound_entry(declaration, symbol);
5787 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5788 return create_invalid_expression();
5791 /* we always do the auto-type conversions; the & and sizeof parser contains
5792 * code to revert this! */
5793 type_t *expression_type = automatic_type_conversion(iter->type);
5795 select->select.compound_entry = iter;
5796 select->base.type = expression_type;
5798 type_t *skipped = skip_typeref(iter->type);
5799 if (skipped->kind == TYPE_BITFIELD) {
5800 select->base.type = skipped->bitfield.base_type;
5807 * Parse a call expression, ie. expression '( ... )'.
5809 * @param expression the function address
5811 static expression_t *parse_call_expression(unsigned precedence,
5812 expression_t *expression)
5815 expression_t *result = allocate_expression_zero(EXPR_CALL);
5816 result->base.source_position = expression->base.source_position;
5818 call_expression_t *call = &result->call;
5819 call->function = expression;
5821 type_t *const orig_type = expression->base.type;
5822 type_t *const type = skip_typeref(orig_type);
5824 function_type_t *function_type = NULL;
5825 if (is_type_pointer(type)) {
5826 type_t *const to_type = skip_typeref(type->pointer.points_to);
5828 if (is_type_function(to_type)) {
5829 function_type = &to_type->function;
5830 call->base.type = function_type->return_type;
5834 if (function_type == NULL && is_type_valid(type)) {
5835 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5838 /* parse arguments */
5840 add_anchor_token(')');
5841 add_anchor_token(',');
5843 if(token.type != ')') {
5844 call_argument_t *last_argument = NULL;
5847 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5849 argument->expression = parse_assignment_expression();
5850 if(last_argument == NULL) {
5851 call->arguments = argument;
5853 last_argument->next = argument;
5855 last_argument = argument;
5857 if(token.type != ',')
5862 rem_anchor_token(',');
5863 rem_anchor_token(')');
5866 if(function_type == NULL)
5869 function_parameter_t *parameter = function_type->parameters;
5870 call_argument_t *argument = call->arguments;
5871 if (!function_type->unspecified_parameters) {
5872 for( ; parameter != NULL && argument != NULL;
5873 parameter = parameter->next, argument = argument->next) {
5874 type_t *expected_type = parameter->type;
5875 /* TODO report scope in error messages */
5876 expression_t *const arg_expr = argument->expression;
5877 type_t *const res_type = semantic_assign(expected_type, arg_expr,
5879 &arg_expr->base.source_position);
5880 if (res_type == NULL) {
5881 /* TODO improve error message */
5882 errorf(&arg_expr->base.source_position,
5883 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5884 arg_expr, arg_expr->base.type, expected_type);
5886 argument->expression = create_implicit_cast(argument->expression, expected_type);
5890 if (parameter != NULL) {
5891 errorf(HERE, "too few arguments to function '%E'", expression);
5892 } else if (argument != NULL && !function_type->variadic) {
5893 errorf(HERE, "too many arguments to function '%E'", expression);
5897 /* do default promotion */
5898 for( ; argument != NULL; argument = argument->next) {
5899 type_t *type = argument->expression->base.type;
5901 type = get_default_promoted_type(type);
5903 argument->expression
5904 = create_implicit_cast(argument->expression, type);
5907 check_format(&result->call);
5911 return create_invalid_expression();
5914 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5916 static bool same_compound_type(const type_t *type1, const type_t *type2)
5919 is_type_compound(type1) &&
5920 type1->kind == type2->kind &&
5921 type1->compound.declaration == type2->compound.declaration;
5925 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5927 * @param expression the conditional expression
5929 static expression_t *parse_conditional_expression(unsigned precedence,
5930 expression_t *expression)
5933 add_anchor_token(':');
5935 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5937 conditional_expression_t *conditional = &result->conditional;
5938 conditional->condition = expression;
5941 type_t *const condition_type_orig = expression->base.type;
5942 type_t *const condition_type = skip_typeref(condition_type_orig);
5943 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5944 type_error("expected a scalar type in conditional condition",
5945 &expression->base.source_position, condition_type_orig);
5948 expression_t *true_expression = parse_expression();
5949 rem_anchor_token(':');
5951 expression_t *false_expression = parse_sub_expression(precedence);
5953 type_t *const orig_true_type = true_expression->base.type;
5954 type_t *const orig_false_type = false_expression->base.type;
5955 type_t *const true_type = skip_typeref(orig_true_type);
5956 type_t *const false_type = skip_typeref(orig_false_type);
5959 type_t *result_type;
5960 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5961 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5962 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5963 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5964 warningf(&expression->base.source_position,
5965 "ISO C forbids conditional expression with only one void side");
5967 result_type = type_void;
5968 } else if (is_type_arithmetic(true_type)
5969 && is_type_arithmetic(false_type)) {
5970 result_type = semantic_arithmetic(true_type, false_type);
5972 true_expression = create_implicit_cast(true_expression, result_type);
5973 false_expression = create_implicit_cast(false_expression, result_type);
5975 conditional->true_expression = true_expression;
5976 conditional->false_expression = false_expression;
5977 conditional->base.type = result_type;
5978 } else if (same_compound_type(true_type, false_type)) {
5979 /* just take 1 of the 2 types */
5980 result_type = true_type;
5981 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5982 type_t *pointer_type;
5984 expression_t *other_expression;
5985 if (is_type_pointer(true_type)) {
5986 pointer_type = true_type;
5987 other_type = false_type;
5988 other_expression = false_expression;
5990 pointer_type = false_type;
5991 other_type = true_type;
5992 other_expression = true_expression;
5995 if(is_type_pointer(other_type)) {
5996 if(!pointers_compatible(true_type, false_type)) {
5997 warningf(&expression->base.source_position,
5998 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
6000 result_type = true_type;
6001 } else if(is_null_pointer_constant(other_expression)) {
6002 result_type = pointer_type;
6003 } else if(is_type_integer(other_type)) {
6004 warningf(&expression->base.source_position,
6005 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6006 result_type = pointer_type;
6008 type_error_incompatible("while parsing conditional",
6009 &expression->base.source_position, true_type, false_type);
6010 result_type = type_error_type;
6013 /* TODO: one pointer to void*, other some pointer */
6015 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6016 type_error_incompatible("while parsing conditional",
6017 &expression->base.source_position, true_type,
6020 result_type = type_error_type;
6023 conditional->true_expression
6024 = create_implicit_cast(true_expression, result_type);
6025 conditional->false_expression
6026 = create_implicit_cast(false_expression, result_type);
6027 conditional->base.type = result_type;
6030 return create_invalid_expression();
6034 * Parse an extension expression.
6036 static expression_t *parse_extension(unsigned precedence)
6038 eat(T___extension__);
6040 /* TODO enable extensions */
6041 expression_t *expression = parse_sub_expression(precedence);
6042 /* TODO disable extensions */
6047 * Parse a __builtin_classify_type() expression.
6049 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6051 eat(T___builtin_classify_type);
6053 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6054 result->base.type = type_int;
6057 add_anchor_token(')');
6058 expression_t *expression = parse_sub_expression(precedence);
6059 rem_anchor_token(')');
6061 result->classify_type.type_expression = expression;
6065 return create_invalid_expression();
6068 static void check_pointer_arithmetic(const source_position_t *source_position,
6069 type_t *pointer_type,
6070 type_t *orig_pointer_type)
6072 type_t *points_to = pointer_type->pointer.points_to;
6073 points_to = skip_typeref(points_to);
6075 if (is_type_incomplete(points_to) &&
6077 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6078 errorf(source_position,
6079 "arithmetic with pointer to incomplete type '%T' not allowed",
6081 } else if (is_type_function(points_to)) {
6082 errorf(source_position,
6083 "arithmetic with pointer to function type '%T' not allowed",
6088 static void semantic_incdec(unary_expression_t *expression)
6090 type_t *const orig_type = expression->value->base.type;
6091 type_t *const type = skip_typeref(orig_type);
6092 if (is_type_pointer(type)) {
6093 check_pointer_arithmetic(&expression->base.source_position,
6095 } else if (!is_type_real(type) && is_type_valid(type)) {
6096 /* TODO: improve error message */
6097 errorf(HERE, "operation needs an arithmetic or pointer type");
6099 expression->base.type = orig_type;
6102 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6104 type_t *const orig_type = expression->value->base.type;
6105 type_t *const type = skip_typeref(orig_type);
6106 if(!is_type_arithmetic(type)) {
6107 if (is_type_valid(type)) {
6108 /* TODO: improve error message */
6109 errorf(HERE, "operation needs an arithmetic type");
6114 expression->base.type = orig_type;
6117 static void semantic_unexpr_scalar(unary_expression_t *expression)
6119 type_t *const orig_type = expression->value->base.type;
6120 type_t *const type = skip_typeref(orig_type);
6121 if (!is_type_scalar(type)) {
6122 if (is_type_valid(type)) {
6123 errorf(HERE, "operand of ! must be of scalar type");
6128 expression->base.type = orig_type;
6131 static void semantic_unexpr_integer(unary_expression_t *expression)
6133 type_t *const orig_type = expression->value->base.type;
6134 type_t *const type = skip_typeref(orig_type);
6135 if (!is_type_integer(type)) {
6136 if (is_type_valid(type)) {
6137 errorf(HERE, "operand of ~ must be of integer type");
6142 expression->base.type = orig_type;
6145 static void semantic_dereference(unary_expression_t *expression)
6147 type_t *const orig_type = expression->value->base.type;
6148 type_t *const type = skip_typeref(orig_type);
6149 if(!is_type_pointer(type)) {
6150 if (is_type_valid(type)) {
6151 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6156 type_t *result_type = type->pointer.points_to;
6157 result_type = automatic_type_conversion(result_type);
6158 expression->base.type = result_type;
6162 * Check the semantic of the address taken expression.
6164 static void semantic_take_addr(unary_expression_t *expression)
6166 expression_t *value = expression->value;
6167 value->base.type = revert_automatic_type_conversion(value);
6169 type_t *orig_type = value->base.type;
6170 if(!is_type_valid(orig_type))
6173 if(value->kind == EXPR_REFERENCE) {
6174 declaration_t *const declaration = value->reference.declaration;
6175 if(declaration != NULL) {
6176 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6177 errorf(&expression->base.source_position,
6178 "address of register variable '%Y' requested",
6179 declaration->symbol);
6181 declaration->address_taken = 1;
6185 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6188 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6189 static expression_t *parse_##unexpression_type(unsigned precedence) \
6193 expression_t *unary_expression \
6194 = allocate_expression_zero(unexpression_type); \
6195 unary_expression->base.source_position = *HERE; \
6196 unary_expression->unary.value = parse_sub_expression(precedence); \
6198 sfunc(&unary_expression->unary); \
6200 return unary_expression; \
6203 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6204 semantic_unexpr_arithmetic)
6205 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6206 semantic_unexpr_arithmetic)
6207 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6208 semantic_unexpr_scalar)
6209 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6210 semantic_dereference)
6211 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6213 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6214 semantic_unexpr_integer)
6215 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6217 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6220 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6222 static expression_t *parse_##unexpression_type(unsigned precedence, \
6223 expression_t *left) \
6225 (void) precedence; \
6228 expression_t *unary_expression \
6229 = allocate_expression_zero(unexpression_type); \
6230 unary_expression->unary.value = left; \
6232 sfunc(&unary_expression->unary); \
6234 return unary_expression; \
6237 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6238 EXPR_UNARY_POSTFIX_INCREMENT,
6240 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6241 EXPR_UNARY_POSTFIX_DECREMENT,
6244 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6246 /* TODO: handle complex + imaginary types */
6248 /* § 6.3.1.8 Usual arithmetic conversions */
6249 if(type_left == type_long_double || type_right == type_long_double) {
6250 return type_long_double;
6251 } else if(type_left == type_double || type_right == type_double) {
6253 } else if(type_left == type_float || type_right == type_float) {
6257 type_right = promote_integer(type_right);
6258 type_left = promote_integer(type_left);
6260 if(type_left == type_right)
6263 bool signed_left = is_type_signed(type_left);
6264 bool signed_right = is_type_signed(type_right);
6265 int rank_left = get_rank(type_left);
6266 int rank_right = get_rank(type_right);
6267 if(rank_left < rank_right) {
6268 if(signed_left == signed_right || !signed_right) {
6274 if(signed_left == signed_right || !signed_left) {
6283 * Check the semantic restrictions for a binary expression.
6285 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6287 expression_t *const left = expression->left;
6288 expression_t *const right = expression->right;
6289 type_t *const orig_type_left = left->base.type;
6290 type_t *const orig_type_right = right->base.type;
6291 type_t *const type_left = skip_typeref(orig_type_left);
6292 type_t *const type_right = skip_typeref(orig_type_right);
6294 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6295 /* TODO: improve error message */
6296 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6297 errorf(HERE, "operation needs arithmetic types");
6302 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6303 expression->left = create_implicit_cast(left, arithmetic_type);
6304 expression->right = create_implicit_cast(right, arithmetic_type);
6305 expression->base.type = arithmetic_type;
6308 static void semantic_shift_op(binary_expression_t *expression)
6310 expression_t *const left = expression->left;
6311 expression_t *const right = expression->right;
6312 type_t *const orig_type_left = left->base.type;
6313 type_t *const orig_type_right = right->base.type;
6314 type_t * type_left = skip_typeref(orig_type_left);
6315 type_t * type_right = skip_typeref(orig_type_right);
6317 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6318 /* TODO: improve error message */
6319 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6320 errorf(HERE, "operation needs integer types");
6325 type_left = promote_integer(type_left);
6326 type_right = promote_integer(type_right);
6328 expression->left = create_implicit_cast(left, type_left);
6329 expression->right = create_implicit_cast(right, type_right);
6330 expression->base.type = type_left;
6333 static void semantic_add(binary_expression_t *expression)
6335 expression_t *const left = expression->left;
6336 expression_t *const right = expression->right;
6337 type_t *const orig_type_left = left->base.type;
6338 type_t *const orig_type_right = right->base.type;
6339 type_t *const type_left = skip_typeref(orig_type_left);
6340 type_t *const type_right = skip_typeref(orig_type_right);
6343 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6344 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6345 expression->left = create_implicit_cast(left, arithmetic_type);
6346 expression->right = create_implicit_cast(right, arithmetic_type);
6347 expression->base.type = arithmetic_type;
6349 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6350 check_pointer_arithmetic(&expression->base.source_position,
6351 type_left, orig_type_left);
6352 expression->base.type = type_left;
6353 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6354 check_pointer_arithmetic(&expression->base.source_position,
6355 type_right, orig_type_right);
6356 expression->base.type = type_right;
6357 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6358 errorf(&expression->base.source_position,
6359 "invalid operands to binary + ('%T', '%T')",
6360 orig_type_left, orig_type_right);
6364 static void semantic_sub(binary_expression_t *expression)
6366 expression_t *const left = expression->left;
6367 expression_t *const right = expression->right;
6368 type_t *const orig_type_left = left->base.type;
6369 type_t *const orig_type_right = right->base.type;
6370 type_t *const type_left = skip_typeref(orig_type_left);
6371 type_t *const type_right = skip_typeref(orig_type_right);
6374 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6375 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6376 expression->left = create_implicit_cast(left, arithmetic_type);
6377 expression->right = create_implicit_cast(right, arithmetic_type);
6378 expression->base.type = arithmetic_type;
6380 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6381 check_pointer_arithmetic(&expression->base.source_position,
6382 type_left, orig_type_left);
6383 expression->base.type = type_left;
6384 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6385 if(!pointers_compatible(type_left, type_right)) {
6387 "pointers to incompatible objects to binary '-' ('%T', '%T')",
6388 orig_type_left, orig_type_right);
6390 expression->base.type = type_ptrdiff_t;
6392 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6393 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6394 orig_type_left, orig_type_right);
6399 * Check the semantics of comparison expressions.
6401 * @param expression The expression to check.
6403 static void semantic_comparison(binary_expression_t *expression)
6405 expression_t *left = expression->left;
6406 expression_t *right = expression->right;
6407 type_t *orig_type_left = left->base.type;
6408 type_t *orig_type_right = right->base.type;
6410 type_t *type_left = skip_typeref(orig_type_left);
6411 type_t *type_right = skip_typeref(orig_type_right);
6413 /* TODO non-arithmetic types */
6414 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6415 /* test for signed vs unsigned compares */
6416 if (warning.sign_compare &&
6417 (expression->base.kind != EXPR_BINARY_EQUAL &&
6418 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6419 (is_type_signed(type_left) != is_type_signed(type_right))) {
6421 /* check if 1 of the operands is a constant, in this case we just
6422 * check wether we can safely represent the resulting constant in
6423 * the type of the other operand. */
6424 expression_t *const_expr = NULL;
6425 expression_t *other_expr = NULL;
6427 if(is_constant_expression(left)) {
6430 } else if(is_constant_expression(right)) {
6435 if(const_expr != NULL) {
6436 type_t *other_type = skip_typeref(other_expr->base.type);
6437 long val = fold_constant(const_expr);
6438 /* TODO: check if val can be represented by other_type */
6442 warningf(&expression->base.source_position,
6443 "comparison between signed and unsigned");
6445 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6446 expression->left = create_implicit_cast(left, arithmetic_type);
6447 expression->right = create_implicit_cast(right, arithmetic_type);
6448 expression->base.type = arithmetic_type;
6449 if (warning.float_equal &&
6450 (expression->base.kind == EXPR_BINARY_EQUAL ||
6451 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6452 is_type_float(arithmetic_type)) {
6453 warningf(&expression->base.source_position,
6454 "comparing floating point with == or != is unsafe");
6456 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6457 /* TODO check compatibility */
6458 } else if (is_type_pointer(type_left)) {
6459 expression->right = create_implicit_cast(right, type_left);
6460 } else if (is_type_pointer(type_right)) {
6461 expression->left = create_implicit_cast(left, type_right);
6462 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6463 type_error_incompatible("invalid operands in comparison",
6464 &expression->base.source_position,
6465 type_left, type_right);
6467 expression->base.type = type_int;
6471 * Checks if a compound type has constant fields.
6473 static bool has_const_fields(const compound_type_t *type)
6475 const scope_t *scope = &type->declaration->scope;
6476 const declaration_t *declaration = scope->declarations;
6478 for (; declaration != NULL; declaration = declaration->next) {
6479 if (declaration->namespc != NAMESPACE_NORMAL)
6482 const type_t *decl_type = skip_typeref(declaration->type);
6483 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6490 static bool is_lvalue(const expression_t *expression)
6492 switch (expression->kind) {
6493 case EXPR_REFERENCE:
6494 case EXPR_ARRAY_ACCESS:
6496 case EXPR_UNARY_DEREFERENCE:
6504 static bool is_valid_assignment_lhs(expression_t const* const left)
6506 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6507 type_t *const type_left = skip_typeref(orig_type_left);
6509 if (!is_lvalue(left)) {
6510 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6515 if (is_type_array(type_left)) {
6516 errorf(HERE, "cannot assign to arrays ('%E')", left);
6519 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6520 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6524 if (is_type_incomplete(type_left)) {
6525 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6526 left, orig_type_left);
6529 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6530 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6531 left, orig_type_left);
6538 static void semantic_arithmetic_assign(binary_expression_t *expression)
6540 expression_t *left = expression->left;
6541 expression_t *right = expression->right;
6542 type_t *orig_type_left = left->base.type;
6543 type_t *orig_type_right = right->base.type;
6545 if (!is_valid_assignment_lhs(left))
6548 type_t *type_left = skip_typeref(orig_type_left);
6549 type_t *type_right = skip_typeref(orig_type_right);
6551 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6552 /* TODO: improve error message */
6553 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6554 errorf(HERE, "operation needs arithmetic types");
6559 /* combined instructions are tricky. We can't create an implicit cast on
6560 * the left side, because we need the uncasted form for the store.
6561 * The ast2firm pass has to know that left_type must be right_type
6562 * for the arithmetic operation and create a cast by itself */
6563 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6564 expression->right = create_implicit_cast(right, arithmetic_type);
6565 expression->base.type = type_left;
6568 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6570 expression_t *const left = expression->left;
6571 expression_t *const right = expression->right;
6572 type_t *const orig_type_left = left->base.type;
6573 type_t *const orig_type_right = right->base.type;
6574 type_t *const type_left = skip_typeref(orig_type_left);
6575 type_t *const type_right = skip_typeref(orig_type_right);
6577 if (!is_valid_assignment_lhs(left))
6580 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6581 /* combined instructions are tricky. We can't create an implicit cast on
6582 * the left side, because we need the uncasted form for the store.
6583 * The ast2firm pass has to know that left_type must be right_type
6584 * for the arithmetic operation and create a cast by itself */
6585 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6586 expression->right = create_implicit_cast(right, arithmetic_type);
6587 expression->base.type = type_left;
6588 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6589 check_pointer_arithmetic(&expression->base.source_position,
6590 type_left, orig_type_left);
6591 expression->base.type = type_left;
6592 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6593 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6598 * Check the semantic restrictions of a logical expression.
6600 static void semantic_logical_op(binary_expression_t *expression)
6602 expression_t *const left = expression->left;
6603 expression_t *const right = expression->right;
6604 type_t *const orig_type_left = left->base.type;
6605 type_t *const orig_type_right = right->base.type;
6606 type_t *const type_left = skip_typeref(orig_type_left);
6607 type_t *const type_right = skip_typeref(orig_type_right);
6609 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6610 /* TODO: improve error message */
6611 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6612 errorf(HERE, "operation needs scalar types");
6617 expression->base.type = type_int;
6621 * Check the semantic restrictions of a binary assign expression.
6623 static void semantic_binexpr_assign(binary_expression_t *expression)
6625 expression_t *left = expression->left;
6626 type_t *orig_type_left = left->base.type;
6628 type_t *type_left = revert_automatic_type_conversion(left);
6629 type_left = skip_typeref(orig_type_left);
6631 if (!is_valid_assignment_lhs(left))
6634 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6635 "assignment", &left->base.source_position);
6636 if (res_type == NULL) {
6637 errorf(&expression->base.source_position,
6638 "cannot assign to '%T' from '%T'",
6639 orig_type_left, expression->right->base.type);
6641 expression->right = create_implicit_cast(expression->right, res_type);
6644 expression->base.type = orig_type_left;
6648 * Determine if the outermost operation (or parts thereof) of the given
6649 * expression has no effect in order to generate a warning about this fact.
6650 * Therefore in some cases this only examines some of the operands of the
6651 * expression (see comments in the function and examples below).
6653 * f() + 23; // warning, because + has no effect
6654 * x || f(); // no warning, because x controls execution of f()
6655 * x ? y : f(); // warning, because y has no effect
6656 * (void)x; // no warning to be able to suppress the warning
6657 * This function can NOT be used for an "expression has definitely no effect"-
6659 static bool expression_has_effect(const expression_t *const expr)
6661 switch (expr->kind) {
6662 case EXPR_UNKNOWN: break;
6663 case EXPR_INVALID: return true; /* do NOT warn */
6664 case EXPR_REFERENCE: return false;
6665 /* suppress the warning for microsoft __noop operations */
6666 case EXPR_CONST: return expr->conste.is_ms_noop;
6667 case EXPR_CHARACTER_CONSTANT: return false;
6668 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6669 case EXPR_STRING_LITERAL: return false;
6670 case EXPR_WIDE_STRING_LITERAL: return false;
6673 const call_expression_t *const call = &expr->call;
6674 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6677 switch (call->function->builtin_symbol.symbol->ID) {
6678 case T___builtin_va_end: return true;
6679 default: return false;
6683 /* Generate the warning if either the left or right hand side of a
6684 * conditional expression has no effect */
6685 case EXPR_CONDITIONAL: {
6686 const conditional_expression_t *const cond = &expr->conditional;
6688 expression_has_effect(cond->true_expression) &&
6689 expression_has_effect(cond->false_expression);
6692 case EXPR_SELECT: return false;
6693 case EXPR_ARRAY_ACCESS: return false;
6694 case EXPR_SIZEOF: return false;
6695 case EXPR_CLASSIFY_TYPE: return false;
6696 case EXPR_ALIGNOF: return false;
6698 case EXPR_FUNCNAME: return false;
6699 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6700 case EXPR_BUILTIN_CONSTANT_P: return false;
6701 case EXPR_BUILTIN_PREFETCH: return true;
6702 case EXPR_OFFSETOF: return false;
6703 case EXPR_VA_START: return true;
6704 case EXPR_VA_ARG: return true;
6705 case EXPR_STATEMENT: return true; // TODO
6706 case EXPR_COMPOUND_LITERAL: return false;
6708 case EXPR_UNARY_NEGATE: return false;
6709 case EXPR_UNARY_PLUS: return false;
6710 case EXPR_UNARY_BITWISE_NEGATE: return false;
6711 case EXPR_UNARY_NOT: return false;
6712 case EXPR_UNARY_DEREFERENCE: return false;
6713 case EXPR_UNARY_TAKE_ADDRESS: return false;
6714 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6715 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6716 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6717 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6719 /* Treat void casts as if they have an effect in order to being able to
6720 * suppress the warning */
6721 case EXPR_UNARY_CAST: {
6722 type_t *const type = skip_typeref(expr->base.type);
6723 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6726 case EXPR_UNARY_CAST_IMPLICIT: return true;
6727 case EXPR_UNARY_ASSUME: return true;
6729 case EXPR_BINARY_ADD: return false;
6730 case EXPR_BINARY_SUB: return false;
6731 case EXPR_BINARY_MUL: return false;
6732 case EXPR_BINARY_DIV: return false;
6733 case EXPR_BINARY_MOD: return false;
6734 case EXPR_BINARY_EQUAL: return false;
6735 case EXPR_BINARY_NOTEQUAL: return false;
6736 case EXPR_BINARY_LESS: return false;
6737 case EXPR_BINARY_LESSEQUAL: return false;
6738 case EXPR_BINARY_GREATER: return false;
6739 case EXPR_BINARY_GREATEREQUAL: return false;
6740 case EXPR_BINARY_BITWISE_AND: return false;
6741 case EXPR_BINARY_BITWISE_OR: return false;
6742 case EXPR_BINARY_BITWISE_XOR: return false;
6743 case EXPR_BINARY_SHIFTLEFT: return false;
6744 case EXPR_BINARY_SHIFTRIGHT: return false;
6745 case EXPR_BINARY_ASSIGN: return true;
6746 case EXPR_BINARY_MUL_ASSIGN: return true;
6747 case EXPR_BINARY_DIV_ASSIGN: return true;
6748 case EXPR_BINARY_MOD_ASSIGN: return true;
6749 case EXPR_BINARY_ADD_ASSIGN: return true;
6750 case EXPR_BINARY_SUB_ASSIGN: return true;
6751 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6752 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6753 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6754 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6755 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6757 /* Only examine the right hand side of && and ||, because the left hand
6758 * side already has the effect of controlling the execution of the right
6760 case EXPR_BINARY_LOGICAL_AND:
6761 case EXPR_BINARY_LOGICAL_OR:
6762 /* Only examine the right hand side of a comma expression, because the left
6763 * hand side has a separate warning */
6764 case EXPR_BINARY_COMMA:
6765 return expression_has_effect(expr->binary.right);
6767 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6768 case EXPR_BINARY_ISGREATER: return false;
6769 case EXPR_BINARY_ISGREATEREQUAL: return false;
6770 case EXPR_BINARY_ISLESS: return false;
6771 case EXPR_BINARY_ISLESSEQUAL: return false;
6772 case EXPR_BINARY_ISLESSGREATER: return false;
6773 case EXPR_BINARY_ISUNORDERED: return false;
6776 internal_errorf(HERE, "unexpected expression");
6779 static void semantic_comma(binary_expression_t *expression)
6781 if (warning.unused_value) {
6782 const expression_t *const left = expression->left;
6783 if (!expression_has_effect(left)) {
6784 warningf(&left->base.source_position,
6785 "left-hand operand of comma expression has no effect");
6788 expression->base.type = expression->right->base.type;
6791 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6792 static expression_t *parse_##binexpression_type(unsigned precedence, \
6793 expression_t *left) \
6796 source_position_t pos = *HERE; \
6798 expression_t *right = parse_sub_expression(precedence + lr); \
6800 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6801 binexpr->base.source_position = pos; \
6802 binexpr->binary.left = left; \
6803 binexpr->binary.right = right; \
6804 sfunc(&binexpr->binary); \
6809 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6810 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6811 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6812 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6813 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6814 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6815 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6816 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6817 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6819 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6820 semantic_comparison, 1)
6821 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6822 semantic_comparison, 1)
6823 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6824 semantic_comparison, 1)
6825 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6826 semantic_comparison, 1)
6828 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6829 semantic_binexpr_arithmetic, 1)
6830 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6831 semantic_binexpr_arithmetic, 1)
6832 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6833 semantic_binexpr_arithmetic, 1)
6834 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6835 semantic_logical_op, 1)
6836 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6837 semantic_logical_op, 1)
6838 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6839 semantic_shift_op, 1)
6840 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6841 semantic_shift_op, 1)
6842 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6843 semantic_arithmetic_addsubb_assign, 0)
6844 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6845 semantic_arithmetic_addsubb_assign, 0)
6846 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6847 semantic_arithmetic_assign, 0)
6848 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6849 semantic_arithmetic_assign, 0)
6850 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6851 semantic_arithmetic_assign, 0)
6852 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6853 semantic_arithmetic_assign, 0)
6854 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6855 semantic_arithmetic_assign, 0)
6856 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6857 semantic_arithmetic_assign, 0)
6858 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6859 semantic_arithmetic_assign, 0)
6860 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6861 semantic_arithmetic_assign, 0)
6863 static expression_t *parse_sub_expression(unsigned precedence)
6865 if(token.type < 0) {
6866 return expected_expression_error();
6869 expression_parser_function_t *parser
6870 = &expression_parsers[token.type];
6871 source_position_t source_position = token.source_position;
6874 if(parser->parser != NULL) {
6875 left = parser->parser(parser->precedence);
6877 left = parse_primary_expression();
6879 assert(left != NULL);
6880 left->base.source_position = source_position;
6883 if(token.type < 0) {
6884 return expected_expression_error();
6887 parser = &expression_parsers[token.type];
6888 if(parser->infix_parser == NULL)
6890 if(parser->infix_precedence < precedence)
6893 left = parser->infix_parser(parser->infix_precedence, left);
6895 assert(left != NULL);
6896 assert(left->kind != EXPR_UNKNOWN);
6897 left->base.source_position = source_position;
6904 * Parse an expression.
6906 static expression_t *parse_expression(void)
6908 return parse_sub_expression(1);
6912 * Register a parser for a prefix-like operator with given precedence.
6914 * @param parser the parser function
6915 * @param token_type the token type of the prefix token
6916 * @param precedence the precedence of the operator
6918 static void register_expression_parser(parse_expression_function parser,
6919 int token_type, unsigned precedence)
6921 expression_parser_function_t *entry = &expression_parsers[token_type];
6923 if(entry->parser != NULL) {
6924 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6925 panic("trying to register multiple expression parsers for a token");
6927 entry->parser = parser;
6928 entry->precedence = precedence;
6932 * Register a parser for an infix operator with given precedence.
6934 * @param parser the parser function
6935 * @param token_type the token type of the infix operator
6936 * @param precedence the precedence of the operator
6938 static void register_infix_parser(parse_expression_infix_function parser,
6939 int token_type, unsigned precedence)
6941 expression_parser_function_t *entry = &expression_parsers[token_type];
6943 if(entry->infix_parser != NULL) {
6944 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6945 panic("trying to register multiple infix expression parsers for a "
6948 entry->infix_parser = parser;
6949 entry->infix_precedence = precedence;
6953 * Initialize the expression parsers.
6955 static void init_expression_parsers(void)
6957 memset(&expression_parsers, 0, sizeof(expression_parsers));
6959 register_infix_parser(parse_array_expression, '[', 30);
6960 register_infix_parser(parse_call_expression, '(', 30);
6961 register_infix_parser(parse_select_expression, '.', 30);
6962 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6963 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6965 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6968 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
6969 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
6970 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
6971 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
6972 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
6973 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
6974 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
6975 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6976 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6977 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6978 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6979 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6980 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6981 T_EXCLAMATIONMARKEQUAL, 13);
6982 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6983 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6984 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6985 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6986 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6987 register_infix_parser(parse_conditional_expression, '?', 7);
6988 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6989 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6990 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6991 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6992 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6993 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6994 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6995 T_LESSLESSEQUAL, 2);
6996 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6997 T_GREATERGREATEREQUAL, 2);
6998 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7000 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7002 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7005 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7007 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7008 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7009 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7010 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7011 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7012 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7013 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7015 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7017 register_expression_parser(parse_sizeof, T_sizeof, 25);
7018 register_expression_parser(parse_alignof, T___alignof__, 25);
7019 register_expression_parser(parse_extension, T___extension__, 25);
7020 register_expression_parser(parse_builtin_classify_type,
7021 T___builtin_classify_type, 25);
7025 * Parse a asm statement arguments specification.
7027 static asm_argument_t *parse_asm_arguments(bool is_out)
7029 asm_argument_t *result = NULL;
7030 asm_argument_t *last = NULL;
7032 while(token.type == T_STRING_LITERAL || token.type == '[') {
7033 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7034 memset(argument, 0, sizeof(argument[0]));
7036 if(token.type == '[') {
7038 if(token.type != T_IDENTIFIER) {
7039 parse_error_expected("while parsing asm argument",
7040 T_IDENTIFIER, NULL);
7043 argument->symbol = token.v.symbol;
7048 argument->constraints = parse_string_literals();
7050 argument->expression = parse_expression();
7051 if (is_out && !is_lvalue(argument->expression)) {
7052 errorf(&argument->expression->base.source_position,
7053 "asm output argument is not an lvalue");
7058 last->next = argument;
7064 if(token.type != ',')
7075 * Parse a asm statement clobber specification.
7077 static asm_clobber_t *parse_asm_clobbers(void)
7079 asm_clobber_t *result = NULL;
7080 asm_clobber_t *last = NULL;
7082 while(token.type == T_STRING_LITERAL) {
7083 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7084 clobber->clobber = parse_string_literals();
7087 last->next = clobber;
7093 if(token.type != ',')
7102 * Parse an asm statement.
7104 static statement_t *parse_asm_statement(void)
7108 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7109 statement->base.source_position = token.source_position;
7111 asm_statement_t *asm_statement = &statement->asms;
7113 if(token.type == T_volatile) {
7115 asm_statement->is_volatile = true;
7119 add_anchor_token(')');
7120 add_anchor_token(':');
7121 asm_statement->asm_text = parse_string_literals();
7123 if(token.type != ':') {
7124 rem_anchor_token(':');
7129 asm_statement->outputs = parse_asm_arguments(true);
7130 if(token.type != ':') {
7131 rem_anchor_token(':');
7136 asm_statement->inputs = parse_asm_arguments(false);
7137 if(token.type != ':') {
7138 rem_anchor_token(':');
7141 rem_anchor_token(':');
7144 asm_statement->clobbers = parse_asm_clobbers();
7147 rem_anchor_token(')');
7152 return create_invalid_statement();
7156 * Parse a case statement.
7158 static statement_t *parse_case_statement(void)
7162 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7164 statement->base.source_position = token.source_position;
7165 statement->case_label.expression = parse_expression();
7167 if (c_mode & _GNUC) {
7168 if (token.type == T_DOTDOTDOT) {
7170 statement->case_label.end_range = parse_expression();
7176 if (! is_constant_expression(statement->case_label.expression)) {
7177 errorf(&statement->base.source_position,
7178 "case label does not reduce to an integer constant");
7180 /* TODO: check if the case label is already known */
7181 if (current_switch != NULL) {
7182 /* link all cases into the switch statement */
7183 if (current_switch->last_case == NULL) {
7184 current_switch->first_case =
7185 current_switch->last_case = &statement->case_label;
7187 current_switch->last_case->next = &statement->case_label;
7190 errorf(&statement->base.source_position,
7191 "case label not within a switch statement");
7194 statement->case_label.statement = parse_statement();
7198 return create_invalid_statement();
7202 * Finds an existing default label of a switch statement.
7204 static case_label_statement_t *
7205 find_default_label(const switch_statement_t *statement)
7207 case_label_statement_t *label = statement->first_case;
7208 for ( ; label != NULL; label = label->next) {
7209 if (label->expression == NULL)
7216 * Parse a default statement.
7218 static statement_t *parse_default_statement(void)
7222 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7224 statement->base.source_position = token.source_position;
7227 if (current_switch != NULL) {
7228 const case_label_statement_t *def_label = find_default_label(current_switch);
7229 if (def_label != NULL) {
7230 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7231 &def_label->base.source_position);
7233 /* link all cases into the switch statement */
7234 if (current_switch->last_case == NULL) {
7235 current_switch->first_case =
7236 current_switch->last_case = &statement->case_label;
7238 current_switch->last_case->next = &statement->case_label;
7242 errorf(&statement->base.source_position,
7243 "'default' label not within a switch statement");
7245 statement->case_label.statement = parse_statement();
7249 return create_invalid_statement();
7253 * Return the declaration for a given label symbol or create a new one.
7255 static declaration_t *get_label(symbol_t *symbol)
7257 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7258 assert(current_function != NULL);
7259 /* if we found a label in the same function, then we already created the
7261 if(candidate != NULL
7262 && candidate->parent_scope == ¤t_function->scope) {
7266 /* otherwise we need to create a new one */
7267 declaration_t *const declaration = allocate_declaration_zero();
7268 declaration->namespc = NAMESPACE_LABEL;
7269 declaration->symbol = symbol;
7271 label_push(declaration);
7277 * Parse a label statement.
7279 static statement_t *parse_label_statement(void)
7281 assert(token.type == T_IDENTIFIER);
7282 symbol_t *symbol = token.v.symbol;
7285 declaration_t *label = get_label(symbol);
7287 /* if source position is already set then the label is defined twice,
7288 * otherwise it was just mentioned in a goto so far */
7289 if(label->source_position.input_name != NULL) {
7290 errorf(HERE, "duplicate label '%Y' (declared %P)",
7291 symbol, &label->source_position);
7293 label->source_position = token.source_position;
7296 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7298 statement->base.source_position = token.source_position;
7299 statement->label.label = label;
7303 if(token.type == '}') {
7304 /* TODO only warn? */
7306 warningf(HERE, "label at end of compound statement");
7307 statement->label.statement = create_empty_statement();
7309 errorf(HERE, "label at end of compound statement");
7310 statement->label.statement = create_invalid_statement();
7314 if (token.type == ';') {
7315 /* eat an empty statement here, to avoid the warning about an empty
7316 * after a label. label:; is commonly used to have a label before
7318 statement->label.statement = create_empty_statement();
7321 statement->label.statement = parse_statement();
7325 /* remember the labels's in a list for later checking */
7326 if (label_last == NULL) {
7327 label_first = &statement->label;
7329 label_last->next = &statement->label;
7331 label_last = &statement->label;
7337 * Parse an if statement.
7339 static statement_t *parse_if(void)
7343 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7344 statement->base.source_position = token.source_position;
7347 add_anchor_token(')');
7348 statement->ifs.condition = parse_expression();
7349 rem_anchor_token(')');
7352 add_anchor_token(T_else);
7353 statement->ifs.true_statement = parse_statement();
7354 rem_anchor_token(T_else);
7356 if(token.type == T_else) {
7358 statement->ifs.false_statement = parse_statement();
7363 return create_invalid_statement();
7367 * Parse a switch statement.
7369 static statement_t *parse_switch(void)
7373 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7374 statement->base.source_position = token.source_position;
7377 expression_t *const expr = parse_expression();
7378 type_t * type = skip_typeref(expr->base.type);
7379 if (is_type_integer(type)) {
7380 type = promote_integer(type);
7381 } else if (is_type_valid(type)) {
7382 errorf(&expr->base.source_position,
7383 "switch quantity is not an integer, but '%T'", type);
7384 type = type_error_type;
7386 statement->switchs.expression = create_implicit_cast(expr, type);
7389 switch_statement_t *rem = current_switch;
7390 current_switch = &statement->switchs;
7391 statement->switchs.body = parse_statement();
7392 current_switch = rem;
7394 if(warning.switch_default &&
7395 find_default_label(&statement->switchs) == NULL) {
7396 warningf(&statement->base.source_position, "switch has no default case");
7401 return create_invalid_statement();
7404 static statement_t *parse_loop_body(statement_t *const loop)
7406 statement_t *const rem = current_loop;
7407 current_loop = loop;
7409 statement_t *const body = parse_statement();
7416 * Parse a while statement.
7418 static statement_t *parse_while(void)
7422 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7423 statement->base.source_position = token.source_position;
7426 add_anchor_token(')');
7427 statement->whiles.condition = parse_expression();
7428 rem_anchor_token(')');
7431 statement->whiles.body = parse_loop_body(statement);
7435 return create_invalid_statement();
7439 * Parse a do statement.
7441 static statement_t *parse_do(void)
7445 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7447 statement->base.source_position = token.source_position;
7449 add_anchor_token(T_while);
7450 statement->do_while.body = parse_loop_body(statement);
7451 rem_anchor_token(T_while);
7455 add_anchor_token(')');
7456 statement->do_while.condition = parse_expression();
7457 rem_anchor_token(')');
7463 return create_invalid_statement();
7467 * Parse a for statement.
7469 static statement_t *parse_for(void)
7473 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7474 statement->base.source_position = token.source_position;
7476 int top = environment_top();
7477 scope_t *last_scope = scope;
7478 set_scope(&statement->fors.scope);
7481 add_anchor_token(')');
7483 if(token.type != ';') {
7484 if(is_declaration_specifier(&token, false)) {
7485 parse_declaration(record_declaration);
7487 add_anchor_token(';');
7488 expression_t *const init = parse_expression();
7489 statement->fors.initialisation = init;
7490 if (warning.unused_value && !expression_has_effect(init)) {
7491 warningf(&init->base.source_position,
7492 "initialisation of 'for'-statement has no effect");
7494 rem_anchor_token(';');
7501 if(token.type != ';') {
7502 add_anchor_token(';');
7503 statement->fors.condition = parse_expression();
7504 rem_anchor_token(';');
7507 if(token.type != ')') {
7508 expression_t *const step = parse_expression();
7509 statement->fors.step = step;
7510 if (warning.unused_value && !expression_has_effect(step)) {
7511 warningf(&step->base.source_position,
7512 "step of 'for'-statement has no effect");
7515 rem_anchor_token(')');
7517 statement->fors.body = parse_loop_body(statement);
7519 assert(scope == &statement->fors.scope);
7520 set_scope(last_scope);
7521 environment_pop_to(top);
7526 rem_anchor_token(')');
7527 assert(scope == &statement->fors.scope);
7528 set_scope(last_scope);
7529 environment_pop_to(top);
7531 return create_invalid_statement();
7535 * Parse a goto statement.
7537 static statement_t *parse_goto(void)
7541 if(token.type != T_IDENTIFIER) {
7542 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7546 symbol_t *symbol = token.v.symbol;
7549 declaration_t *label = get_label(symbol);
7551 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7552 statement->base.source_position = token.source_position;
7554 statement->gotos.label = label;
7556 /* remember the goto's in a list for later checking */
7557 if (goto_last == NULL) {
7558 goto_first = &statement->gotos;
7560 goto_last->next = &statement->gotos;
7562 goto_last = &statement->gotos;
7568 return create_invalid_statement();
7572 * Parse a continue statement.
7574 static statement_t *parse_continue(void)
7576 statement_t *statement;
7577 if (current_loop == NULL) {
7578 errorf(HERE, "continue statement not within loop");
7579 statement = create_invalid_statement();
7581 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7583 statement->base.source_position = token.source_position;
7591 return create_invalid_statement();
7595 * Parse a break statement.
7597 static statement_t *parse_break(void)
7599 statement_t *statement;
7600 if (current_switch == NULL && current_loop == NULL) {
7601 errorf(HERE, "break statement not within loop or switch");
7602 statement = create_invalid_statement();
7604 statement = allocate_statement_zero(STATEMENT_BREAK);
7606 statement->base.source_position = token.source_position;
7614 return create_invalid_statement();
7618 * Parse a __leave statement.
7620 static statement_t *parse_leave(void)
7622 statement_t *statement;
7623 if (current_try == NULL) {
7624 errorf(HERE, "__leave statement not within __try");
7625 statement = create_invalid_statement();
7627 statement = allocate_statement_zero(STATEMENT_LEAVE);
7629 statement->base.source_position = token.source_position;
7637 return create_invalid_statement();
7641 * Check if a given declaration represents a local variable.
7643 static bool is_local_var_declaration(const declaration_t *declaration) {
7644 switch ((storage_class_tag_t) declaration->storage_class) {
7645 case STORAGE_CLASS_AUTO:
7646 case STORAGE_CLASS_REGISTER: {
7647 const type_t *type = skip_typeref(declaration->type);
7648 if(is_type_function(type)) {
7660 * Check if a given declaration represents a variable.
7662 static bool is_var_declaration(const declaration_t *declaration) {
7663 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7666 const type_t *type = skip_typeref(declaration->type);
7667 return !is_type_function(type);
7671 * Check if a given expression represents a local variable.
7673 static bool is_local_variable(const expression_t *expression)
7675 if (expression->base.kind != EXPR_REFERENCE) {
7678 const declaration_t *declaration = expression->reference.declaration;
7679 return is_local_var_declaration(declaration);
7683 * Check if a given expression represents a local variable and
7684 * return its declaration then, else return NULL.
7686 declaration_t *expr_is_variable(const expression_t *expression)
7688 if (expression->base.kind != EXPR_REFERENCE) {
7691 declaration_t *declaration = expression->reference.declaration;
7692 if (is_var_declaration(declaration))
7698 * Parse a return statement.
7700 static statement_t *parse_return(void)
7702 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7703 statement->base.source_position = token.source_position;
7707 expression_t *return_value = NULL;
7708 if(token.type != ';') {
7709 return_value = parse_expression();
7713 const type_t *const func_type = current_function->type;
7714 assert(is_type_function(func_type));
7715 type_t *const return_type = skip_typeref(func_type->function.return_type);
7717 if(return_value != NULL) {
7718 type_t *return_value_type = skip_typeref(return_value->base.type);
7720 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7721 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7722 warningf(&statement->base.source_position,
7723 "'return' with a value, in function returning void");
7724 return_value = NULL;
7726 type_t *const res_type = semantic_assign(return_type,
7727 return_value, "'return'", &statement->base.source_position);
7728 if (res_type == NULL) {
7729 errorf(&statement->base.source_position,
7730 "cannot return something of type '%T' in function returning '%T'",
7731 return_value->base.type, return_type);
7733 return_value = create_implicit_cast(return_value, res_type);
7736 /* check for returning address of a local var */
7737 if (return_value != NULL &&
7738 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7739 const expression_t *expression = return_value->unary.value;
7740 if (is_local_variable(expression)) {
7741 warningf(&statement->base.source_position,
7742 "function returns address of local variable");
7746 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7747 warningf(&statement->base.source_position,
7748 "'return' without value, in function returning non-void");
7751 statement->returns.value = return_value;
7755 return create_invalid_statement();
7759 * Parse a declaration statement.
7761 static statement_t *parse_declaration_statement(void)
7763 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7765 statement->base.source_position = token.source_position;
7767 declaration_t *before = last_declaration;
7768 parse_declaration(record_declaration);
7770 if(before == NULL) {
7771 statement->declaration.declarations_begin = scope->declarations;
7773 statement->declaration.declarations_begin = before->next;
7775 statement->declaration.declarations_end = last_declaration;
7781 * Parse an expression statement, ie. expr ';'.
7783 static statement_t *parse_expression_statement(void)
7785 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7787 statement->base.source_position = token.source_position;
7788 expression_t *const expr = parse_expression();
7789 statement->expression.expression = expr;
7795 return create_invalid_statement();
7799 * Parse a microsoft __try { } __finally { } or
7800 * __try{ } __except() { }
7802 static statement_t *parse_ms_try_statment(void) {
7803 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
7805 statement->base.source_position = token.source_position;
7808 ms_try_statement_t *rem = current_try;
7809 current_try = &statement->ms_try;
7810 statement->ms_try.try_statement = parse_compound_statement(false);
7813 if(token.type == T___except) {
7816 add_anchor_token(')');
7817 expression_t *const expr = parse_expression();
7818 type_t * type = skip_typeref(expr->base.type);
7819 if (is_type_integer(type)) {
7820 type = promote_integer(type);
7821 } else if (is_type_valid(type)) {
7822 errorf(&expr->base.source_position,
7823 "__expect expression is not an integer, but '%T'", type);
7824 type = type_error_type;
7826 statement->ms_try.except_expression = create_implicit_cast(expr, type);
7827 rem_anchor_token(')');
7829 statement->ms_try.final_statement = parse_compound_statement(false);
7830 } else if(token.type == T__finally) {
7832 statement->ms_try.final_statement = parse_compound_statement(false);
7834 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
7835 return create_invalid_statement();
7839 return create_invalid_statement();
7843 * Parse a statement.
7844 * There's also parse_statement() which additionally checks for
7845 * "statement has no effect" warnings
7847 static statement_t *intern_parse_statement(void)
7849 statement_t *statement = NULL;
7851 /* declaration or statement */
7852 add_anchor_token(';');
7853 switch(token.type) {
7855 statement = parse_asm_statement();
7859 statement = parse_case_statement();
7863 statement = parse_default_statement();
7867 statement = parse_compound_statement(false);
7871 statement = parse_if();
7875 statement = parse_switch();
7879 statement = parse_while();
7883 statement = parse_do();
7887 statement = parse_for();
7891 statement = parse_goto();
7895 statement = parse_continue();
7899 statement = parse_break();
7903 statement = parse_leave();
7907 statement = parse_return();
7911 if(warning.empty_statement) {
7912 warningf(HERE, "statement is empty");
7914 statement = create_empty_statement();
7919 if(look_ahead(1)->type == ':') {
7920 statement = parse_label_statement();
7924 if(is_typedef_symbol(token.v.symbol)) {
7925 statement = parse_declaration_statement();
7929 statement = parse_expression_statement();
7932 case T___extension__:
7933 /* this can be a prefix to a declaration or an expression statement */
7934 /* we simply eat it now and parse the rest with tail recursion */
7937 } while(token.type == T___extension__);
7938 statement = parse_statement();
7942 statement = parse_declaration_statement();
7946 statement = parse_ms_try_statment();
7950 statement = parse_expression_statement();
7953 rem_anchor_token(';');
7955 assert(statement != NULL
7956 && statement->base.source_position.input_name != NULL);
7962 * parse a statement and emits "statement has no effect" warning if needed
7963 * (This is really a wrapper around intern_parse_statement with check for 1
7964 * single warning. It is needed, because for statement expressions we have
7965 * to avoid the warning on the last statement)
7967 static statement_t *parse_statement(void)
7969 statement_t *statement = intern_parse_statement();
7971 if(statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
7972 expression_t *expression = statement->expression.expression;
7973 if(!expression_has_effect(expression)) {
7974 warningf(&expression->base.source_position,
7975 "statement has no effect");
7983 * Parse a compound statement.
7985 static statement_t *parse_compound_statement(bool inside_expression_statement)
7987 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7989 statement->base.source_position = token.source_position;
7992 add_anchor_token('}');
7994 int top = environment_top();
7995 scope_t *last_scope = scope;
7996 set_scope(&statement->compound.scope);
7998 statement_t *last_statement = NULL;
8000 while(token.type != '}' && token.type != T_EOF) {
8001 statement_t *sub_statement = intern_parse_statement();
8002 if(is_invalid_statement(sub_statement)) {
8003 /* an error occurred. if we are at an anchor, return */
8009 if(last_statement != NULL) {
8010 last_statement->base.next = sub_statement;
8012 statement->compound.statements = sub_statement;
8015 while(sub_statement->base.next != NULL)
8016 sub_statement = sub_statement->base.next;
8018 last_statement = sub_statement;
8021 if(token.type == '}') {
8024 errorf(&statement->base.source_position,
8025 "end of file while looking for closing '}'");
8028 /* look over all statements again to produce no effect warnings */
8029 if(warning.unused_value) {
8030 statement_t *sub_statement = statement->compound.statements;
8031 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8032 if(sub_statement->kind != STATEMENT_EXPRESSION)
8034 /* don't emit a warning for the last expression in an expression
8035 * statement as it has always an effect */
8036 if(inside_expression_statement && sub_statement->base.next == NULL)
8039 expression_t *expression = sub_statement->expression.expression;
8040 if(!expression_has_effect(expression)) {
8041 warningf(&expression->base.source_position,
8042 "statement has no effect");
8048 rem_anchor_token('}');
8049 assert(scope == &statement->compound.scope);
8050 set_scope(last_scope);
8051 environment_pop_to(top);
8057 * Initialize builtin types.
8059 static void initialize_builtin_types(void)
8061 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8062 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8063 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8064 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8065 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8066 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8067 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8068 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8070 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8071 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8072 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8073 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8077 * Check for unused global static functions and variables
8079 static void check_unused_globals(void)
8081 if (!warning.unused_function && !warning.unused_variable)
8084 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8085 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
8088 type_t *const type = decl->type;
8090 if (is_type_function(skip_typeref(type))) {
8091 if (!warning.unused_function || decl->is_inline)
8094 s = (decl->init.statement != NULL ? "defined" : "declared");
8096 if (!warning.unused_variable)
8102 warningf(&decl->source_position, "'%#T' %s but not used",
8103 type, decl->symbol, s);
8108 * Parse a translation unit.
8110 static void parse_translation_unit(void)
8112 while(token.type != T_EOF) {
8113 if (token.type == ';') {
8114 /* TODO error in strict mode */
8115 warningf(HERE, "stray ';' outside of function");
8118 parse_external_declaration();
8126 * @return the translation unit or NULL if errors occurred.
8128 void start_parsing(void)
8130 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8131 label_stack = NEW_ARR_F(stack_entry_t, 0);
8132 diagnostic_count = 0;
8136 type_set_output(stderr);
8137 ast_set_output(stderr);
8139 assert(unit == NULL);
8140 unit = allocate_ast_zero(sizeof(unit[0]));
8142 assert(global_scope == NULL);
8143 global_scope = &unit->scope;
8145 assert(scope == NULL);
8146 set_scope(&unit->scope);
8148 initialize_builtin_types();
8151 translation_unit_t *finish_parsing(void)
8153 assert(scope == &unit->scope);
8155 last_declaration = NULL;
8157 assert(global_scope == &unit->scope);
8158 check_unused_globals();
8159 global_scope = NULL;
8161 DEL_ARR_F(environment_stack);
8162 DEL_ARR_F(label_stack);
8164 translation_unit_t *result = unit;
8171 lookahead_bufpos = 0;
8172 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8175 parse_translation_unit();
8179 * Initialize the parser.
8181 void init_parser(void)
8184 /* add predefined symbols for extended-decl-modifier */
8185 sym_align = symbol_table_insert("align");
8186 sym_allocate = symbol_table_insert("allocate");
8187 sym_dllimport = symbol_table_insert("dllimport");
8188 sym_dllexport = symbol_table_insert("dllexport");
8189 sym_naked = symbol_table_insert("naked");
8190 sym_noinline = symbol_table_insert("noinline");
8191 sym_noreturn = symbol_table_insert("noreturn");
8192 sym_nothrow = symbol_table_insert("nothrow");
8193 sym_novtable = symbol_table_insert("novtable");
8194 sym_property = symbol_table_insert("property");
8195 sym_get = symbol_table_insert("get");
8196 sym_put = symbol_table_insert("put");
8197 sym_selectany = symbol_table_insert("selectany");
8198 sym_thread = symbol_table_insert("thread");
8199 sym_uuid = symbol_table_insert("uuid");
8200 sym_deprecated = symbol_table_insert("deprecated");
8201 sym_restrict = symbol_table_insert("restrict");
8202 sym_noalias = symbol_table_insert("noalias");
8204 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8206 init_expression_parsers();
8207 obstack_init(&temp_obst);
8209 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8210 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8214 * Terminate the parser.
8216 void exit_parser(void)
8218 obstack_free(&temp_obst, NULL);