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 declaration_specifiers_t declaration_specifiers_t;
52 struct declaration_specifiers_t {
53 source_position_t source_position;
54 unsigned char declared_storage_class;
55 unsigned char alignment; /**< Alignment, 0 if not set. */
56 unsigned int is_inline : 1;
57 unsigned int deprecated : 1;
58 decl_modifiers_t decl_modifiers; /**< MS __declspec extended modifier mask */
59 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
60 symbol_t *get_property_sym; /**< the name of the get property if set. */
61 symbol_t *put_property_sym; /**< the name of the put property if set. */
66 * An environment for parsing initializers (and compound literals).
68 typedef struct parse_initializer_env_t {
69 type_t *type; /**< the type of the initializer. In case of an
70 array type with unspecified size this gets
71 adjusted to the actual size. */
72 declaration_t *declaration; /**< the declaration that is initialized if any */
73 bool must_be_constant;
74 } parse_initializer_env_t;
76 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
79 static token_t lookahead_buffer[MAX_LOOKAHEAD];
80 static int lookahead_bufpos;
81 static stack_entry_t *environment_stack = NULL;
82 static stack_entry_t *label_stack = NULL;
83 static scope_t *global_scope = NULL;
84 static scope_t *scope = NULL;
85 static declaration_t *last_declaration = NULL;
86 static declaration_t *current_function = NULL;
87 static switch_statement_t *current_switch = NULL;
88 static statement_t *current_loop = NULL;
89 static goto_statement_t *goto_first = NULL;
90 static goto_statement_t *goto_last = NULL;
91 static label_statement_t *label_first = NULL;
92 static label_statement_t *label_last = NULL;
93 static struct obstack temp_obst;
95 /* symbols for Microsoft extended-decl-modifier */
96 static const symbol_t *sym_align = NULL;
97 static const symbol_t *sym_allocate = NULL;
98 static const symbol_t *sym_dllimport = NULL;
99 static const symbol_t *sym_dllexport = NULL;
100 static const symbol_t *sym_naked = NULL;
101 static const symbol_t *sym_noinline = NULL;
102 static const symbol_t *sym_noreturn = NULL;
103 static const symbol_t *sym_nothrow = NULL;
104 static const symbol_t *sym_novtable = NULL;
105 static const symbol_t *sym_property = NULL;
106 static const symbol_t *sym_get = NULL;
107 static const symbol_t *sym_put = NULL;
108 static const symbol_t *sym_selectany = NULL;
109 static const symbol_t *sym_thread = NULL;
110 static const symbol_t *sym_uuid = NULL;
111 static const symbol_t *sym_deprecated = NULL;
112 static const symbol_t *sym_restrict = NULL;
113 static const symbol_t *sym_noalias = NULL;
115 /** The token anchor set */
116 static unsigned char token_anchor_set[T_LAST_TOKEN];
118 /** The current source position. */
119 #define HERE token.source_position
121 static type_t *type_valist;
123 static statement_t *parse_compound_statement(void);
124 static statement_t *parse_statement(void);
126 static expression_t *parse_sub_expression(unsigned precedence);
127 static expression_t *parse_expression(void);
128 static type_t *parse_typename(void);
130 static void parse_compound_type_entries(declaration_t *compound_declaration);
131 static declaration_t *parse_declarator(
132 const declaration_specifiers_t *specifiers, bool may_be_abstract);
133 static declaration_t *record_declaration(declaration_t *declaration);
135 static void semantic_comparison(binary_expression_t *expression);
137 #define STORAGE_CLASSES \
144 #define TYPE_QUALIFIERS \
151 #ifdef PROVIDE_COMPLEX
152 #define COMPLEX_SPECIFIERS \
154 #define IMAGINARY_SPECIFIERS \
157 #define COMPLEX_SPECIFIERS
158 #define IMAGINARY_SPECIFIERS
161 #define TYPE_SPECIFIERS \
176 case T___builtin_va_list: \
181 #define DECLARATION_START \
186 #define TYPENAME_START \
191 * Allocate an AST node with given size and
192 * initialize all fields with zero.
194 static void *allocate_ast_zero(size_t size)
196 void *res = allocate_ast(size);
197 memset(res, 0, size);
201 static declaration_t *allocate_declaration_zero(void)
203 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
204 declaration->type = type_error_type;
205 declaration->alignment = 0;
210 * Returns the size of a statement node.
212 * @param kind the statement kind
214 static size_t get_statement_struct_size(statement_kind_t kind)
216 static const size_t sizes[] = {
217 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
218 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
219 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
220 [STATEMENT_RETURN] = sizeof(return_statement_t),
221 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
222 [STATEMENT_IF] = sizeof(if_statement_t),
223 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
224 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
225 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
226 [STATEMENT_BREAK] = sizeof(statement_base_t),
227 [STATEMENT_GOTO] = sizeof(goto_statement_t),
228 [STATEMENT_LABEL] = sizeof(label_statement_t),
229 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
230 [STATEMENT_WHILE] = sizeof(while_statement_t),
231 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
232 [STATEMENT_FOR] = sizeof(for_statement_t),
233 [STATEMENT_ASM] = sizeof(asm_statement_t)
235 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
236 assert(sizes[kind] != 0);
241 * Returns the size of an expression node.
243 * @param kind the expression kind
245 static size_t get_expression_struct_size(expression_kind_t kind)
247 static const size_t sizes[] = {
248 [EXPR_INVALID] = sizeof(expression_base_t),
249 [EXPR_REFERENCE] = sizeof(reference_expression_t),
250 [EXPR_CONST] = sizeof(const_expression_t),
251 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
252 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
253 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
254 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
255 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
256 [EXPR_CALL] = sizeof(call_expression_t),
257 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
258 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
259 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
260 [EXPR_SELECT] = sizeof(select_expression_t),
261 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
262 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
263 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
264 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
265 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
266 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
267 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
268 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
269 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
270 [EXPR_VA_START] = sizeof(va_start_expression_t),
271 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
272 [EXPR_STATEMENT] = sizeof(statement_expression_t),
274 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
275 return sizes[EXPR_UNARY_FIRST];
277 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
278 return sizes[EXPR_BINARY_FIRST];
280 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
281 assert(sizes[kind] != 0);
286 * Allocate a statement node of given kind and initialize all
289 static statement_t *allocate_statement_zero(statement_kind_t kind)
291 size_t size = get_statement_struct_size(kind);
292 statement_t *res = allocate_ast_zero(size);
294 res->base.kind = kind;
299 * Allocate an expression node of given kind and initialize all
302 static expression_t *allocate_expression_zero(expression_kind_t kind)
304 size_t size = get_expression_struct_size(kind);
305 expression_t *res = allocate_ast_zero(size);
307 res->base.kind = kind;
308 res->base.type = type_error_type;
313 * Creates a new invalid expression.
315 static expression_t *create_invalid_expression(void)
317 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
318 expression->base.source_position = token.source_position;
323 * Creates a new invalid statement.
325 static statement_t *create_invalid_statement(void)
327 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
328 statement->base.source_position = token.source_position;
333 * Allocate a new empty statement.
335 static statement_t *create_empty_statement(void)
337 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
338 statement->base.source_position = token.source_position;
343 * Returns the size of a type node.
345 * @param kind the type kind
347 static size_t get_type_struct_size(type_kind_t kind)
349 static const size_t sizes[] = {
350 [TYPE_ATOMIC] = sizeof(atomic_type_t),
351 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
352 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
353 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
354 [TYPE_ENUM] = sizeof(enum_type_t),
355 [TYPE_FUNCTION] = sizeof(function_type_t),
356 [TYPE_POINTER] = sizeof(pointer_type_t),
357 [TYPE_ARRAY] = sizeof(array_type_t),
358 [TYPE_BUILTIN] = sizeof(builtin_type_t),
359 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
360 [TYPE_TYPEOF] = sizeof(typeof_type_t),
362 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
363 assert(kind <= TYPE_TYPEOF);
364 assert(sizes[kind] != 0);
369 * Allocate a type node of given kind and initialize all
372 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
374 size_t size = get_type_struct_size(kind);
375 type_t *res = obstack_alloc(type_obst, size);
376 memset(res, 0, size);
378 res->base.kind = kind;
379 res->base.source_position = source_position;
384 * Returns the size of an initializer node.
386 * @param kind the initializer kind
388 static size_t get_initializer_size(initializer_kind_t kind)
390 static const size_t sizes[] = {
391 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
392 [INITIALIZER_STRING] = sizeof(initializer_string_t),
393 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
394 [INITIALIZER_LIST] = sizeof(initializer_list_t),
395 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
397 assert(kind < sizeof(sizes) / sizeof(*sizes));
398 assert(sizes[kind] != 0);
403 * Allocate an initializer node of given kind and initialize all
406 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
408 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
415 * Free a type from the type obstack.
417 static void free_type(void *type)
419 obstack_free(type_obst, type);
423 * Returns the index of the top element of the environment stack.
425 static size_t environment_top(void)
427 return ARR_LEN(environment_stack);
431 * Returns the index of the top element of the label stack.
433 static size_t label_top(void)
435 return ARR_LEN(label_stack);
439 * Return the next token.
441 static inline void next_token(void)
443 token = lookahead_buffer[lookahead_bufpos];
444 lookahead_buffer[lookahead_bufpos] = lexer_token;
447 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
450 print_token(stderr, &token);
451 fprintf(stderr, "\n");
456 * Return the next token with a given lookahead.
458 static inline const token_t *look_ahead(int num)
460 assert(num > 0 && num <= MAX_LOOKAHEAD);
461 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
462 return &lookahead_buffer[pos];
466 * Adds a token to the token anchor set (a multi-set).
468 static void add_anchor_token(int token_type) {
469 assert(0 <= token_type && token_type < T_LAST_TOKEN);
470 ++token_anchor_set[token_type];
474 * Remove a token from the token anchor set (a multi-set).
476 static void rem_anchor_token(int token_type) {
477 assert(0 <= token_type && token_type < T_LAST_TOKEN);
478 --token_anchor_set[token_type];
481 static bool at_anchor(void) {
484 return token_anchor_set[token.type];
488 * Eat tokens until a matching token is found.
490 static void eat_until_matching_token(int type) {
491 unsigned parenthesis_count = 0;
492 unsigned brace_count = 0;
493 unsigned bracket_count = 0;
494 int end_token = type;
503 while(token.type != end_token ||
504 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
508 case '(': ++parenthesis_count; break;
509 case '{': ++brace_count; break;
510 case '[': ++bracket_count; break;
512 if(parenthesis_count > 0)
520 if(bracket_count > 0)
531 * Eat input tokens until an anchor is found.
533 static void eat_until_anchor(void) {
534 if(token.type == T_EOF)
536 while(token_anchor_set[token.type] == 0) {
537 if(token.type == '(' || token.type == '{' || token.type == '[')
538 eat_until_matching_token(token.type);
539 if(token.type == T_EOF)
545 static void eat_block(void) {
546 eat_until_matching_token('{');
547 if(token.type == '}')
552 * eat all token until a ';' is reached
553 * or a stop token is found.
555 static void eat_statement(void) {
556 eat_until_matching_token(';');
557 if(token.type == ';')
561 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
564 * Report a parse error because an expected token was not found.
566 static void parse_error_expected(const char *message, ...)
568 if(message != NULL) {
569 errorf(HERE, "%s", message);
572 va_start(ap, message);
573 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
578 * Report a type error.
580 static void type_error(const char *msg, const source_position_t source_position,
583 errorf(source_position, "%s, but found type '%T'", msg, type);
587 * Report an incompatible type.
589 static void type_error_incompatible(const char *msg,
590 const source_position_t source_position, type_t *type1, type_t *type2)
592 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
596 * Expect the the current token is the expected token.
597 * If not, generate an error, eat the current statement,
598 * and goto the end_error label.
600 #define expect(expected) \
602 if(UNLIKELY(token.type != (expected))) { \
603 parse_error_expected(NULL, (expected), 0); \
604 add_anchor_token(expected); \
605 eat_until_anchor(); \
606 rem_anchor_token(expected); \
612 static void set_scope(scope_t *new_scope)
615 scope->last_declaration = last_declaration;
619 last_declaration = new_scope->last_declaration;
623 * Search a symbol in a given namespace and returns its declaration or
624 * NULL if this symbol was not found.
626 static declaration_t *get_declaration(const symbol_t *const symbol,
627 const namespace_t namespc)
629 declaration_t *declaration = symbol->declaration;
630 for( ; declaration != NULL; declaration = declaration->symbol_next) {
631 if(declaration->namespc == namespc)
639 * pushs an environment_entry on the environment stack and links the
640 * corresponding symbol to the new entry
642 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
644 symbol_t *symbol = declaration->symbol;
645 namespace_t namespc = (namespace_t) declaration->namespc;
647 /* replace/add declaration into declaration list of the symbol */
648 declaration_t *iter = symbol->declaration;
650 symbol->declaration = declaration;
652 declaration_t *iter_last = NULL;
653 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
654 /* replace an entry? */
655 if(iter->namespc == namespc) {
656 if(iter_last == NULL) {
657 symbol->declaration = declaration;
659 iter_last->symbol_next = declaration;
661 declaration->symbol_next = iter->symbol_next;
666 assert(iter_last->symbol_next == NULL);
667 iter_last->symbol_next = declaration;
671 /* remember old declaration */
673 entry.symbol = symbol;
674 entry.old_declaration = iter;
675 entry.namespc = (unsigned short) namespc;
676 ARR_APP1(stack_entry_t, *stack_ptr, entry);
679 static void environment_push(declaration_t *declaration)
681 assert(declaration->source_position.input_name != NULL);
682 assert(declaration->parent_scope != NULL);
683 stack_push(&environment_stack, declaration);
686 static void label_push(declaration_t *declaration)
688 declaration->parent_scope = ¤t_function->scope;
689 stack_push(&label_stack, declaration);
693 * pops symbols from the environment stack until @p new_top is the top element
695 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
697 stack_entry_t *stack = *stack_ptr;
698 size_t top = ARR_LEN(stack);
701 assert(new_top <= top);
705 for(i = top; i > new_top; --i) {
706 stack_entry_t *entry = &stack[i - 1];
708 declaration_t *old_declaration = entry->old_declaration;
709 symbol_t *symbol = entry->symbol;
710 namespace_t namespc = (namespace_t)entry->namespc;
712 /* replace/remove declaration */
713 declaration_t *declaration = symbol->declaration;
714 assert(declaration != NULL);
715 if(declaration->namespc == namespc) {
716 if(old_declaration == NULL) {
717 symbol->declaration = declaration->symbol_next;
719 symbol->declaration = old_declaration;
722 declaration_t *iter_last = declaration;
723 declaration_t *iter = declaration->symbol_next;
724 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
725 /* replace an entry? */
726 if(iter->namespc == namespc) {
727 assert(iter_last != NULL);
728 iter_last->symbol_next = old_declaration;
729 if(old_declaration != NULL) {
730 old_declaration->symbol_next = iter->symbol_next;
735 assert(iter != NULL);
739 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
742 static void environment_pop_to(size_t new_top)
744 stack_pop_to(&environment_stack, new_top);
747 static void label_pop_to(size_t new_top)
749 stack_pop_to(&label_stack, new_top);
753 static int get_rank(const type_t *type)
755 assert(!is_typeref(type));
756 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
757 * and esp. footnote 108). However we can't fold constants (yet), so we
758 * can't decide whether unsigned int is possible, while int always works.
759 * (unsigned int would be preferable when possible... for stuff like
760 * struct { enum { ... } bla : 4; } ) */
761 if(type->kind == TYPE_ENUM)
762 return ATOMIC_TYPE_INT;
764 assert(type->kind == TYPE_ATOMIC);
765 return type->atomic.akind;
768 static type_t *promote_integer(type_t *type)
770 if(type->kind == TYPE_BITFIELD)
771 type = type->bitfield.base;
773 if(get_rank(type) < ATOMIC_TYPE_INT)
780 * Create a cast expression.
782 * @param expression the expression to cast
783 * @param dest_type the destination type
785 static expression_t *create_cast_expression(expression_t *expression,
788 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
790 cast->unary.value = expression;
791 cast->base.type = dest_type;
797 * Check if a given expression represents the 0 pointer constant.
799 static bool is_null_pointer_constant(const expression_t *expression)
801 /* skip void* cast */
802 if(expression->kind == EXPR_UNARY_CAST
803 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
804 expression = expression->unary.value;
807 /* TODO: not correct yet, should be any constant integer expression
808 * which evaluates to 0 */
809 if (expression->kind != EXPR_CONST)
812 type_t *const type = skip_typeref(expression->base.type);
813 if (!is_type_integer(type))
816 return expression->conste.v.int_value == 0;
820 * Create an implicit cast expression.
822 * @param expression the expression to cast
823 * @param dest_type the destination type
825 static expression_t *create_implicit_cast(expression_t *expression,
828 type_t *const source_type = expression->base.type;
830 if (source_type == dest_type)
833 return create_cast_expression(expression, dest_type);
836 /** Implements the rules from § 6.5.16.1 */
837 static type_t *semantic_assign(type_t *orig_type_left,
838 const expression_t *const right,
840 source_position_t source_position)
842 type_t *const orig_type_right = right->base.type;
843 type_t *const type_left = skip_typeref(orig_type_left);
844 type_t *const type_right = skip_typeref(orig_type_right);
846 if(is_type_pointer(type_left)) {
847 if(is_null_pointer_constant(right)) {
848 return orig_type_left;
849 } else if(is_type_pointer(type_right)) {
850 type_t *points_to_left
851 = skip_typeref(type_left->pointer.points_to);
852 type_t *points_to_right
853 = skip_typeref(type_right->pointer.points_to);
855 /* the left type has all qualifiers from the right type */
856 unsigned missing_qualifiers
857 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
858 if(missing_qualifiers != 0) {
859 errorf(source_position,
860 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
861 return orig_type_left;
864 points_to_left = get_unqualified_type(points_to_left);
865 points_to_right = get_unqualified_type(points_to_right);
867 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
868 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
869 return orig_type_left;
872 if (!types_compatible(points_to_left, points_to_right)) {
873 warningf(source_position,
874 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
875 orig_type_left, context, right, orig_type_right);
878 return orig_type_left;
879 } else if(is_type_integer(type_right)) {
880 warningf(source_position,
881 "%s makes pointer '%T' from integer '%T' without a cast",
882 context, orig_type_left, orig_type_right);
883 return orig_type_left;
885 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
886 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
887 && is_type_pointer(type_right))) {
888 return orig_type_left;
889 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
890 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
891 type_t *const unqual_type_left = get_unqualified_type(type_left);
892 type_t *const unqual_type_right = get_unqualified_type(type_right);
893 if (types_compatible(unqual_type_left, unqual_type_right)) {
894 return orig_type_left;
896 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
897 warningf(source_position,
898 "%s makes integer '%T' from pointer '%T' without a cast",
899 context, orig_type_left, orig_type_right);
900 return orig_type_left;
903 if (!is_type_valid(type_left))
906 if (!is_type_valid(type_right))
907 return orig_type_right;
912 static expression_t *parse_constant_expression(void)
914 /* start parsing at precedence 7 (conditional expression) */
915 expression_t *result = parse_sub_expression(7);
917 if(!is_constant_expression(result)) {
918 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
924 static expression_t *parse_assignment_expression(void)
926 /* start parsing at precedence 2 (assignment expression) */
927 return parse_sub_expression(2);
930 static type_t *make_global_typedef(const char *name, type_t *type)
932 symbol_t *const symbol = symbol_table_insert(name);
934 declaration_t *const declaration = allocate_declaration_zero();
935 declaration->namespc = NAMESPACE_NORMAL;
936 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
937 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
938 declaration->type = type;
939 declaration->symbol = symbol;
940 declaration->source_position = builtin_source_position;
942 record_declaration(declaration);
944 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
945 typedef_type->typedeft.declaration = declaration;
950 static string_t parse_string_literals(void)
952 assert(token.type == T_STRING_LITERAL);
953 string_t result = token.v.string;
957 while (token.type == T_STRING_LITERAL) {
958 result = concat_strings(&result, &token.v.string);
965 typedef enum gnu_attribute_kind_t {
976 GNU_AK_ALWAYS_INLINE,
982 GNU_AK_TRANSPARENT_UNION,
989 GNU_AK_NO_INSTRUMENT_FUNCTION,
990 GNU_AK_WARN_UNUSED_RESULT,
995 GNU_AK_FUNCTION_VECTOR,
997 GNU_AK_INTERRUPT_HANDLER,
1001 GNU_AK_EIGTHBIT_DATA,
1018 } gnu_attribute_kind_t;
1020 static const char *gnu_attribute_names[GNU_AK_LAST] = {
1021 [GNU_AK_CONST] = "const",
1022 [GNU_AK_VOLATILE] = "volatile",
1023 [GNU_AK_CDECL] = "cdecl",
1024 [GNU_AK_STDCALL] = "stdcall",
1025 [GNU_AK_FASTCALL] = "fastcall",
1026 [GNU_AK_DEPRECATED] = "deprecated",
1027 [GNU_AK_NOINLINE] = "noinline",
1028 [GNU_AK_NORETURN] = "noreturn",
1029 [GNU_AK_NAKED] = "naked",
1030 [GNU_AK_PURE] = "pure",
1031 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1032 [GNU_AK_MALLOC] = "malloc",
1033 [GNU_AK_WEAK] = "weak",
1034 [GNU_AK_CONSTRUCTOR] = "constructor",
1035 [GNU_AK_DESTRUCTOR] = "destructor",
1036 [GNU_AK_NOTHROW] = "nothrow",
1037 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1038 [GNU_AK_COMMON] = "coommon",
1039 [GNU_AK_NOCOMMON] = "nocommon",
1040 [GNU_AK_PACKED] = "packed",
1041 [GNU_AK_SHARED] = "shared",
1042 [GNU_AK_USED] = "used",
1043 [GNU_AK_UNUSED] = "unused",
1044 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1045 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1046 [GNU_AK_LONGCALL] = "longcall",
1047 [GNU_AK_SHORTCALL] = "shortcall",
1048 [GNU_AK_LONG_CALL] = "long_call",
1049 [GNU_AK_SHORT_CALL] = "short_call",
1050 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1051 [GNU_AK_INTERRUPT] = "interrupt",
1052 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1053 [GNU_AK_NEAR] = "near",
1054 [GNU_AK_FAR] = "far",
1055 [GNU_AK_SIGNAL] = "signal",
1056 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1057 [GNU_AK_TINY_DATA] = "tiny_data",
1058 [GNU_AK_SAVEALL] = "saveall",
1059 [GNU_AK_ALIGNED] = "aligned",
1060 [GNU_AK_ALIAS] = "alias",
1061 [GNU_AK_SECTION] = "section",
1062 [GNU_AK_FORMAT] = "format",
1063 [GNU_AK_FORMAT_ARG] = "format_arg",
1064 [GNU_AK_WEAKREF] = "weakref",
1065 [GNU_AK_NONNULL] = "nonnull",
1066 [GNU_AK_TLS_MODEL] = "tls_model",
1067 [GNU_AK_VISIBILITY] = "visibility",
1068 [GNU_AK_REGPARM] = "regparm",
1069 [GNU_AK_MODEL] = "model",
1070 [GNU_AK_TRAP_EXIT] = "trap_exit",
1071 [GNU_AK_SP_SWITCH] = "sp_switch"
1075 * compare two string, ignoring double underscores on the second.
1077 static int strcmp_underscore(const char *s1, const char *s2) {
1078 if(s2[0] == '_' && s2[1] == '_') {
1080 size_t l1 = strlen(s1);
1081 if(l1 + 2 != strlen(s2)) {
1085 return strncmp(s1, s2, l1);
1087 return strcmp(s1, s2);
1091 * parse one constant expression argument.
1093 static expression_t *parse_gnu_attribute_const_arg(void) {
1094 expression_t *expression;
1095 add_anchor_token(')');
1096 expression = parse_constant_expression();
1097 rem_anchor_token(')');
1101 return create_invalid_expression();
1105 * parse a list of constant expressions argumnets.
1107 static expression_t *parse_gnu_attribute_const_arg_list(void) {
1108 expression_t *expression;
1109 add_anchor_token(')');
1110 add_anchor_token(',');
1112 expression = parse_constant_expression();
1113 if(token.type != ',')
1117 rem_anchor_token(',');
1118 rem_anchor_token(')');
1122 return create_invalid_expression();
1126 * parse one string literal argument.
1128 static string_t parse_gnu_attribute_string_arg(void) {
1129 string_t string = { NULL, 0 };
1130 add_anchor_token('(');
1131 if(token.type != T_STRING_LITERAL) {
1132 parse_error_expected("while parsing attribute directive", T_STRING_LITERAL);
1135 string = parse_string_literals();
1136 rem_anchor_token('(');
1143 * parse one tls model.
1145 static int parse_gnu_attribute_tls_model_arg(void) {
1146 static const char *tls_models[] = {
1152 string_t string = parse_gnu_attribute_string_arg();
1153 if(string.begin != NULL) {
1154 for(int i = 0; i < 4; ++i) {
1155 if(strcmp(tls_models[i], string.begin) == 0)
1159 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1164 * parse one tls model.
1166 static int parse_gnu_attribute_visibility_arg(void) {
1167 static const char *visibilities[] = {
1173 string_t string = parse_gnu_attribute_string_arg();
1174 if(string.begin != NULL) {
1175 for(int i = 0; i < 4; ++i) {
1176 if(strcmp(visibilities[i], string.begin) == 0)
1180 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1185 * parse one (code) model.
1187 static int parse_gnu_attribute_model_arg(void) {
1188 static const char *visibilities[] = {
1193 string_t string = parse_gnu_attribute_string_arg();
1194 if(string.begin != NULL) {
1195 for(int i = 0; i < 3; ++i) {
1196 if(strcmp(visibilities[i], string.begin) == 0)
1200 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1205 * parse one interrupt argument.
1207 static int parse_gnu_attribute_interrupt_arg(void) {
1208 static const char *interrupts[] = {
1215 string_t string = parse_gnu_attribute_string_arg();
1216 if(string.begin != NULL) {
1217 for(int i = 0; i < 5; ++i) {
1218 if(strcmp(interrupts[i], string.begin) == 0)
1222 errorf(HERE, "'%s' is an interrupt", string.begin);
1227 * parse ( identifier, const expression, const expression )
1229 static void parse_gnu_attribute_format_args(void) {
1230 static const char *format_names[] = {
1238 if(token.type != T_IDENTIFIER) {
1239 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER);
1242 const char *name = token.v.symbol->string;
1243 for(i = 0; i < 4; ++i) {
1244 if(strcmp_underscore(format_names[i], name) == 0)
1248 if(warning.attribute)
1249 warningf(HERE, "'%s' is an unrecognized format function type", name);
1254 add_anchor_token(')');
1255 add_anchor_token(',');
1256 parse_constant_expression();
1257 rem_anchor_token(',');
1258 rem_anchor_token('(');
1261 add_anchor_token(')');
1262 parse_constant_expression();
1263 rem_anchor_token('(');
1271 * Parse one GNU attribute.
1273 * Note that attribute names can be specified WITH or WITHOUT
1274 * double underscores, ie const or __const__.
1276 * The following attributes are parsed without arguments
1300 * no_instrument_function
1301 * warn_unused_result
1315 * The following attributes are parsed with arguments
1316 * aligned( const expression )
1317 * alias( string literal )
1318 * section( string literal )
1319 * format( identifier, const expression, const expression )
1320 * format_arg( const expression )
1321 * tls_model( string literal )
1322 * visibility( string literal )
1323 * regparm( const expression )
1324 * model( string leteral )
1325 * trap_exit( const expression )
1326 * sp_switch( string literal )
1328 * The following attributes might have arguments
1329 * weak_ref( string literal )
1330 * non_null( const expression // ',' )
1331 * interrupt( string literal )
1333 static void parse_gnu_attribute(void)
1335 eat(T___attribute__);
1338 if(token.type != ')') {
1339 /* non-empty attribute list */
1342 if(token.type == T_const) {
1344 } else if(token.type == T_volatile) {
1346 } else if(token.type == T_cdecl) {
1347 /* __attribute__((cdecl)), WITH ms mode */
1349 } else if(token.type != T_IDENTIFIER) {
1350 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1353 const symbol_t *sym = token.v.symbol;
1357 gnu_attribute_kind_t kind;
1358 for(kind = 0; kind < GNU_AK_LAST; ++kind) {
1359 if(strcmp_underscore(gnu_attribute_names[kind], name) == 0)
1363 if(kind == GNU_AK_LAST) {
1364 if(warning.attribute)
1365 warningf(HERE, "'%s' attribute directive ignored", name);
1367 /* skip possible arguments */
1368 if(token.type == '(') {
1369 eat_until_matching_token(')');
1372 /* check for arguments */
1373 bool have_args = false;
1374 if(token.type == '(') {
1376 if(token.type == ')') {
1377 /* empty args are allowed */
1385 case GNU_AK_VOLATILE:
1387 case GNU_AK_STDCALL:
1388 case GNU_AK_FASTCALL:
1389 case GNU_AK_DEPRECATED:
1390 case GNU_AK_NOINLINE:
1391 case GNU_AK_NORETURN:
1394 case GNU_AK_ALWAYS_INLINE:
1397 case GNU_AK_CONSTRUCTOR:
1398 case GNU_AK_DESTRUCTOR:
1399 case GNU_AK_NOTHROW:
1400 case GNU_AK_TRANSPARENT_UNION:
1402 case GNU_AK_NOCOMMON:
1407 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1408 case GNU_AK_WARN_UNUSED_RESULT:
1409 case GNU_AK_LONGCALL:
1410 case GNU_AK_SHORTCALL:
1411 case GNU_AK_LONG_CALL:
1412 case GNU_AK_SHORT_CALL:
1413 case GNU_AK_FUNCTION_VECTOR:
1414 case GNU_AK_INTERRUPT_HANDLER:
1418 case GNU_AK_EIGTHBIT_DATA:
1419 case GNU_AK_TINY_DATA:
1420 case GNU_AK_SAVEALL:
1422 /* should have no arguments */
1423 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1424 eat_until_matching_token('(');
1425 /* we have already consumend '(', so we stop before ')', eat it */
1430 case GNU_AK_ALIGNED:
1431 case GNU_AK_FORMAT_ARG:
1432 case GNU_AK_REGPARM:
1433 case GNU_AK_TRAP_EXIT:
1435 /* should have arguments */
1436 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1438 parse_gnu_attribute_const_arg();
1441 case GNU_AK_SECTION:
1442 case GNU_AK_SP_SWITCH:
1444 /* should have arguments */
1445 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1447 parse_gnu_attribute_string_arg();
1451 /* should have arguments */
1452 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1454 parse_gnu_attribute_format_args();
1456 case GNU_AK_WEAKREF:
1457 /* may have one string argument */
1459 parse_gnu_attribute_string_arg();
1461 case GNU_AK_NONNULL:
1463 parse_gnu_attribute_const_arg_list();
1465 case GNU_AK_TLS_MODEL:
1467 /* should have arguments */
1468 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1470 parse_gnu_attribute_tls_model_arg();
1472 case GNU_AK_VISIBILITY:
1474 /* should have arguments */
1475 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1477 parse_gnu_attribute_visibility_arg();
1481 /* should have arguments */
1482 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1484 parse_gnu_attribute_model_arg();
1485 case GNU_AK_INTERRUPT:
1486 /* may have one string argument */
1488 parse_gnu_attribute_interrupt_arg();
1491 /* already handled */
1495 if(token.type != ',')
1507 * Parse GNU attributes.
1509 static void parse_attributes(void)
1512 switch(token.type) {
1513 case T___attribute__: {
1514 parse_gnu_attribute();
1520 if(token.type != T_STRING_LITERAL) {
1521 parse_error_expected("while parsing assembler attribute",
1523 eat_until_matching_token('(');
1526 parse_string_literals();
1531 goto attributes_finished;
1536 attributes_finished:
1540 static designator_t *parse_designation(void)
1542 designator_t *result = NULL;
1543 designator_t *last = NULL;
1546 designator_t *designator;
1547 switch(token.type) {
1549 designator = allocate_ast_zero(sizeof(designator[0]));
1550 designator->source_position = token.source_position;
1552 add_anchor_token(']');
1553 designator->array_index = parse_constant_expression();
1554 rem_anchor_token(']');
1558 designator = allocate_ast_zero(sizeof(designator[0]));
1559 designator->source_position = token.source_position;
1561 if(token.type != T_IDENTIFIER) {
1562 parse_error_expected("while parsing designator",
1566 designator->symbol = token.v.symbol;
1574 assert(designator != NULL);
1576 last->next = designator;
1578 result = designator;
1586 static initializer_t *initializer_from_string(array_type_t *type,
1587 const string_t *const string)
1589 /* TODO: check len vs. size of array type */
1592 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1593 initializer->string.string = *string;
1598 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1599 wide_string_t *const string)
1601 /* TODO: check len vs. size of array type */
1604 initializer_t *const initializer =
1605 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1606 initializer->wide_string.string = *string;
1612 * Build an initializer from a given expression.
1614 static initializer_t *initializer_from_expression(type_t *orig_type,
1615 expression_t *expression)
1617 /* TODO check that expression is a constant expression */
1619 /* § 6.7.8.14/15 char array may be initialized by string literals */
1620 type_t *type = skip_typeref(orig_type);
1621 type_t *expr_type_orig = expression->base.type;
1622 type_t *expr_type = skip_typeref(expr_type_orig);
1623 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1624 array_type_t *const array_type = &type->array;
1625 type_t *const element_type = skip_typeref(array_type->element_type);
1627 if (element_type->kind == TYPE_ATOMIC) {
1628 atomic_type_kind_t akind = element_type->atomic.akind;
1629 switch (expression->kind) {
1630 case EXPR_STRING_LITERAL:
1631 if (akind == ATOMIC_TYPE_CHAR
1632 || akind == ATOMIC_TYPE_SCHAR
1633 || akind == ATOMIC_TYPE_UCHAR) {
1634 return initializer_from_string(array_type,
1635 &expression->string.value);
1638 case EXPR_WIDE_STRING_LITERAL: {
1639 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1640 if (get_unqualified_type(element_type) == bare_wchar_type) {
1641 return initializer_from_wide_string(array_type,
1642 &expression->wide_string.value);
1652 type_t *const res_type = semantic_assign(type, expression, "initializer",
1653 expression->base.source_position);
1654 if (res_type == NULL)
1657 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1658 result->value.value = create_implicit_cast(expression, res_type);
1664 * Checks if a given expression can be used as an constant initializer.
1666 static bool is_initializer_constant(const expression_t *expression)
1668 return is_constant_expression(expression)
1669 || is_address_constant(expression);
1673 * Parses an scalar initializer.
1675 * § 6.7.8.11; eat {} without warning
1677 static initializer_t *parse_scalar_initializer(type_t *type,
1678 bool must_be_constant)
1680 /* there might be extra {} hierarchies */
1682 while(token.type == '{') {
1685 warningf(HERE, "extra curly braces around scalar initializer");
1690 expression_t *expression = parse_assignment_expression();
1691 if(must_be_constant && !is_initializer_constant(expression)) {
1692 errorf(expression->base.source_position,
1693 "Initialisation expression '%E' is not constant\n",
1697 initializer_t *initializer = initializer_from_expression(type, expression);
1699 if(initializer == NULL) {
1700 errorf(expression->base.source_position,
1701 "expression '%E' (type '%T') doesn't match expected type '%T'",
1702 expression, expression->base.type, type);
1707 bool additional_warning_displayed = false;
1709 if(token.type == ',') {
1712 if(token.type != '}') {
1713 if(!additional_warning_displayed) {
1714 warningf(HERE, "additional elements in scalar initializer");
1715 additional_warning_displayed = true;
1726 * An entry in the type path.
1728 typedef struct type_path_entry_t type_path_entry_t;
1729 struct type_path_entry_t {
1730 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1732 size_t index; /**< For array types: the current index. */
1733 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1738 * A type path expression a position inside compound or array types.
1740 typedef struct type_path_t type_path_t;
1741 struct type_path_t {
1742 type_path_entry_t *path; /**< An flexible array containing the current path. */
1743 type_t *top_type; /**< type of the element the path points */
1744 size_t max_index; /**< largest index in outermost array */
1748 * Prints a type path for debugging.
1750 static __attribute__((unused)) void debug_print_type_path(
1751 const type_path_t *path)
1753 size_t len = ARR_LEN(path->path);
1755 for(size_t i = 0; i < len; ++i) {
1756 const type_path_entry_t *entry = & path->path[i];
1758 type_t *type = skip_typeref(entry->type);
1759 if(is_type_compound(type)) {
1760 /* in gcc mode structs can have no members */
1761 if(entry->v.compound_entry == NULL) {
1765 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1766 } else if(is_type_array(type)) {
1767 fprintf(stderr, "[%zd]", entry->v.index);
1769 fprintf(stderr, "-INVALID-");
1772 if(path->top_type != NULL) {
1773 fprintf(stderr, " (");
1774 print_type(path->top_type);
1775 fprintf(stderr, ")");
1780 * Return the top type path entry, ie. in a path
1781 * (type).a.b returns the b.
1783 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1785 size_t len = ARR_LEN(path->path);
1787 return &path->path[len-1];
1791 * Enlarge the type path by an (empty) element.
1793 static type_path_entry_t *append_to_type_path(type_path_t *path)
1795 size_t len = ARR_LEN(path->path);
1796 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1798 type_path_entry_t *result = & path->path[len];
1799 memset(result, 0, sizeof(result[0]));
1804 * Descending into a sub-type. Enter the scope of the current
1807 static void descend_into_subtype(type_path_t *path)
1809 type_t *orig_top_type = path->top_type;
1810 type_t *top_type = skip_typeref(orig_top_type);
1812 assert(is_type_compound(top_type) || is_type_array(top_type));
1814 type_path_entry_t *top = append_to_type_path(path);
1815 top->type = top_type;
1817 if(is_type_compound(top_type)) {
1818 declaration_t *declaration = top_type->compound.declaration;
1819 declaration_t *entry = declaration->scope.declarations;
1820 top->v.compound_entry = entry;
1823 path->top_type = entry->type;
1825 path->top_type = NULL;
1828 assert(is_type_array(top_type));
1831 path->top_type = top_type->array.element_type;
1836 * Pop an entry from the given type path, ie. returning from
1837 * (type).a.b to (type).a
1839 static void ascend_from_subtype(type_path_t *path)
1841 type_path_entry_t *top = get_type_path_top(path);
1843 path->top_type = top->type;
1845 size_t len = ARR_LEN(path->path);
1846 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1850 * Pop entries from the given type path until the given
1851 * path level is reached.
1853 static void ascend_to(type_path_t *path, size_t top_path_level)
1855 size_t len = ARR_LEN(path->path);
1857 while(len > top_path_level) {
1858 ascend_from_subtype(path);
1859 len = ARR_LEN(path->path);
1863 static bool walk_designator(type_path_t *path, const designator_t *designator,
1864 bool used_in_offsetof)
1866 for( ; designator != NULL; designator = designator->next) {
1867 type_path_entry_t *top = get_type_path_top(path);
1868 type_t *orig_type = top->type;
1870 type_t *type = skip_typeref(orig_type);
1872 if(designator->symbol != NULL) {
1873 symbol_t *symbol = designator->symbol;
1874 if(!is_type_compound(type)) {
1875 if(is_type_valid(type)) {
1876 errorf(designator->source_position,
1877 "'.%Y' designator used for non-compound type '%T'",
1883 declaration_t *declaration = type->compound.declaration;
1884 declaration_t *iter = declaration->scope.declarations;
1885 for( ; iter != NULL; iter = iter->next) {
1886 if(iter->symbol == symbol) {
1891 errorf(designator->source_position,
1892 "'%T' has no member named '%Y'", orig_type, symbol);
1895 if(used_in_offsetof) {
1896 type_t *real_type = skip_typeref(iter->type);
1897 if(real_type->kind == TYPE_BITFIELD) {
1898 errorf(designator->source_position,
1899 "offsetof designator '%Y' may not specify bitfield",
1905 top->type = orig_type;
1906 top->v.compound_entry = iter;
1907 orig_type = iter->type;
1909 expression_t *array_index = designator->array_index;
1910 assert(designator->array_index != NULL);
1912 if(!is_type_array(type)) {
1913 if(is_type_valid(type)) {
1914 errorf(designator->source_position,
1915 "[%E] designator used for non-array type '%T'",
1916 array_index, orig_type);
1920 if(!is_type_valid(array_index->base.type)) {
1924 long index = fold_constant(array_index);
1925 if(!used_in_offsetof) {
1927 errorf(designator->source_position,
1928 "array index [%E] must be positive", array_index);
1931 if(type->array.size_constant == true) {
1932 long array_size = type->array.size;
1933 if(index >= array_size) {
1934 errorf(designator->source_position,
1935 "designator [%E] (%d) exceeds array size %d",
1936 array_index, index, array_size);
1942 top->type = orig_type;
1943 top->v.index = (size_t) index;
1944 orig_type = type->array.element_type;
1946 path->top_type = orig_type;
1948 if(designator->next != NULL) {
1949 descend_into_subtype(path);
1958 static void advance_current_object(type_path_t *path, size_t top_path_level)
1960 type_path_entry_t *top = get_type_path_top(path);
1962 type_t *type = skip_typeref(top->type);
1963 if(is_type_union(type)) {
1964 /* in unions only the first element is initialized */
1965 top->v.compound_entry = NULL;
1966 } else if(is_type_struct(type)) {
1967 declaration_t *entry = top->v.compound_entry;
1969 entry = entry->next;
1970 top->v.compound_entry = entry;
1972 path->top_type = entry->type;
1976 assert(is_type_array(type));
1980 if(!type->array.size_constant || top->v.index < type->array.size) {
1985 /* we're past the last member of the current sub-aggregate, try if we
1986 * can ascend in the type hierarchy and continue with another subobject */
1987 size_t len = ARR_LEN(path->path);
1989 if(len > top_path_level) {
1990 ascend_from_subtype(path);
1991 advance_current_object(path, top_path_level);
1993 path->top_type = NULL;
1998 * skip until token is found.
2000 static void skip_until(int type) {
2001 while(token.type != type) {
2002 if(token.type == T_EOF)
2009 * skip any {...} blocks until a closing braket is reached.
2011 static void skip_initializers(void)
2013 if(token.type == '{')
2016 while(token.type != '}') {
2017 if(token.type == T_EOF)
2019 if(token.type == '{') {
2027 static initializer_t *create_empty_initializer(void)
2029 static initializer_t empty_initializer
2030 = { .list = { { INITIALIZER_LIST }, 0 } };
2031 return &empty_initializer;
2035 * Parse a part of an initialiser for a struct or union,
2037 static initializer_t *parse_sub_initializer(type_path_t *path,
2038 type_t *outer_type, size_t top_path_level,
2039 parse_initializer_env_t *env)
2041 if(token.type == '}') {
2042 /* empty initializer */
2043 return create_empty_initializer();
2046 type_t *orig_type = path->top_type;
2047 type_t *type = NULL;
2049 if (orig_type == NULL) {
2050 /* We are initializing an empty compound. */
2052 type = skip_typeref(orig_type);
2054 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2055 * initializers in this case. */
2056 if(!is_type_valid(type)) {
2057 skip_initializers();
2058 return create_empty_initializer();
2062 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2065 designator_t *designator = NULL;
2066 if(token.type == '.' || token.type == '[') {
2067 designator = parse_designation();
2069 /* reset path to toplevel, evaluate designator from there */
2070 ascend_to(path, top_path_level);
2071 if(!walk_designator(path, designator, false)) {
2072 /* can't continue after designation error */
2076 initializer_t *designator_initializer
2077 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2078 designator_initializer->designator.designator = designator;
2079 ARR_APP1(initializer_t*, initializers, designator_initializer);
2084 if(token.type == '{') {
2085 if(type != NULL && is_type_scalar(type)) {
2086 sub = parse_scalar_initializer(type, env->must_be_constant);
2090 if (env->declaration != NULL)
2091 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2092 env->declaration->symbol);
2094 errorf(HERE, "extra brace group at end of initializer");
2096 descend_into_subtype(path);
2098 add_anchor_token('}');
2099 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2101 rem_anchor_token('}');
2104 ascend_from_subtype(path);
2108 goto error_parse_next;
2112 /* must be an expression */
2113 expression_t *expression = parse_assignment_expression();
2115 if(env->must_be_constant && !is_initializer_constant(expression)) {
2116 errorf(expression->base.source_position,
2117 "Initialisation expression '%E' is not constant\n",
2122 /* we are already outside, ... */
2126 /* handle { "string" } special case */
2127 if((expression->kind == EXPR_STRING_LITERAL
2128 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2129 && outer_type != NULL) {
2130 sub = initializer_from_expression(outer_type, expression);
2132 if(token.type == ',') {
2135 if(token.type != '}') {
2136 warningf(HERE, "excessive elements in initializer for type '%T'",
2139 /* TODO: eat , ... */
2144 /* descend into subtypes until expression matches type */
2146 orig_type = path->top_type;
2147 type = skip_typeref(orig_type);
2149 sub = initializer_from_expression(orig_type, expression);
2153 if(!is_type_valid(type)) {
2156 if(is_type_scalar(type)) {
2157 errorf(expression->base.source_position,
2158 "expression '%E' doesn't match expected type '%T'",
2159 expression, orig_type);
2163 descend_into_subtype(path);
2167 /* update largest index of top array */
2168 const type_path_entry_t *first = &path->path[0];
2169 type_t *first_type = first->type;
2170 first_type = skip_typeref(first_type);
2171 if(is_type_array(first_type)) {
2172 size_t index = first->v.index;
2173 if(index > path->max_index)
2174 path->max_index = index;
2178 /* append to initializers list */
2179 ARR_APP1(initializer_t*, initializers, sub);
2182 if(env->declaration != NULL)
2183 warningf(HERE, "excess elements in struct initializer for '%Y'",
2184 env->declaration->symbol);
2186 warningf(HERE, "excess elements in struct initializer");
2190 if(token.type == '}') {
2194 if(token.type == '}') {
2199 /* advance to the next declaration if we are not at the end */
2200 advance_current_object(path, top_path_level);
2201 orig_type = path->top_type;
2202 if(orig_type != NULL)
2203 type = skip_typeref(orig_type);
2209 size_t len = ARR_LEN(initializers);
2210 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2211 initializer_t *result = allocate_ast_zero(size);
2212 result->kind = INITIALIZER_LIST;
2213 result->list.len = len;
2214 memcpy(&result->list.initializers, initializers,
2215 len * sizeof(initializers[0]));
2217 DEL_ARR_F(initializers);
2218 ascend_to(path, top_path_level);
2223 skip_initializers();
2224 DEL_ARR_F(initializers);
2225 ascend_to(path, top_path_level);
2230 * Parses an initializer. Parsers either a compound literal
2231 * (env->declaration == NULL) or an initializer of a declaration.
2233 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2235 type_t *type = skip_typeref(env->type);
2236 initializer_t *result = NULL;
2239 if(is_type_scalar(type)) {
2240 result = parse_scalar_initializer(type, env->must_be_constant);
2241 } else if(token.type == '{') {
2245 memset(&path, 0, sizeof(path));
2246 path.top_type = env->type;
2247 path.path = NEW_ARR_F(type_path_entry_t, 0);
2249 descend_into_subtype(&path);
2251 add_anchor_token('}');
2252 result = parse_sub_initializer(&path, env->type, 1, env);
2253 rem_anchor_token('}');
2255 max_index = path.max_index;
2256 DEL_ARR_F(path.path);
2260 /* parse_scalar_initializer() also works in this case: we simply
2261 * have an expression without {} around it */
2262 result = parse_scalar_initializer(type, env->must_be_constant);
2265 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2266 * the array type size */
2267 if(is_type_array(type) && type->array.size_expression == NULL
2268 && result != NULL) {
2270 switch (result->kind) {
2271 case INITIALIZER_LIST:
2272 size = max_index + 1;
2275 case INITIALIZER_STRING:
2276 size = result->string.string.size;
2279 case INITIALIZER_WIDE_STRING:
2280 size = result->wide_string.string.size;
2284 internal_errorf(HERE, "invalid initializer type");
2287 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2288 cnst->base.type = type_size_t;
2289 cnst->conste.v.int_value = size;
2291 type_t *new_type = duplicate_type(type);
2293 new_type->array.size_expression = cnst;
2294 new_type->array.size_constant = true;
2295 new_type->array.size = size;
2296 env->type = new_type;
2304 static declaration_t *append_declaration(declaration_t *declaration);
2306 static declaration_t *parse_compound_type_specifier(bool is_struct)
2314 symbol_t *symbol = NULL;
2315 declaration_t *declaration = NULL;
2317 if (token.type == T___attribute__) {
2322 if(token.type == T_IDENTIFIER) {
2323 symbol = token.v.symbol;
2327 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2329 declaration = get_declaration(symbol, NAMESPACE_UNION);
2331 } else if(token.type != '{') {
2333 parse_error_expected("while parsing struct type specifier",
2334 T_IDENTIFIER, '{', 0);
2336 parse_error_expected("while parsing union type specifier",
2337 T_IDENTIFIER, '{', 0);
2343 if(declaration == NULL) {
2344 declaration = allocate_declaration_zero();
2345 declaration->namespc =
2346 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2347 declaration->source_position = token.source_position;
2348 declaration->symbol = symbol;
2349 declaration->parent_scope = scope;
2350 if (symbol != NULL) {
2351 environment_push(declaration);
2353 append_declaration(declaration);
2356 if(token.type == '{') {
2357 if(declaration->init.is_defined) {
2358 assert(symbol != NULL);
2359 errorf(HERE, "multiple definitions of '%s %Y'",
2360 is_struct ? "struct" : "union", symbol);
2361 declaration->scope.declarations = NULL;
2363 declaration->init.is_defined = true;
2365 parse_compound_type_entries(declaration);
2372 static void parse_enum_entries(type_t *const enum_type)
2376 if(token.type == '}') {
2378 errorf(HERE, "empty enum not allowed");
2382 add_anchor_token('}');
2384 if(token.type != T_IDENTIFIER) {
2385 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2387 rem_anchor_token('}');
2391 declaration_t *const entry = allocate_declaration_zero();
2392 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2393 entry->type = enum_type;
2394 entry->symbol = token.v.symbol;
2395 entry->source_position = token.source_position;
2398 if(token.type == '=') {
2400 expression_t *value = parse_constant_expression();
2402 value = create_implicit_cast(value, enum_type);
2403 entry->init.enum_value = value;
2408 record_declaration(entry);
2410 if(token.type != ',')
2413 } while(token.type != '}');
2414 rem_anchor_token('}');
2422 static type_t *parse_enum_specifier(void)
2426 declaration_t *declaration;
2429 if(token.type == T_IDENTIFIER) {
2430 symbol = token.v.symbol;
2433 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2434 } else if(token.type != '{') {
2435 parse_error_expected("while parsing enum type specifier",
2436 T_IDENTIFIER, '{', 0);
2443 if(declaration == NULL) {
2444 declaration = allocate_declaration_zero();
2445 declaration->namespc = NAMESPACE_ENUM;
2446 declaration->source_position = token.source_position;
2447 declaration->symbol = symbol;
2448 declaration->parent_scope = scope;
2451 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2452 type->enumt.declaration = declaration;
2454 if(token.type == '{') {
2455 if(declaration->init.is_defined) {
2456 errorf(HERE, "multiple definitions of enum %Y", symbol);
2458 if (symbol != NULL) {
2459 environment_push(declaration);
2461 append_declaration(declaration);
2462 declaration->init.is_defined = 1;
2464 parse_enum_entries(type);
2472 * if a symbol is a typedef to another type, return true
2474 static bool is_typedef_symbol(symbol_t *symbol)
2476 const declaration_t *const declaration =
2477 get_declaration(symbol, NAMESPACE_NORMAL);
2479 declaration != NULL &&
2480 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2483 static type_t *parse_typeof(void)
2490 add_anchor_token(')');
2492 expression_t *expression = NULL;
2495 switch(token.type) {
2496 case T___extension__:
2497 /* this can be a prefix to a typename or an expression */
2498 /* we simply eat it now. */
2501 } while(token.type == T___extension__);
2505 if(is_typedef_symbol(token.v.symbol)) {
2506 type = parse_typename();
2508 expression = parse_expression();
2509 type = expression->base.type;
2514 type = parse_typename();
2518 expression = parse_expression();
2519 type = expression->base.type;
2523 rem_anchor_token(')');
2526 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2527 typeof_type->typeoft.expression = expression;
2528 typeof_type->typeoft.typeof_type = type;
2536 SPECIFIER_SIGNED = 1 << 0,
2537 SPECIFIER_UNSIGNED = 1 << 1,
2538 SPECIFIER_LONG = 1 << 2,
2539 SPECIFIER_INT = 1 << 3,
2540 SPECIFIER_DOUBLE = 1 << 4,
2541 SPECIFIER_CHAR = 1 << 5,
2542 SPECIFIER_SHORT = 1 << 6,
2543 SPECIFIER_LONG_LONG = 1 << 7,
2544 SPECIFIER_FLOAT = 1 << 8,
2545 SPECIFIER_BOOL = 1 << 9,
2546 SPECIFIER_VOID = 1 << 10,
2547 SPECIFIER_INT8 = 1 << 11,
2548 SPECIFIER_INT16 = 1 << 12,
2549 SPECIFIER_INT32 = 1 << 13,
2550 SPECIFIER_INT64 = 1 << 14,
2551 SPECIFIER_INT128 = 1 << 15,
2552 #ifdef PROVIDE_COMPLEX
2553 SPECIFIER_COMPLEX = 1 << 16,
2554 SPECIFIER_IMAGINARY = 1 << 17,
2558 static type_t *create_builtin_type(symbol_t *const symbol,
2559 type_t *const real_type)
2561 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2562 type->builtin.symbol = symbol;
2563 type->builtin.real_type = real_type;
2565 type_t *result = typehash_insert(type);
2566 if (type != result) {
2573 static type_t *get_typedef_type(symbol_t *symbol)
2575 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2576 if(declaration == NULL
2577 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2580 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2581 type->typedeft.declaration = declaration;
2587 * check for the allowed MS alignment values.
2589 static bool check_elignment_value(long long intvalue) {
2590 if(intvalue < 1 || intvalue > 8192) {
2591 errorf(HERE, "illegal alignment value");
2594 unsigned v = (unsigned)intvalue;
2595 for(unsigned i = 1; i <= 8192; i += i) {
2599 errorf(HERE, "alignment must be power of two");
2603 #define DET_MOD(name, tag) do { \
2604 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2605 *modifiers |= tag; \
2608 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2610 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2613 if(token.type == T_restrict) {
2615 DET_MOD(restrict, DM_RESTRICT);
2617 } else if(token.type != T_IDENTIFIER)
2619 symbol_t *symbol = token.v.symbol;
2620 if(symbol == sym_align) {
2623 if(token.type != T_INTEGER)
2625 if(check_elignment_value(token.v.intvalue)) {
2626 if(specifiers->alignment != 0)
2627 warningf(HERE, "align used more than once");
2628 specifiers->alignment = (unsigned char)token.v.intvalue;
2632 } else if(symbol == sym_allocate) {
2635 if(token.type != T_IDENTIFIER)
2637 (void)token.v.symbol;
2639 } else if(symbol == sym_dllimport) {
2641 DET_MOD(dllimport, DM_DLLIMPORT);
2642 } else if(symbol == sym_dllexport) {
2644 DET_MOD(dllexport, DM_DLLEXPORT);
2645 } else if(symbol == sym_thread) {
2647 DET_MOD(thread, DM_THREAD);
2648 } else if(symbol == sym_naked) {
2650 DET_MOD(naked, DM_NAKED);
2651 } else if(symbol == sym_noinline) {
2653 DET_MOD(noinline, DM_NOINLINE);
2654 } else if(symbol == sym_noreturn) {
2656 DET_MOD(noreturn, DM_NORETURN);
2657 } else if(symbol == sym_nothrow) {
2659 DET_MOD(nothrow, DM_NOTHROW);
2660 } else if(symbol == sym_novtable) {
2662 DET_MOD(novtable, DM_NOVTABLE);
2663 } else if(symbol == sym_property) {
2667 bool is_get = false;
2668 if(token.type != T_IDENTIFIER)
2670 if(token.v.symbol == sym_get) {
2672 } else if(token.v.symbol == sym_put) {
2674 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2679 if(token.type != T_IDENTIFIER)
2682 if(specifiers->get_property_sym != NULL) {
2683 errorf(HERE, "get property name already specified");
2685 specifiers->get_property_sym = token.v.symbol;
2688 if(specifiers->put_property_sym != NULL) {
2689 errorf(HERE, "put property name already specified");
2691 specifiers->put_property_sym = token.v.symbol;
2695 if(token.type == ',') {
2702 } else if(symbol == sym_selectany) {
2704 DET_MOD(selectany, DM_SELECTANY);
2705 } else if(symbol == sym_uuid) {
2708 if(token.type != T_STRING_LITERAL)
2712 } else if(symbol == sym_deprecated) {
2714 if(specifiers->deprecated != 0)
2715 warningf(HERE, "deprecated used more than once");
2716 specifiers->deprecated = 1;
2717 if(token.type == '(') {
2719 if(token.type == T_STRING_LITERAL) {
2720 specifiers->deprecated_string = token.v.string.begin;
2723 errorf(HERE, "string literal expected");
2727 } else if(symbol == sym_noalias) {
2729 DET_MOD(noalias, DM_NOALIAS);
2731 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2733 if(token.type == '(')
2737 if (token.type == ',')
2744 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2746 type_t *type = NULL;
2747 unsigned type_qualifiers = 0;
2748 unsigned type_specifiers = 0;
2751 specifiers->source_position = token.source_position;
2754 switch(token.type) {
2757 #define MATCH_STORAGE_CLASS(token, class) \
2759 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2760 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2762 specifiers->declared_storage_class = class; \
2766 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2767 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2768 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2769 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2770 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2775 add_anchor_token(')');
2776 parse_microsoft_extended_decl_modifier(specifiers);
2777 rem_anchor_token(')');
2782 switch (specifiers->declared_storage_class) {
2783 case STORAGE_CLASS_NONE:
2784 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2787 case STORAGE_CLASS_EXTERN:
2788 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2791 case STORAGE_CLASS_STATIC:
2792 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2796 errorf(HERE, "multiple storage classes in declaration specifiers");
2802 /* type qualifiers */
2803 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2805 type_qualifiers |= qualifier; \
2809 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2810 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2811 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2812 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2813 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2814 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2815 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2816 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2818 case T___extension__:
2823 /* type specifiers */
2824 #define MATCH_SPECIFIER(token, specifier, name) \
2827 if(type_specifiers & specifier) { \
2828 errorf(HERE, "multiple " name " type specifiers given"); \
2830 type_specifiers |= specifier; \
2834 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2835 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2836 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2837 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2838 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2839 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2840 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2841 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2842 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2843 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2844 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2845 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2846 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2847 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2848 #ifdef PROVIDE_COMPLEX
2849 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2850 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2852 case T__forceinline:
2853 /* only in microsoft mode */
2854 specifiers->decl_modifiers |= DM_FORCEINLINE;
2858 specifiers->is_inline = true;
2863 if(type_specifiers & SPECIFIER_LONG_LONG) {
2864 errorf(HERE, "multiple type specifiers given");
2865 } else if(type_specifiers & SPECIFIER_LONG) {
2866 type_specifiers |= SPECIFIER_LONG_LONG;
2868 type_specifiers |= SPECIFIER_LONG;
2873 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2875 type->compound.declaration = parse_compound_type_specifier(true);
2879 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2881 type->compound.declaration = parse_compound_type_specifier(false);
2885 type = parse_enum_specifier();
2888 type = parse_typeof();
2890 case T___builtin_va_list:
2891 type = duplicate_type(type_valist);
2895 case T___attribute__:
2899 case T_IDENTIFIER: {
2900 /* only parse identifier if we haven't found a type yet */
2901 if(type != NULL || type_specifiers != 0)
2902 goto finish_specifiers;
2904 type_t *typedef_type = get_typedef_type(token.v.symbol);
2906 if(typedef_type == NULL)
2907 goto finish_specifiers;
2910 type = typedef_type;
2914 /* function specifier */
2916 goto finish_specifiers;
2923 atomic_type_kind_t atomic_type;
2925 /* match valid basic types */
2926 switch(type_specifiers) {
2927 case SPECIFIER_VOID:
2928 atomic_type = ATOMIC_TYPE_VOID;
2930 case SPECIFIER_CHAR:
2931 atomic_type = ATOMIC_TYPE_CHAR;
2933 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2934 atomic_type = ATOMIC_TYPE_SCHAR;
2936 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2937 atomic_type = ATOMIC_TYPE_UCHAR;
2939 case SPECIFIER_SHORT:
2940 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2941 case SPECIFIER_SHORT | SPECIFIER_INT:
2942 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2943 atomic_type = ATOMIC_TYPE_SHORT;
2945 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2946 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2947 atomic_type = ATOMIC_TYPE_USHORT;
2950 case SPECIFIER_SIGNED:
2951 case SPECIFIER_SIGNED | SPECIFIER_INT:
2952 atomic_type = ATOMIC_TYPE_INT;
2954 case SPECIFIER_UNSIGNED:
2955 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2956 atomic_type = ATOMIC_TYPE_UINT;
2958 case SPECIFIER_LONG:
2959 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2960 case SPECIFIER_LONG | SPECIFIER_INT:
2961 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2962 atomic_type = ATOMIC_TYPE_LONG;
2964 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2965 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2966 atomic_type = ATOMIC_TYPE_ULONG;
2968 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2969 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2970 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2971 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2973 atomic_type = ATOMIC_TYPE_LONGLONG;
2975 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2976 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2978 atomic_type = ATOMIC_TYPE_ULONGLONG;
2981 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2982 atomic_type = unsigned_int8_type_kind;
2985 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2986 atomic_type = unsigned_int16_type_kind;
2989 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2990 atomic_type = unsigned_int32_type_kind;
2993 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2994 atomic_type = unsigned_int64_type_kind;
2997 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2998 atomic_type = unsigned_int128_type_kind;
3001 case SPECIFIER_INT8:
3002 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3003 atomic_type = int8_type_kind;
3006 case SPECIFIER_INT16:
3007 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3008 atomic_type = int16_type_kind;
3011 case SPECIFIER_INT32:
3012 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3013 atomic_type = int32_type_kind;
3016 case SPECIFIER_INT64:
3017 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3018 atomic_type = int64_type_kind;
3021 case SPECIFIER_INT128:
3022 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3023 atomic_type = int128_type_kind;
3026 case SPECIFIER_FLOAT:
3027 atomic_type = ATOMIC_TYPE_FLOAT;
3029 case SPECIFIER_DOUBLE:
3030 atomic_type = ATOMIC_TYPE_DOUBLE;
3032 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3033 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3035 case SPECIFIER_BOOL:
3036 atomic_type = ATOMIC_TYPE_BOOL;
3038 #ifdef PROVIDE_COMPLEX
3039 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3040 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
3042 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3043 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
3045 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3046 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
3048 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3049 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
3051 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3052 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
3054 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3055 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
3059 /* invalid specifier combination, give an error message */
3060 if(type_specifiers == 0) {
3061 if (! strict_mode) {
3062 if (warning.implicit_int) {
3063 warningf(HERE, "no type specifiers in declaration, using 'int'");
3065 atomic_type = ATOMIC_TYPE_INT;
3068 errorf(HERE, "no type specifiers given in declaration");
3070 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3071 (type_specifiers & SPECIFIER_UNSIGNED)) {
3072 errorf(HERE, "signed and unsigned specifiers gives");
3073 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3074 errorf(HERE, "only integer types can be signed or unsigned");
3076 errorf(HERE, "multiple datatypes in declaration");
3078 atomic_type = ATOMIC_TYPE_INVALID;
3081 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
3082 type->atomic.akind = atomic_type;
3085 if(type_specifiers != 0) {
3086 errorf(HERE, "multiple datatypes in declaration");
3090 type->base.qualifiers = type_qualifiers;
3091 /* FIXME: check type qualifiers here */
3093 type_t *result = typehash_insert(type);
3094 if(newtype && result != type) {
3098 specifiers->type = result;
3103 static type_qualifiers_t parse_type_qualifiers(void)
3105 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3108 switch(token.type) {
3109 /* type qualifiers */
3110 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3111 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3112 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3113 /* microsoft extended type modifiers */
3114 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3115 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3116 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3117 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3118 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3121 return type_qualifiers;
3126 static declaration_t *parse_identifier_list(void)
3128 declaration_t *declarations = NULL;
3129 declaration_t *last_declaration = NULL;
3131 declaration_t *const declaration = allocate_declaration_zero();
3132 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3133 declaration->source_position = token.source_position;
3134 declaration->symbol = token.v.symbol;
3137 if(last_declaration != NULL) {
3138 last_declaration->next = declaration;
3140 declarations = declaration;
3142 last_declaration = declaration;
3144 if(token.type != ',')
3147 } while(token.type == T_IDENTIFIER);
3149 return declarations;
3152 static void semantic_parameter(declaration_t *declaration)
3154 /* TODO: improve error messages */
3156 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3157 errorf(HERE, "typedef not allowed in parameter list");
3158 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3159 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3160 errorf(HERE, "parameter may only have none or register storage class");
3163 type_t *const orig_type = declaration->type;
3164 type_t * type = skip_typeref(orig_type);
3166 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3167 * into a pointer. § 6.7.5.3 (7) */
3168 if (is_type_array(type)) {
3169 type_t *const element_type = type->array.element_type;
3171 type = make_pointer_type(element_type, type->base.qualifiers);
3173 declaration->type = type;
3176 if(is_type_incomplete(type)) {
3177 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3178 orig_type, declaration->symbol);
3182 static declaration_t *parse_parameter(void)
3184 declaration_specifiers_t specifiers;
3185 memset(&specifiers, 0, sizeof(specifiers));
3187 parse_declaration_specifiers(&specifiers);
3189 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3191 semantic_parameter(declaration);
3196 static declaration_t *parse_parameters(function_type_t *type)
3198 if(token.type == T_IDENTIFIER) {
3199 symbol_t *symbol = token.v.symbol;
3200 if(!is_typedef_symbol(symbol)) {
3201 type->kr_style_parameters = true;
3202 return parse_identifier_list();
3206 if(token.type == ')') {
3207 type->unspecified_parameters = 1;
3210 if(token.type == T_void && look_ahead(1)->type == ')') {
3215 declaration_t *declarations = NULL;
3216 declaration_t *declaration;
3217 declaration_t *last_declaration = NULL;
3218 function_parameter_t *parameter;
3219 function_parameter_t *last_parameter = NULL;
3222 switch(token.type) {
3226 return declarations;
3229 case T___extension__:
3231 declaration = parse_parameter();
3233 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3234 memset(parameter, 0, sizeof(parameter[0]));
3235 parameter->type = declaration->type;
3237 if(last_parameter != NULL) {
3238 last_declaration->next = declaration;
3239 last_parameter->next = parameter;
3241 type->parameters = parameter;
3242 declarations = declaration;
3244 last_parameter = parameter;
3245 last_declaration = declaration;
3249 return declarations;
3251 if(token.type != ',')
3252 return declarations;
3262 } construct_type_kind_t;
3264 typedef struct construct_type_t construct_type_t;
3265 struct construct_type_t {
3266 construct_type_kind_t kind;
3267 construct_type_t *next;
3270 typedef struct parsed_pointer_t parsed_pointer_t;
3271 struct parsed_pointer_t {
3272 construct_type_t construct_type;
3273 type_qualifiers_t type_qualifiers;
3276 typedef struct construct_function_type_t construct_function_type_t;
3277 struct construct_function_type_t {
3278 construct_type_t construct_type;
3279 type_t *function_type;
3282 typedef struct parsed_array_t parsed_array_t;
3283 struct parsed_array_t {
3284 construct_type_t construct_type;
3285 type_qualifiers_t type_qualifiers;
3291 typedef struct construct_base_type_t construct_base_type_t;
3292 struct construct_base_type_t {
3293 construct_type_t construct_type;
3297 static construct_type_t *parse_pointer_declarator(void)
3301 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3302 memset(pointer, 0, sizeof(pointer[0]));
3303 pointer->construct_type.kind = CONSTRUCT_POINTER;
3304 pointer->type_qualifiers = parse_type_qualifiers();
3306 return (construct_type_t*) pointer;
3309 static construct_type_t *parse_array_declarator(void)
3312 add_anchor_token(']');
3314 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3315 memset(array, 0, sizeof(array[0]));
3316 array->construct_type.kind = CONSTRUCT_ARRAY;
3318 if(token.type == T_static) {
3319 array->is_static = true;
3323 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3324 if(type_qualifiers != 0) {
3325 if(token.type == T_static) {
3326 array->is_static = true;
3330 array->type_qualifiers = type_qualifiers;
3332 if(token.type == '*' && look_ahead(1)->type == ']') {
3333 array->is_variable = true;
3335 } else if(token.type != ']') {
3336 array->size = parse_assignment_expression();
3339 rem_anchor_token(']');
3342 return (construct_type_t*) array;
3347 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3350 add_anchor_token(')');
3353 if(declaration != NULL) {
3354 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
3356 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
3359 declaration_t *parameters = parse_parameters(&type->function);
3360 if(declaration != NULL) {
3361 declaration->scope.declarations = parameters;
3364 construct_function_type_t *construct_function_type =
3365 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3366 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3367 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3368 construct_function_type->function_type = type;
3370 rem_anchor_token(')');
3374 return (construct_type_t*) construct_function_type;
3377 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3378 bool may_be_abstract)
3380 /* construct a single linked list of construct_type_t's which describe
3381 * how to construct the final declarator type */
3382 construct_type_t *first = NULL;
3383 construct_type_t *last = NULL;
3386 while(token.type == '*') {
3387 construct_type_t *type = parse_pointer_declarator();
3398 /* TODO: find out if this is correct */
3401 construct_type_t *inner_types = NULL;
3403 switch(token.type) {
3405 if(declaration == NULL) {
3406 errorf(HERE, "no identifier expected in typename");
3408 declaration->symbol = token.v.symbol;
3409 declaration->source_position = token.source_position;
3415 add_anchor_token(')');
3416 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3417 rem_anchor_token(')');
3423 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3424 /* avoid a loop in the outermost scope, because eat_statement doesn't
3426 if(token.type == '}' && current_function == NULL) {
3434 construct_type_t *p = last;
3437 construct_type_t *type;
3438 switch(token.type) {
3440 type = parse_function_declarator(declaration);
3443 type = parse_array_declarator();
3446 goto declarator_finished;
3449 /* insert in the middle of the list (behind p) */
3451 type->next = p->next;
3462 declarator_finished:
3465 /* append inner_types at the end of the list, we don't to set last anymore
3466 * as it's not needed anymore */
3468 assert(first == NULL);
3469 first = inner_types;
3471 last->next = inner_types;
3479 static type_t *construct_declarator_type(construct_type_t *construct_list,
3482 construct_type_t *iter = construct_list;
3483 for( ; iter != NULL; iter = iter->next) {
3484 switch(iter->kind) {
3485 case CONSTRUCT_INVALID:
3486 internal_errorf(HERE, "invalid type construction found");
3487 case CONSTRUCT_FUNCTION: {
3488 construct_function_type_t *construct_function_type
3489 = (construct_function_type_t*) iter;
3491 type_t *function_type = construct_function_type->function_type;
3493 function_type->function.return_type = type;
3495 type_t *skipped_return_type = skip_typeref(type);
3496 if (is_type_function(skipped_return_type)) {
3497 errorf(HERE, "function returning function is not allowed");
3498 type = type_error_type;
3499 } else if (is_type_array(skipped_return_type)) {
3500 errorf(HERE, "function returning array is not allowed");
3501 type = type_error_type;
3503 type = function_type;
3508 case CONSTRUCT_POINTER: {
3509 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3510 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3511 pointer_type->pointer.points_to = type;
3512 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3514 type = pointer_type;
3518 case CONSTRUCT_ARRAY: {
3519 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3520 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3522 expression_t *size_expression = parsed_array->size;
3523 if(size_expression != NULL) {
3525 = create_implicit_cast(size_expression, type_size_t);
3528 array_type->base.qualifiers = parsed_array->type_qualifiers;
3529 array_type->array.element_type = type;
3530 array_type->array.is_static = parsed_array->is_static;
3531 array_type->array.is_variable = parsed_array->is_variable;
3532 array_type->array.size_expression = size_expression;
3534 if(size_expression != NULL) {
3535 if(is_constant_expression(size_expression)) {
3536 array_type->array.size_constant = true;
3537 array_type->array.size
3538 = fold_constant(size_expression);
3540 array_type->array.is_vla = true;
3544 type_t *skipped_type = skip_typeref(type);
3545 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3546 errorf(HERE, "array of void is not allowed");
3547 type = type_error_type;
3555 type_t *hashed_type = typehash_insert(type);
3556 if(hashed_type != type) {
3557 /* the function type was constructed earlier freeing it here will
3558 * destroy other types... */
3559 if(iter->kind != CONSTRUCT_FUNCTION) {
3569 static declaration_t *parse_declarator(
3570 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3572 declaration_t *const declaration = allocate_declaration_zero();
3573 declaration->declared_storage_class = specifiers->declared_storage_class;
3574 declaration->modifiers = specifiers->decl_modifiers;
3575 declaration->deprecated = specifiers->deprecated;
3576 declaration->deprecated_string = specifiers->deprecated_string;
3577 declaration->get_property_sym = specifiers->get_property_sym;
3578 declaration->put_property_sym = specifiers->put_property_sym;
3579 declaration->is_inline = specifiers->is_inline;
3581 declaration->storage_class = specifiers->declared_storage_class;
3582 if(declaration->storage_class == STORAGE_CLASS_NONE
3583 && scope != global_scope) {
3584 declaration->storage_class = STORAGE_CLASS_AUTO;
3587 if(specifiers->alignment != 0) {
3588 /* TODO: add checks here */
3589 declaration->alignment = specifiers->alignment;
3592 construct_type_t *construct_type
3593 = parse_inner_declarator(declaration, may_be_abstract);
3594 type_t *const type = specifiers->type;
3595 declaration->type = construct_declarator_type(construct_type, type);
3597 if(construct_type != NULL) {
3598 obstack_free(&temp_obst, construct_type);
3604 static type_t *parse_abstract_declarator(type_t *base_type)
3606 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3608 type_t *result = construct_declarator_type(construct_type, base_type);
3609 if(construct_type != NULL) {
3610 obstack_free(&temp_obst, construct_type);
3616 static declaration_t *append_declaration(declaration_t* const declaration)
3618 if (last_declaration != NULL) {
3619 last_declaration->next = declaration;
3621 scope->declarations = declaration;
3623 last_declaration = declaration;
3628 * Check if the declaration of main is suspicious. main should be a
3629 * function with external linkage, returning int, taking either zero
3630 * arguments, two, or three arguments of appropriate types, ie.
3632 * int main([ int argc, char **argv [, char **env ] ]).
3634 * @param decl the declaration to check
3635 * @param type the function type of the declaration
3637 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3639 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3640 warningf(decl->source_position, "'main' is normally a non-static function");
3642 if (skip_typeref(func_type->return_type) != type_int) {
3643 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3645 const function_parameter_t *parm = func_type->parameters;
3647 type_t *const first_type = parm->type;
3648 if (!types_compatible(skip_typeref(first_type), type_int)) {
3649 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3653 type_t *const second_type = parm->type;
3654 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3655 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3659 type_t *const third_type = parm->type;
3660 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3661 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3665 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3669 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3675 * Check if a symbol is the equal to "main".
3677 static bool is_sym_main(const symbol_t *const sym)
3679 return strcmp(sym->string, "main") == 0;
3682 static declaration_t *internal_record_declaration(
3683 declaration_t *const declaration,
3684 const bool is_function_definition)
3686 const symbol_t *const symbol = declaration->symbol;
3687 const namespace_t namespc = (namespace_t)declaration->namespc;
3689 type_t *const orig_type = declaration->type;
3690 type_t *const type = skip_typeref(orig_type);
3691 if (is_type_function(type) &&
3692 type->function.unspecified_parameters &&
3693 warning.strict_prototypes) {
3694 warningf(declaration->source_position,
3695 "function declaration '%#T' is not a prototype",
3696 orig_type, declaration->symbol);
3699 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3700 check_type_of_main(declaration, &type->function);
3703 assert(declaration->symbol != NULL);
3704 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3706 assert(declaration != previous_declaration);
3707 if (previous_declaration != NULL) {
3708 if (previous_declaration->parent_scope == scope) {
3709 /* can happen for K&R style declarations */
3710 if(previous_declaration->type == NULL) {
3711 previous_declaration->type = declaration->type;
3714 const type_t *prev_type = skip_typeref(previous_declaration->type);
3715 if (!types_compatible(type, prev_type)) {
3716 errorf(declaration->source_position,
3717 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3718 orig_type, symbol, previous_declaration->type, symbol,
3719 previous_declaration->source_position);
3721 unsigned old_storage_class = previous_declaration->storage_class;
3722 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3723 errorf(declaration->source_position, "redeclaration of enum entry '%Y' (declared %P)",
3724 symbol, previous_declaration->source_position);
3725 return previous_declaration;
3728 unsigned new_storage_class = declaration->storage_class;
3730 if(is_type_incomplete(prev_type)) {
3731 previous_declaration->type = type;
3735 /* pretend no storage class means extern for function
3736 * declarations (except if the previous declaration is neither
3737 * none nor extern) */
3738 if (is_type_function(type)) {
3739 switch (old_storage_class) {
3740 case STORAGE_CLASS_NONE:
3741 old_storage_class = STORAGE_CLASS_EXTERN;
3743 case STORAGE_CLASS_EXTERN:
3744 if (is_function_definition) {
3745 if (warning.missing_prototypes &&
3746 prev_type->function.unspecified_parameters &&
3747 !is_sym_main(symbol)) {
3748 warningf(declaration->source_position,
3749 "no previous prototype for '%#T'",
3752 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3753 new_storage_class = STORAGE_CLASS_EXTERN;
3761 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3762 new_storage_class == STORAGE_CLASS_EXTERN) {
3763 warn_redundant_declaration:
3764 if (warning.redundant_decls) {
3765 warningf(declaration->source_position,
3766 "redundant declaration for '%Y' (declared %P)",
3767 symbol, previous_declaration->source_position);
3769 } else if (current_function == NULL) {
3770 if (old_storage_class != STORAGE_CLASS_STATIC &&
3771 new_storage_class == STORAGE_CLASS_STATIC) {
3772 errorf(declaration->source_position,
3773 "static declaration of '%Y' follows non-static declaration (declared %P)",
3774 symbol, previous_declaration->source_position);
3776 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3777 goto warn_redundant_declaration;
3779 if (new_storage_class == STORAGE_CLASS_NONE) {
3780 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3781 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3785 if (old_storage_class == new_storage_class) {
3786 errorf(declaration->source_position,
3787 "redeclaration of '%Y' (declared %P)",
3788 symbol, previous_declaration->source_position);
3790 errorf(declaration->source_position,
3791 "redeclaration of '%Y' with different linkage (declared %P)",
3792 symbol, previous_declaration->source_position);
3796 return previous_declaration;
3798 } else if (is_function_definition) {
3799 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3800 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3801 warningf(declaration->source_position,
3802 "no previous prototype for '%#T'", orig_type, symbol);
3803 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3804 warningf(declaration->source_position,
3805 "no previous declaration for '%#T'", orig_type,
3809 } else if (warning.missing_declarations &&
3810 scope == global_scope &&
3811 !is_type_function(type) && (
3812 declaration->storage_class == STORAGE_CLASS_NONE ||
3813 declaration->storage_class == STORAGE_CLASS_THREAD
3815 warningf(declaration->source_position,
3816 "no previous declaration for '%#T'", orig_type, symbol);
3819 assert(declaration->parent_scope == NULL);
3820 assert(scope != NULL);
3822 declaration->parent_scope = scope;
3824 environment_push(declaration);
3825 return append_declaration(declaration);
3828 static declaration_t *record_declaration(declaration_t *declaration)
3830 return internal_record_declaration(declaration, false);
3833 static declaration_t *record_function_definition(declaration_t *declaration)
3835 return internal_record_declaration(declaration, true);
3838 static void parser_error_multiple_definition(declaration_t *declaration,
3839 const source_position_t source_position)
3841 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
3842 declaration->symbol, declaration->source_position);
3845 static bool is_declaration_specifier(const token_t *token,
3846 bool only_type_specifiers)
3848 switch(token->type) {
3852 return is_typedef_symbol(token->v.symbol);
3854 case T___extension__:
3857 return !only_type_specifiers;
3864 static void parse_init_declarator_rest(declaration_t *declaration)
3868 type_t *orig_type = declaration->type;
3869 type_t *type = skip_typeref(orig_type);
3871 if(declaration->init.initializer != NULL) {
3872 parser_error_multiple_definition(declaration, token.source_position);
3875 bool must_be_constant = false;
3876 if(declaration->storage_class == STORAGE_CLASS_STATIC
3877 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3878 || declaration->parent_scope == global_scope) {
3879 must_be_constant = true;
3882 parse_initializer_env_t env;
3883 env.type = orig_type;
3884 env.must_be_constant = must_be_constant;
3885 env.declaration = declaration;
3887 initializer_t *initializer = parse_initializer(&env);
3889 if(env.type != orig_type) {
3890 orig_type = env.type;
3891 type = skip_typeref(orig_type);
3892 declaration->type = env.type;
3895 if(is_type_function(type)) {
3896 errorf(declaration->source_position,
3897 "initializers not allowed for function types at declator '%Y' (type '%T')",
3898 declaration->symbol, orig_type);
3900 declaration->init.initializer = initializer;
3904 /* parse rest of a declaration without any declarator */
3905 static void parse_anonymous_declaration_rest(
3906 const declaration_specifiers_t *specifiers,
3907 parsed_declaration_func finished_declaration)
3911 declaration_t *const declaration = allocate_declaration_zero();
3912 declaration->type = specifiers->type;
3913 declaration->declared_storage_class = specifiers->declared_storage_class;
3914 declaration->source_position = specifiers->source_position;
3915 declaration->modifiers = specifiers->decl_modifiers;
3917 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3918 warningf(declaration->source_position, "useless storage class in empty declaration");
3920 declaration->storage_class = STORAGE_CLASS_NONE;
3922 type_t *type = declaration->type;
3923 switch (type->kind) {
3924 case TYPE_COMPOUND_STRUCT:
3925 case TYPE_COMPOUND_UNION: {
3926 if (type->compound.declaration->symbol == NULL) {
3927 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3936 warningf(declaration->source_position, "empty declaration");
3940 finished_declaration(declaration);
3943 static void parse_declaration_rest(declaration_t *ndeclaration,
3944 const declaration_specifiers_t *specifiers,
3945 parsed_declaration_func finished_declaration)
3947 add_anchor_token(';');
3948 add_anchor_token('=');
3949 add_anchor_token(',');
3951 declaration_t *declaration = finished_declaration(ndeclaration);
3953 type_t *orig_type = declaration->type;
3954 type_t *type = skip_typeref(orig_type);
3956 if (type->kind != TYPE_FUNCTION &&
3957 declaration->is_inline &&
3958 is_type_valid(type)) {
3959 warningf(declaration->source_position,
3960 "variable '%Y' declared 'inline'\n", declaration->symbol);
3963 if(token.type == '=') {
3964 parse_init_declarator_rest(declaration);
3967 if(token.type != ',')
3971 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3976 rem_anchor_token(';');
3977 rem_anchor_token('=');
3978 rem_anchor_token(',');
3981 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3983 symbol_t *symbol = declaration->symbol;
3984 if(symbol == NULL) {
3985 errorf(HERE, "anonymous declaration not valid as function parameter");
3988 namespace_t namespc = (namespace_t) declaration->namespc;
3989 if(namespc != NAMESPACE_NORMAL) {
3990 return record_declaration(declaration);
3993 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3994 if(previous_declaration == NULL ||
3995 previous_declaration->parent_scope != scope) {
3996 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4001 if(previous_declaration->type == NULL) {
4002 previous_declaration->type = declaration->type;
4003 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4004 previous_declaration->storage_class = declaration->storage_class;
4005 previous_declaration->parent_scope = scope;
4006 return previous_declaration;
4008 return record_declaration(declaration);
4012 static void parse_declaration(parsed_declaration_func finished_declaration)
4014 declaration_specifiers_t specifiers;
4015 memset(&specifiers, 0, sizeof(specifiers));
4016 parse_declaration_specifiers(&specifiers);
4018 if(token.type == ';') {
4019 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4021 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4022 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4026 static void parse_kr_declaration_list(declaration_t *declaration)
4028 type_t *type = skip_typeref(declaration->type);
4029 if(!is_type_function(type))
4032 if(!type->function.kr_style_parameters)
4035 /* push function parameters */
4036 int top = environment_top();
4037 scope_t *last_scope = scope;
4038 set_scope(&declaration->scope);
4040 declaration_t *parameter = declaration->scope.declarations;
4041 for( ; parameter != NULL; parameter = parameter->next) {
4042 assert(parameter->parent_scope == NULL);
4043 parameter->parent_scope = scope;
4044 environment_push(parameter);
4047 /* parse declaration list */
4048 while(is_declaration_specifier(&token, false)) {
4049 parse_declaration(finished_kr_declaration);
4052 /* pop function parameters */
4053 assert(scope == &declaration->scope);
4054 set_scope(last_scope);
4055 environment_pop_to(top);
4057 /* update function type */
4058 type_t *new_type = duplicate_type(type);
4059 new_type->function.kr_style_parameters = false;
4061 function_parameter_t *parameters = NULL;
4062 function_parameter_t *last_parameter = NULL;
4064 declaration_t *parameter_declaration = declaration->scope.declarations;
4065 for( ; parameter_declaration != NULL;
4066 parameter_declaration = parameter_declaration->next) {
4067 type_t *parameter_type = parameter_declaration->type;
4068 if(parameter_type == NULL) {
4070 errorf(HERE, "no type specified for function parameter '%Y'",
4071 parameter_declaration->symbol);
4073 if (warning.implicit_int) {
4074 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4075 parameter_declaration->symbol);
4077 parameter_type = type_int;
4078 parameter_declaration->type = parameter_type;
4082 semantic_parameter(parameter_declaration);
4083 parameter_type = parameter_declaration->type;
4085 function_parameter_t *function_parameter
4086 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4087 memset(function_parameter, 0, sizeof(function_parameter[0]));
4089 function_parameter->type = parameter_type;
4090 if(last_parameter != NULL) {
4091 last_parameter->next = function_parameter;
4093 parameters = function_parameter;
4095 last_parameter = function_parameter;
4097 new_type->function.parameters = parameters;
4099 type = typehash_insert(new_type);
4100 if(type != new_type) {
4101 obstack_free(type_obst, new_type);
4104 declaration->type = type;
4107 static bool first_err = true;
4110 * When called with first_err set, prints the name of the current function,
4113 static void print_in_function(void) {
4116 diagnosticf("%s: In function '%Y':\n",
4117 current_function->source_position.input_name,
4118 current_function->symbol);
4123 * Check if all labels are defined in the current function.
4124 * Check if all labels are used in the current function.
4126 static void check_labels(void)
4128 for (const goto_statement_t *goto_statement = goto_first;
4129 goto_statement != NULL;
4130 goto_statement = goto_statement->next) {
4131 declaration_t *label = goto_statement->label;
4134 if (label->source_position.input_name == NULL) {
4135 print_in_function();
4136 errorf(goto_statement->base.source_position,
4137 "label '%Y' used but not defined", label->symbol);
4140 goto_first = goto_last = NULL;
4142 if (warning.unused_label) {
4143 for (const label_statement_t *label_statement = label_first;
4144 label_statement != NULL;
4145 label_statement = label_statement->next) {
4146 const declaration_t *label = label_statement->label;
4148 if (! label->used) {
4149 print_in_function();
4150 warningf(label_statement->base.source_position,
4151 "label '%Y' defined but not used", label->symbol);
4155 label_first = label_last = NULL;
4159 * Check declarations of current_function for unused entities.
4161 static void check_declarations(void)
4163 if (warning.unused_parameter) {
4164 const scope_t *scope = ¤t_function->scope;
4166 const declaration_t *parameter = scope->declarations;
4167 for (; parameter != NULL; parameter = parameter->next) {
4168 if (! parameter->used) {
4169 print_in_function();
4170 warningf(parameter->source_position,
4171 "unused parameter '%Y'", parameter->symbol);
4175 if (warning.unused_variable) {
4179 static void parse_external_declaration(void)
4181 /* function-definitions and declarations both start with declaration
4183 declaration_specifiers_t specifiers;
4184 memset(&specifiers, 0, sizeof(specifiers));
4186 add_anchor_token(';');
4187 parse_declaration_specifiers(&specifiers);
4188 rem_anchor_token(';');
4190 /* must be a declaration */
4191 if(token.type == ';') {
4192 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4196 add_anchor_token(',');
4197 add_anchor_token('=');
4198 rem_anchor_token(';');
4200 /* declarator is common to both function-definitions and declarations */
4201 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4203 rem_anchor_token(',');
4204 rem_anchor_token('=');
4205 rem_anchor_token(';');
4207 /* must be a declaration */
4208 if(token.type == ',' || token.type == '=' || token.type == ';') {
4209 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4213 /* must be a function definition */
4214 parse_kr_declaration_list(ndeclaration);
4216 if(token.type != '{') {
4217 parse_error_expected("while parsing function definition", '{', 0);
4218 eat_until_matching_token(';');
4222 type_t *type = ndeclaration->type;
4224 /* note that we don't skip typerefs: the standard doesn't allow them here
4225 * (so we can't use is_type_function here) */
4226 if(type->kind != TYPE_FUNCTION) {
4227 if (is_type_valid(type)) {
4228 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4229 type, ndeclaration->symbol);
4235 /* § 6.7.5.3 (14) a function definition with () means no
4236 * parameters (and not unspecified parameters) */
4237 if(type->function.unspecified_parameters) {
4238 type_t *duplicate = duplicate_type(type);
4239 duplicate->function.unspecified_parameters = false;
4241 type = typehash_insert(duplicate);
4242 if(type != duplicate) {
4243 obstack_free(type_obst, duplicate);
4245 ndeclaration->type = type;
4248 declaration_t *const declaration = record_function_definition(ndeclaration);
4249 if(ndeclaration != declaration) {
4250 declaration->scope = ndeclaration->scope;
4252 type = skip_typeref(declaration->type);
4254 /* push function parameters and switch scope */
4255 int top = environment_top();
4256 scope_t *last_scope = scope;
4257 set_scope(&declaration->scope);
4259 declaration_t *parameter = declaration->scope.declarations;
4260 for( ; parameter != NULL; parameter = parameter->next) {
4261 if(parameter->parent_scope == &ndeclaration->scope) {
4262 parameter->parent_scope = scope;
4264 assert(parameter->parent_scope == NULL
4265 || parameter->parent_scope == scope);
4266 parameter->parent_scope = scope;
4267 environment_push(parameter);
4270 if(declaration->init.statement != NULL) {
4271 parser_error_multiple_definition(declaration, token.source_position);
4273 goto end_of_parse_external_declaration;
4275 /* parse function body */
4276 int label_stack_top = label_top();
4277 declaration_t *old_current_function = current_function;
4278 current_function = declaration;
4280 declaration->init.statement = parse_compound_statement();
4283 check_declarations();
4285 assert(current_function == declaration);
4286 current_function = old_current_function;
4287 label_pop_to(label_stack_top);
4290 end_of_parse_external_declaration:
4291 assert(scope == &declaration->scope);
4292 set_scope(last_scope);
4293 environment_pop_to(top);
4296 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4297 source_position_t source_position)
4299 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4300 type->bitfield.base = base;
4301 type->bitfield.size = size;
4306 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4309 declaration_t *iter = compound_declaration->scope.declarations;
4310 for( ; iter != NULL; iter = iter->next) {
4311 if(iter->namespc != NAMESPACE_NORMAL)
4314 if(iter->symbol == NULL) {
4315 type_t *type = skip_typeref(iter->type);
4316 if(is_type_compound(type)) {
4317 declaration_t *result
4318 = find_compound_entry(type->compound.declaration, symbol);
4325 if(iter->symbol == symbol) {
4333 static void parse_compound_declarators(declaration_t *struct_declaration,
4334 const declaration_specifiers_t *specifiers)
4336 declaration_t *last_declaration = struct_declaration->scope.declarations;
4337 if(last_declaration != NULL) {
4338 while(last_declaration->next != NULL) {
4339 last_declaration = last_declaration->next;
4344 declaration_t *declaration;
4346 if(token.type == ':') {
4347 source_position_t source_position = HERE;
4350 type_t *base_type = specifiers->type;
4351 expression_t *size = parse_constant_expression();
4353 if(!is_type_integer(skip_typeref(base_type))) {
4354 errorf(HERE, "bitfield base type '%T' is not an integer type",
4358 type_t *type = make_bitfield_type(base_type, size, source_position);
4360 declaration = allocate_declaration_zero();
4361 declaration->namespc = NAMESPACE_NORMAL;
4362 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4363 declaration->storage_class = STORAGE_CLASS_NONE;
4364 declaration->source_position = source_position;
4365 declaration->modifiers = specifiers->decl_modifiers;
4366 declaration->type = type;
4368 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4370 type_t *orig_type = declaration->type;
4371 type_t *type = skip_typeref(orig_type);
4373 if(token.type == ':') {
4374 source_position_t source_position = HERE;
4376 expression_t *size = parse_constant_expression();
4378 if(!is_type_integer(type)) {
4379 errorf(HERE, "bitfield base type '%T' is not an "
4380 "integer type", orig_type);
4383 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
4384 declaration->type = bitfield_type;
4386 /* TODO we ignore arrays for now... what is missing is a check
4387 * that they're at the end of the struct */
4388 if(is_type_incomplete(type) && !is_type_array(type)) {
4390 "compound member '%Y' has incomplete type '%T'",
4391 declaration->symbol, orig_type);
4392 } else if(is_type_function(type)) {
4393 errorf(HERE, "compound member '%Y' must not have function "
4394 "type '%T'", declaration->symbol, orig_type);
4399 /* make sure we don't define a symbol multiple times */
4400 symbol_t *symbol = declaration->symbol;
4401 if(symbol != NULL) {
4402 declaration_t *prev_decl
4403 = find_compound_entry(struct_declaration, symbol);
4405 if(prev_decl != NULL) {
4406 assert(prev_decl->symbol == symbol);
4407 errorf(declaration->source_position,
4408 "multiple declarations of symbol '%Y' (declared %P)",
4409 symbol, prev_decl->source_position);
4413 /* append declaration */
4414 if(last_declaration != NULL) {
4415 last_declaration->next = declaration;
4417 struct_declaration->scope.declarations = declaration;
4419 last_declaration = declaration;
4421 if(token.type != ',')
4431 static void parse_compound_type_entries(declaration_t *compound_declaration)
4434 add_anchor_token('}');
4436 while(token.type != '}' && token.type != T_EOF) {
4437 declaration_specifiers_t specifiers;
4438 memset(&specifiers, 0, sizeof(specifiers));
4439 parse_declaration_specifiers(&specifiers);
4441 parse_compound_declarators(compound_declaration, &specifiers);
4443 rem_anchor_token('}');
4445 if(token.type == T_EOF) {
4446 errorf(HERE, "EOF while parsing struct");
4451 static type_t *parse_typename(void)
4453 declaration_specifiers_t specifiers;
4454 memset(&specifiers, 0, sizeof(specifiers));
4455 parse_declaration_specifiers(&specifiers);
4456 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4457 /* TODO: improve error message, user does probably not know what a
4458 * storage class is...
4460 errorf(HERE, "typename may not have a storage class");
4463 type_t *result = parse_abstract_declarator(specifiers.type);
4471 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4472 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4473 expression_t *left);
4475 typedef struct expression_parser_function_t expression_parser_function_t;
4476 struct expression_parser_function_t {
4477 unsigned precedence;
4478 parse_expression_function parser;
4479 unsigned infix_precedence;
4480 parse_expression_infix_function infix_parser;
4483 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4486 * Prints an error message if an expression was expected but not read
4488 static expression_t *expected_expression_error(void)
4490 /* skip the error message if the error token was read */
4491 if (token.type != T_ERROR) {
4492 errorf(HERE, "expected expression, got token '%K'", &token);
4496 return create_invalid_expression();
4500 * Parse a string constant.
4502 static expression_t *parse_string_const(void)
4505 if (token.type == T_STRING_LITERAL) {
4506 string_t res = token.v.string;
4508 while (token.type == T_STRING_LITERAL) {
4509 res = concat_strings(&res, &token.v.string);
4512 if (token.type != T_WIDE_STRING_LITERAL) {
4513 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4514 /* note: that we use type_char_ptr here, which is already the
4515 * automatic converted type. revert_automatic_type_conversion
4516 * will construct the array type */
4517 cnst->base.type = type_char_ptr;
4518 cnst->string.value = res;
4522 wres = concat_string_wide_string(&res, &token.v.wide_string);
4524 wres = token.v.wide_string;
4529 switch (token.type) {
4530 case T_WIDE_STRING_LITERAL:
4531 wres = concat_wide_strings(&wres, &token.v.wide_string);
4534 case T_STRING_LITERAL:
4535 wres = concat_wide_string_string(&wres, &token.v.string);
4539 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4540 cnst->base.type = type_wchar_t_ptr;
4541 cnst->wide_string.value = wres;
4550 * Parse an integer constant.
4552 static expression_t *parse_int_const(void)
4554 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4555 cnst->base.source_position = HERE;
4556 cnst->base.type = token.datatype;
4557 cnst->conste.v.int_value = token.v.intvalue;
4565 * Parse a character constant.
4567 static expression_t *parse_character_constant(void)
4569 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4571 cnst->base.source_position = HERE;
4572 cnst->base.type = token.datatype;
4573 cnst->conste.v.character = token.v.string;
4575 if (cnst->conste.v.character.size != 1) {
4576 if (warning.multichar && (c_mode & _GNUC)) {
4578 warningf(HERE, "multi-character character constant");
4580 errorf(HERE, "more than 1 characters in character constant");
4589 * Parse a wide character constant.
4591 static expression_t *parse_wide_character_constant(void)
4593 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4595 cnst->base.source_position = HERE;
4596 cnst->base.type = token.datatype;
4597 cnst->conste.v.wide_character = token.v.wide_string;
4599 if (cnst->conste.v.wide_character.size != 1) {
4600 if (warning.multichar && (c_mode & _GNUC)) {
4602 warningf(HERE, "multi-character character constant");
4604 errorf(HERE, "more than 1 characters in character constant");
4613 * Parse a float constant.
4615 static expression_t *parse_float_const(void)
4617 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4618 cnst->base.type = token.datatype;
4619 cnst->conste.v.float_value = token.v.floatvalue;
4626 static declaration_t *create_implicit_function(symbol_t *symbol,
4627 const source_position_t source_position)
4629 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4630 ntype->function.return_type = type_int;
4631 ntype->function.unspecified_parameters = true;
4633 type_t *type = typehash_insert(ntype);
4638 declaration_t *const declaration = allocate_declaration_zero();
4639 declaration->storage_class = STORAGE_CLASS_EXTERN;
4640 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4641 declaration->type = type;
4642 declaration->symbol = symbol;
4643 declaration->source_position = source_position;
4644 declaration->parent_scope = global_scope;
4646 scope_t *old_scope = scope;
4647 set_scope(global_scope);
4649 environment_push(declaration);
4650 /* prepends the declaration to the global declarations list */
4651 declaration->next = scope->declarations;
4652 scope->declarations = declaration;
4654 assert(scope == global_scope);
4655 set_scope(old_scope);
4661 * Creates a return_type (func)(argument_type) function type if not
4664 * @param return_type the return type
4665 * @param argument_type the argument type
4667 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4669 function_parameter_t *parameter
4670 = obstack_alloc(type_obst, sizeof(parameter[0]));
4671 memset(parameter, 0, sizeof(parameter[0]));
4672 parameter->type = argument_type;
4674 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4675 type->function.return_type = return_type;
4676 type->function.parameters = parameter;
4678 type_t *result = typehash_insert(type);
4679 if(result != type) {
4687 * Creates a function type for some function like builtins.
4689 * @param symbol the symbol describing the builtin
4691 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4693 switch(symbol->ID) {
4694 case T___builtin_alloca:
4695 return make_function_1_type(type_void_ptr, type_size_t);
4696 case T___builtin_nan:
4697 return make_function_1_type(type_double, type_char_ptr);
4698 case T___builtin_nanf:
4699 return make_function_1_type(type_float, type_char_ptr);
4700 case T___builtin_nand:
4701 return make_function_1_type(type_long_double, type_char_ptr);
4702 case T___builtin_va_end:
4703 return make_function_1_type(type_void, type_valist);
4705 internal_errorf(HERE, "not implemented builtin symbol found");
4710 * Performs automatic type cast as described in § 6.3.2.1.
4712 * @param orig_type the original type
4714 static type_t *automatic_type_conversion(type_t *orig_type)
4716 type_t *type = skip_typeref(orig_type);
4717 if(is_type_array(type)) {
4718 array_type_t *array_type = &type->array;
4719 type_t *element_type = array_type->element_type;
4720 unsigned qualifiers = array_type->type.qualifiers;
4722 return make_pointer_type(element_type, qualifiers);
4725 if(is_type_function(type)) {
4726 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4733 * reverts the automatic casts of array to pointer types and function
4734 * to function-pointer types as defined § 6.3.2.1
4736 type_t *revert_automatic_type_conversion(const expression_t *expression)
4738 switch (expression->kind) {
4739 case EXPR_REFERENCE: return expression->reference.declaration->type;
4740 case EXPR_SELECT: return expression->select.compound_entry->type;
4742 case EXPR_UNARY_DEREFERENCE: {
4743 const expression_t *const value = expression->unary.value;
4744 type_t *const type = skip_typeref(value->base.type);
4745 assert(is_type_pointer(type));
4746 return type->pointer.points_to;
4749 case EXPR_BUILTIN_SYMBOL:
4750 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4752 case EXPR_ARRAY_ACCESS: {
4753 const expression_t *array_ref = expression->array_access.array_ref;
4754 type_t *type_left = skip_typeref(array_ref->base.type);
4755 if (!is_type_valid(type_left))
4757 assert(is_type_pointer(type_left));
4758 return type_left->pointer.points_to;
4761 case EXPR_STRING_LITERAL: {
4762 size_t size = expression->string.value.size;
4763 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4766 case EXPR_WIDE_STRING_LITERAL: {
4767 size_t size = expression->wide_string.value.size;
4768 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4771 case EXPR_COMPOUND_LITERAL:
4772 return expression->compound_literal.type;
4777 return expression->base.type;
4780 static expression_t *parse_reference(void)
4782 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4784 reference_expression_t *ref = &expression->reference;
4785 ref->symbol = token.v.symbol;
4787 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4789 source_position_t source_position = token.source_position;
4792 if(declaration == NULL) {
4793 if (! strict_mode && token.type == '(') {
4794 /* an implicitly defined function */
4795 if (warning.implicit_function_declaration) {
4796 warningf(HERE, "implicit declaration of function '%Y'",
4800 declaration = create_implicit_function(ref->symbol,
4803 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4804 return create_invalid_expression();
4808 type_t *type = declaration->type;
4810 /* we always do the auto-type conversions; the & and sizeof parser contains
4811 * code to revert this! */
4812 type = automatic_type_conversion(type);
4814 ref->declaration = declaration;
4815 ref->base.type = type;
4817 /* this declaration is used */
4818 declaration->used = true;
4820 /* check for deprecated functions */
4821 if(declaration->deprecated != 0) {
4822 const char *prefix = "";
4823 if (is_type_function(declaration->type))
4824 prefix = "function ";
4826 if (declaration->deprecated_string != NULL) {
4827 warningf(source_position,
4828 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4829 declaration->deprecated_string);
4831 warningf(source_position,
4832 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4839 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4843 /* TODO check if explicit cast is allowed and issue warnings/errors */
4846 static expression_t *parse_compound_literal(type_t *type)
4848 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4850 parse_initializer_env_t env;
4852 env.declaration = NULL;
4853 env.must_be_constant = false;
4854 initializer_t *initializer = parse_initializer(&env);
4857 expression->compound_literal.initializer = initializer;
4858 expression->compound_literal.type = type;
4859 expression->base.type = automatic_type_conversion(type);
4865 * Parse a cast expression.
4867 static expression_t *parse_cast(void)
4869 source_position_t source_position = token.source_position;
4871 type_t *type = parse_typename();
4873 /* matching add_anchor_token() is at call site */
4874 rem_anchor_token(')');
4877 if(token.type == '{') {
4878 return parse_compound_literal(type);
4881 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4882 cast->base.source_position = source_position;
4884 expression_t *value = parse_sub_expression(20);
4886 check_cast_allowed(value, type);
4888 cast->base.type = type;
4889 cast->unary.value = value;
4893 return create_invalid_expression();
4897 * Parse a statement expression.
4899 static expression_t *parse_statement_expression(void)
4901 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4903 statement_t *statement = parse_compound_statement();
4904 expression->statement.statement = statement;
4905 expression->base.source_position = statement->base.source_position;
4907 /* find last statement and use its type */
4908 type_t *type = type_void;
4909 const statement_t *stmt = statement->compound.statements;
4911 while (stmt->base.next != NULL)
4912 stmt = stmt->base.next;
4914 if (stmt->kind == STATEMENT_EXPRESSION) {
4915 type = stmt->expression.expression->base.type;
4918 warningf(expression->base.source_position, "empty statement expression ({})");
4920 expression->base.type = type;
4926 return create_invalid_expression();
4930 * Parse a braced expression.
4932 static expression_t *parse_brace_expression(void)
4935 add_anchor_token(')');
4937 switch(token.type) {
4939 /* gcc extension: a statement expression */
4940 return parse_statement_expression();
4944 return parse_cast();
4946 if(is_typedef_symbol(token.v.symbol)) {
4947 return parse_cast();
4951 expression_t *result = parse_expression();
4952 rem_anchor_token(')');
4957 return create_invalid_expression();
4960 static expression_t *parse_function_keyword(void)
4965 if (current_function == NULL) {
4966 errorf(HERE, "'__func__' used outside of a function");
4969 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4970 expression->base.type = type_char_ptr;
4971 expression->funcname.kind = FUNCNAME_FUNCTION;
4976 static expression_t *parse_pretty_function_keyword(void)
4978 eat(T___PRETTY_FUNCTION__);
4980 if (current_function == NULL) {
4981 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4984 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4985 expression->base.type = type_char_ptr;
4986 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
4991 static expression_t *parse_funcsig_keyword(void)
4995 if (current_function == NULL) {
4996 errorf(HERE, "'__FUNCSIG__' used outside of a function");
4999 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5000 expression->base.type = type_char_ptr;
5001 expression->funcname.kind = FUNCNAME_FUNCSIG;
5006 static expression_t *parse_funcdname_keyword(void)
5008 eat(T___FUNCDNAME__);
5010 if (current_function == NULL) {
5011 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5014 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5015 expression->base.type = type_char_ptr;
5016 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5021 static designator_t *parse_designator(void)
5023 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5024 result->source_position = HERE;
5026 if(token.type != T_IDENTIFIER) {
5027 parse_error_expected("while parsing member designator",
5031 result->symbol = token.v.symbol;
5034 designator_t *last_designator = result;
5036 if(token.type == '.') {
5038 if(token.type != T_IDENTIFIER) {
5039 parse_error_expected("while parsing member designator",
5043 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5044 designator->source_position = HERE;
5045 designator->symbol = token.v.symbol;
5048 last_designator->next = designator;
5049 last_designator = designator;
5052 if(token.type == '[') {
5054 add_anchor_token(']');
5055 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5056 designator->source_position = HERE;
5057 designator->array_index = parse_expression();
5058 rem_anchor_token(']');
5060 if(designator->array_index == NULL) {
5064 last_designator->next = designator;
5065 last_designator = designator;
5077 * Parse the __builtin_offsetof() expression.
5079 static expression_t *parse_offsetof(void)
5081 eat(T___builtin_offsetof);
5083 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5084 expression->base.type = type_size_t;
5087 add_anchor_token(',');
5088 type_t *type = parse_typename();
5089 rem_anchor_token(',');
5091 add_anchor_token(')');
5092 designator_t *designator = parse_designator();
5093 rem_anchor_token(')');
5096 expression->offsetofe.type = type;
5097 expression->offsetofe.designator = designator;
5100 memset(&path, 0, sizeof(path));
5101 path.top_type = type;
5102 path.path = NEW_ARR_F(type_path_entry_t, 0);
5104 descend_into_subtype(&path);
5106 if(!walk_designator(&path, designator, true)) {
5107 return create_invalid_expression();
5110 DEL_ARR_F(path.path);
5114 return create_invalid_expression();
5118 * Parses a _builtin_va_start() expression.
5120 static expression_t *parse_va_start(void)
5122 eat(T___builtin_va_start);
5124 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5127 add_anchor_token(',');
5128 expression->va_starte.ap = parse_assignment_expression();
5129 rem_anchor_token(',');
5131 expression_t *const expr = parse_assignment_expression();
5132 if (expr->kind == EXPR_REFERENCE) {
5133 declaration_t *const decl = expr->reference.declaration;
5135 return create_invalid_expression();
5136 if (decl->parent_scope == ¤t_function->scope &&
5137 decl->next == NULL) {
5138 expression->va_starte.parameter = decl;
5143 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
5145 return create_invalid_expression();
5149 * Parses a _builtin_va_arg() expression.
5151 static expression_t *parse_va_arg(void)
5153 eat(T___builtin_va_arg);
5155 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5158 expression->va_arge.ap = parse_assignment_expression();
5160 expression->base.type = parse_typename();
5165 return create_invalid_expression();
5168 static expression_t *parse_builtin_symbol(void)
5170 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5172 symbol_t *symbol = token.v.symbol;
5174 expression->builtin_symbol.symbol = symbol;
5177 type_t *type = get_builtin_symbol_type(symbol);
5178 type = automatic_type_conversion(type);
5180 expression->base.type = type;
5185 * Parses a __builtin_constant() expression.
5187 static expression_t *parse_builtin_constant(void)
5189 eat(T___builtin_constant_p);
5191 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5194 add_anchor_token(')');
5195 expression->builtin_constant.value = parse_assignment_expression();
5196 rem_anchor_token(')');
5198 expression->base.type = type_int;
5202 return create_invalid_expression();
5206 * Parses a __builtin_prefetch() expression.
5208 static expression_t *parse_builtin_prefetch(void)
5210 eat(T___builtin_prefetch);
5212 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5215 add_anchor_token(')');
5216 expression->builtin_prefetch.adr = parse_assignment_expression();
5217 if (token.type == ',') {
5219 expression->builtin_prefetch.rw = parse_assignment_expression();
5221 if (token.type == ',') {
5223 expression->builtin_prefetch.locality = parse_assignment_expression();
5225 rem_anchor_token(')');
5227 expression->base.type = type_void;
5231 return create_invalid_expression();
5235 * Parses a __builtin_is_*() compare expression.
5237 static expression_t *parse_compare_builtin(void)
5239 expression_t *expression;
5241 switch(token.type) {
5242 case T___builtin_isgreater:
5243 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5245 case T___builtin_isgreaterequal:
5246 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5248 case T___builtin_isless:
5249 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5251 case T___builtin_islessequal:
5252 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5254 case T___builtin_islessgreater:
5255 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5257 case T___builtin_isunordered:
5258 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5261 internal_errorf(HERE, "invalid compare builtin found");
5264 expression->base.source_position = HERE;
5268 expression->binary.left = parse_assignment_expression();
5270 expression->binary.right = parse_assignment_expression();
5273 type_t *const orig_type_left = expression->binary.left->base.type;
5274 type_t *const orig_type_right = expression->binary.right->base.type;
5276 type_t *const type_left = skip_typeref(orig_type_left);
5277 type_t *const type_right = skip_typeref(orig_type_right);
5278 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5279 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5280 type_error_incompatible("invalid operands in comparison",
5281 expression->base.source_position, orig_type_left, orig_type_right);
5284 semantic_comparison(&expression->binary);
5289 return create_invalid_expression();
5293 * Parses a __builtin_expect() expression.
5295 static expression_t *parse_builtin_expect(void)
5297 eat(T___builtin_expect);
5299 expression_t *expression
5300 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5303 expression->binary.left = parse_assignment_expression();
5305 expression->binary.right = parse_constant_expression();
5308 expression->base.type = expression->binary.left->base.type;
5312 return create_invalid_expression();
5316 * Parses a MS assume() expression.
5318 static expression_t *parse_assume(void) {
5321 expression_t *expression
5322 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5325 add_anchor_token(')');
5326 expression->unary.value = parse_assignment_expression();
5327 rem_anchor_token(')');
5330 expression->base.type = type_void;
5333 return create_invalid_expression();
5337 * Parse a microsoft __noop expression.
5339 static expression_t *parse_noop_expression(void) {
5340 source_position_t source_position = HERE;
5343 if (token.type == '(') {
5344 /* parse arguments */
5346 add_anchor_token(')');
5347 add_anchor_token(',');
5349 if(token.type != ')') {
5351 (void)parse_assignment_expression();
5352 if(token.type != ',')
5358 rem_anchor_token(',');
5359 rem_anchor_token(')');
5362 /* the result is a (int)0 */
5363 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5364 cnst->base.source_position = source_position;
5365 cnst->base.type = type_int;
5366 cnst->conste.v.int_value = 0;
5367 cnst->conste.is_ms_noop = true;
5372 return create_invalid_expression();
5376 * Parses a primary expression.
5378 static expression_t *parse_primary_expression(void)
5380 switch (token.type) {
5381 case T_INTEGER: return parse_int_const();
5382 case T_CHARACTER_CONSTANT: return parse_character_constant();
5383 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5384 case T_FLOATINGPOINT: return parse_float_const();
5385 case T_STRING_LITERAL:
5386 case T_WIDE_STRING_LITERAL: return parse_string_const();
5387 case T_IDENTIFIER: return parse_reference();
5388 case T___FUNCTION__:
5389 case T___func__: return parse_function_keyword();
5390 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5391 case T___FUNCSIG__: return parse_funcsig_keyword();
5392 case T___FUNCDNAME__: return parse_funcdname_keyword();
5393 case T___builtin_offsetof: return parse_offsetof();
5394 case T___builtin_va_start: return parse_va_start();
5395 case T___builtin_va_arg: return parse_va_arg();
5396 case T___builtin_expect: return parse_builtin_expect();
5397 case T___builtin_alloca:
5398 case T___builtin_nan:
5399 case T___builtin_nand:
5400 case T___builtin_nanf:
5401 case T___builtin_va_end: return parse_builtin_symbol();
5402 case T___builtin_isgreater:
5403 case T___builtin_isgreaterequal:
5404 case T___builtin_isless:
5405 case T___builtin_islessequal:
5406 case T___builtin_islessgreater:
5407 case T___builtin_isunordered: return parse_compare_builtin();
5408 case T___builtin_constant_p: return parse_builtin_constant();
5409 case T___builtin_prefetch: return parse_builtin_prefetch();
5410 case T__assume: return parse_assume();
5412 case '(': return parse_brace_expression();
5413 case T___noop: return parse_noop_expression();
5416 errorf(HERE, "unexpected token %K, expected an expression", &token);
5417 return create_invalid_expression();
5421 * Check if the expression has the character type and issue a warning then.
5423 static void check_for_char_index_type(const expression_t *expression) {
5424 type_t *const type = expression->base.type;
5425 const type_t *const base_type = skip_typeref(type);
5427 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5428 warning.char_subscripts) {
5429 warningf(expression->base.source_position,
5430 "array subscript has type '%T'", type);
5434 static expression_t *parse_array_expression(unsigned precedence,
5440 add_anchor_token(']');
5442 expression_t *inside = parse_expression();
5444 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5446 array_access_expression_t *array_access = &expression->array_access;
5448 type_t *const orig_type_left = left->base.type;
5449 type_t *const orig_type_inside = inside->base.type;
5451 type_t *const type_left = skip_typeref(orig_type_left);
5452 type_t *const type_inside = skip_typeref(orig_type_inside);
5454 type_t *return_type;
5455 if (is_type_pointer(type_left)) {
5456 return_type = type_left->pointer.points_to;
5457 array_access->array_ref = left;
5458 array_access->index = inside;
5459 check_for_char_index_type(inside);
5460 } else if (is_type_pointer(type_inside)) {
5461 return_type = type_inside->pointer.points_to;
5462 array_access->array_ref = inside;
5463 array_access->index = left;
5464 array_access->flipped = true;
5465 check_for_char_index_type(left);
5467 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5469 "array access on object with non-pointer types '%T', '%T'",
5470 orig_type_left, orig_type_inside);
5472 return_type = type_error_type;
5473 array_access->array_ref = create_invalid_expression();
5476 rem_anchor_token(']');
5477 if(token.type != ']') {
5478 parse_error_expected("Problem while parsing array access", ']', 0);
5483 return_type = automatic_type_conversion(return_type);
5484 expression->base.type = return_type;
5489 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5491 expression_t *tp_expression = allocate_expression_zero(kind);
5492 tp_expression->base.type = type_size_t;
5494 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5496 add_anchor_token(')');
5497 tp_expression->typeprop.type = parse_typename();
5498 rem_anchor_token(')');
5501 expression_t *expression = parse_sub_expression(precedence);
5502 expression->base.type = revert_automatic_type_conversion(expression);
5504 tp_expression->typeprop.type = expression->base.type;
5505 tp_expression->typeprop.tp_expression = expression;
5508 return tp_expression;
5510 return create_invalid_expression();
5513 static expression_t *parse_sizeof(unsigned precedence)
5516 return parse_typeprop(EXPR_SIZEOF, precedence);
5519 static expression_t *parse_alignof(unsigned precedence)
5522 return parse_typeprop(EXPR_SIZEOF, precedence);
5525 static expression_t *parse_select_expression(unsigned precedence,
5526 expression_t *compound)
5529 assert(token.type == '.' || token.type == T_MINUSGREATER);
5531 bool is_pointer = (token.type == T_MINUSGREATER);
5534 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5535 select->select.compound = compound;
5537 if(token.type != T_IDENTIFIER) {
5538 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5541 symbol_t *symbol = token.v.symbol;
5542 select->select.symbol = symbol;
5545 type_t *const orig_type = compound->base.type;
5546 type_t *const type = skip_typeref(orig_type);
5548 type_t *type_left = type;
5550 if (!is_type_pointer(type)) {
5551 if (is_type_valid(type)) {
5552 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5554 return create_invalid_expression();
5556 type_left = type->pointer.points_to;
5558 type_left = skip_typeref(type_left);
5560 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5561 type_left->kind != TYPE_COMPOUND_UNION) {
5562 if (is_type_valid(type_left)) {
5563 errorf(HERE, "request for member '%Y' in something not a struct or "
5564 "union, but '%T'", symbol, type_left);
5566 return create_invalid_expression();
5569 declaration_t *const declaration = type_left->compound.declaration;
5571 if(!declaration->init.is_defined) {
5572 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5574 return create_invalid_expression();
5577 declaration_t *iter = find_compound_entry(declaration, symbol);
5579 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5580 return create_invalid_expression();
5583 /* we always do the auto-type conversions; the & and sizeof parser contains
5584 * code to revert this! */
5585 type_t *expression_type = automatic_type_conversion(iter->type);
5587 select->select.compound_entry = iter;
5588 select->base.type = expression_type;
5590 if(expression_type->kind == TYPE_BITFIELD) {
5591 expression_t *extract
5592 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5593 extract->unary.value = select;
5594 extract->base.type = expression_type->bitfield.base;
5603 * Parse a call expression, ie. expression '( ... )'.
5605 * @param expression the function address
5607 static expression_t *parse_call_expression(unsigned precedence,
5608 expression_t *expression)
5611 expression_t *result = allocate_expression_zero(EXPR_CALL);
5612 result->base.source_position = expression->base.source_position;
5614 call_expression_t *call = &result->call;
5615 call->function = expression;
5617 type_t *const orig_type = expression->base.type;
5618 type_t *const type = skip_typeref(orig_type);
5620 function_type_t *function_type = NULL;
5621 if (is_type_pointer(type)) {
5622 type_t *const to_type = skip_typeref(type->pointer.points_to);
5624 if (is_type_function(to_type)) {
5625 function_type = &to_type->function;
5626 call->base.type = function_type->return_type;
5630 if (function_type == NULL && is_type_valid(type)) {
5631 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5634 /* parse arguments */
5636 add_anchor_token(')');
5637 add_anchor_token(',');
5639 if(token.type != ')') {
5640 call_argument_t *last_argument = NULL;
5643 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5645 argument->expression = parse_assignment_expression();
5646 if(last_argument == NULL) {
5647 call->arguments = argument;
5649 last_argument->next = argument;
5651 last_argument = argument;
5653 if(token.type != ',')
5658 rem_anchor_token(',');
5659 rem_anchor_token(')');
5662 if(function_type != NULL) {
5663 function_parameter_t *parameter = function_type->parameters;
5664 call_argument_t *argument = call->arguments;
5665 for( ; parameter != NULL && argument != NULL;
5666 parameter = parameter->next, argument = argument->next) {
5667 type_t *expected_type = parameter->type;
5668 /* TODO report scope in error messages */
5669 expression_t *const arg_expr = argument->expression;
5670 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call", arg_expr->base.source_position);
5671 if (res_type == NULL) {
5672 /* TODO improve error message */
5673 errorf(arg_expr->base.source_position,
5674 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5675 arg_expr, arg_expr->base.type, expected_type);
5677 argument->expression = create_implicit_cast(argument->expression, expected_type);
5680 /* too few parameters */
5681 if(parameter != NULL) {
5682 errorf(HERE, "too few arguments to function '%E'", expression);
5683 } else if(argument != NULL) {
5684 /* too many parameters */
5685 if(!function_type->variadic
5686 && !function_type->unspecified_parameters) {
5687 errorf(HERE, "too many arguments to function '%E'", expression);
5689 /* do default promotion */
5690 for( ; argument != NULL; argument = argument->next) {
5691 type_t *type = argument->expression->base.type;
5693 type = skip_typeref(type);
5694 if(is_type_integer(type)) {
5695 type = promote_integer(type);
5696 } else if(type == type_float) {
5700 argument->expression
5701 = create_implicit_cast(argument->expression, type);
5704 check_format(&result->call);
5707 check_format(&result->call);
5713 return create_invalid_expression();
5716 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5718 static bool same_compound_type(const type_t *type1, const type_t *type2)
5721 is_type_compound(type1) &&
5722 type1->kind == type2->kind &&
5723 type1->compound.declaration == type2->compound.declaration;
5727 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5729 * @param expression the conditional expression
5731 static expression_t *parse_conditional_expression(unsigned precedence,
5732 expression_t *expression)
5735 add_anchor_token(':');
5737 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5739 conditional_expression_t *conditional = &result->conditional;
5740 conditional->condition = expression;
5743 type_t *const condition_type_orig = expression->base.type;
5744 type_t *const condition_type = skip_typeref(condition_type_orig);
5745 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5746 type_error("expected a scalar type in conditional condition",
5747 expression->base.source_position, condition_type_orig);
5750 expression_t *true_expression = parse_expression();
5751 rem_anchor_token(':');
5753 expression_t *false_expression = parse_sub_expression(precedence);
5755 type_t *const orig_true_type = true_expression->base.type;
5756 type_t *const orig_false_type = false_expression->base.type;
5757 type_t *const true_type = skip_typeref(orig_true_type);
5758 type_t *const false_type = skip_typeref(orig_false_type);
5761 type_t *result_type;
5762 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5763 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5764 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5765 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5766 warningf(expression->base.source_position,
5767 "ISO C forbids conditional expression with only one void side");
5769 result_type = type_void;
5770 } else if (is_type_arithmetic(true_type)
5771 && is_type_arithmetic(false_type)) {
5772 result_type = semantic_arithmetic(true_type, false_type);
5774 true_expression = create_implicit_cast(true_expression, result_type);
5775 false_expression = create_implicit_cast(false_expression, result_type);
5777 conditional->true_expression = true_expression;
5778 conditional->false_expression = false_expression;
5779 conditional->base.type = result_type;
5780 } else if (same_compound_type(true_type, false_type)) {
5781 /* just take 1 of the 2 types */
5782 result_type = true_type;
5783 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5784 type_t *pointer_type;
5786 expression_t *other_expression;
5787 if (is_type_pointer(true_type)) {
5788 pointer_type = true_type;
5789 other_type = false_type;
5790 other_expression = false_expression;
5792 pointer_type = false_type;
5793 other_type = true_type;
5794 other_expression = true_expression;
5797 if(is_type_pointer(other_type)) {
5798 if(!pointers_compatible(true_type, false_type)) {
5799 warningf(expression->base.source_position,
5800 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5802 result_type = true_type;
5803 } else if(is_null_pointer_constant(other_expression)) {
5804 result_type = pointer_type;
5805 } else if(is_type_integer(other_type)) {
5806 warningf(expression->base.source_position,
5807 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5808 result_type = pointer_type;
5810 type_error_incompatible("while parsing conditional",
5811 expression->base.source_position, true_type, false_type);
5812 result_type = type_error_type;
5815 /* TODO: one pointer to void*, other some pointer */
5817 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5818 type_error_incompatible("while parsing conditional",
5819 expression->base.source_position, true_type,
5822 result_type = type_error_type;
5825 conditional->true_expression
5826 = create_implicit_cast(true_expression, result_type);
5827 conditional->false_expression
5828 = create_implicit_cast(false_expression, result_type);
5829 conditional->base.type = result_type;
5832 return create_invalid_expression();
5836 * Parse an extension expression.
5838 static expression_t *parse_extension(unsigned precedence)
5840 eat(T___extension__);
5842 /* TODO enable extensions */
5843 expression_t *expression = parse_sub_expression(precedence);
5844 /* TODO disable extensions */
5849 * Parse a __builtin_classify_type() expression.
5851 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5853 eat(T___builtin_classify_type);
5855 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5856 result->base.type = type_int;
5859 add_anchor_token(')');
5860 expression_t *expression = parse_sub_expression(precedence);
5861 rem_anchor_token(')');
5863 result->classify_type.type_expression = expression;
5867 return create_invalid_expression();
5870 static void semantic_incdec(unary_expression_t *expression)
5872 type_t *const orig_type = expression->value->base.type;
5873 type_t *const type = skip_typeref(orig_type);
5874 /* TODO !is_type_real && !is_type_pointer */
5875 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5876 if (is_type_valid(type)) {
5877 /* TODO: improve error message */
5878 errorf(HERE, "operation needs an arithmetic or pointer type");
5883 expression->base.type = orig_type;
5886 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5888 type_t *const orig_type = expression->value->base.type;
5889 type_t *const type = skip_typeref(orig_type);
5890 if(!is_type_arithmetic(type)) {
5891 if (is_type_valid(type)) {
5892 /* TODO: improve error message */
5893 errorf(HERE, "operation needs an arithmetic type");
5898 expression->base.type = orig_type;
5901 static void semantic_unexpr_scalar(unary_expression_t *expression)
5903 type_t *const orig_type = expression->value->base.type;
5904 type_t *const type = skip_typeref(orig_type);
5905 if (!is_type_scalar(type)) {
5906 if (is_type_valid(type)) {
5907 errorf(HERE, "operand of ! must be of scalar type");
5912 expression->base.type = orig_type;
5915 static void semantic_unexpr_integer(unary_expression_t *expression)
5917 type_t *const orig_type = expression->value->base.type;
5918 type_t *const type = skip_typeref(orig_type);
5919 if (!is_type_integer(type)) {
5920 if (is_type_valid(type)) {
5921 errorf(HERE, "operand of ~ must be of integer type");
5926 expression->base.type = orig_type;
5929 static void semantic_dereference(unary_expression_t *expression)
5931 type_t *const orig_type = expression->value->base.type;
5932 type_t *const type = skip_typeref(orig_type);
5933 if(!is_type_pointer(type)) {
5934 if (is_type_valid(type)) {
5935 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5940 type_t *result_type = type->pointer.points_to;
5941 result_type = automatic_type_conversion(result_type);
5942 expression->base.type = result_type;
5946 * Check the semantic of the address taken expression.
5948 static void semantic_take_addr(unary_expression_t *expression)
5950 expression_t *value = expression->value;
5951 value->base.type = revert_automatic_type_conversion(value);
5953 type_t *orig_type = value->base.type;
5954 if(!is_type_valid(orig_type))
5957 if(value->kind == EXPR_REFERENCE) {
5958 declaration_t *const declaration = value->reference.declaration;
5959 if(declaration != NULL) {
5960 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5961 errorf(expression->base.source_position,
5962 "address of register variable '%Y' requested",
5963 declaration->symbol);
5965 declaration->address_taken = 1;
5969 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5972 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5973 static expression_t *parse_##unexpression_type(unsigned precedence) \
5977 expression_t *unary_expression \
5978 = allocate_expression_zero(unexpression_type); \
5979 unary_expression->base.source_position = HERE; \
5980 unary_expression->unary.value = parse_sub_expression(precedence); \
5982 sfunc(&unary_expression->unary); \
5984 return unary_expression; \
5987 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5988 semantic_unexpr_arithmetic)
5989 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5990 semantic_unexpr_arithmetic)
5991 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5992 semantic_unexpr_scalar)
5993 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5994 semantic_dereference)
5995 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5997 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5998 semantic_unexpr_integer)
5999 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6001 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6004 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6006 static expression_t *parse_##unexpression_type(unsigned precedence, \
6007 expression_t *left) \
6009 (void) precedence; \
6012 expression_t *unary_expression \
6013 = allocate_expression_zero(unexpression_type); \
6014 unary_expression->unary.value = left; \
6016 sfunc(&unary_expression->unary); \
6018 return unary_expression; \
6021 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6022 EXPR_UNARY_POSTFIX_INCREMENT,
6024 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6025 EXPR_UNARY_POSTFIX_DECREMENT,
6028 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6030 /* TODO: handle complex + imaginary types */
6032 /* § 6.3.1.8 Usual arithmetic conversions */
6033 if(type_left == type_long_double || type_right == type_long_double) {
6034 return type_long_double;
6035 } else if(type_left == type_double || type_right == type_double) {
6037 } else if(type_left == type_float || type_right == type_float) {
6041 type_right = promote_integer(type_right);
6042 type_left = promote_integer(type_left);
6044 if(type_left == type_right)
6047 bool signed_left = is_type_signed(type_left);
6048 bool signed_right = is_type_signed(type_right);
6049 int rank_left = get_rank(type_left);
6050 int rank_right = get_rank(type_right);
6051 if(rank_left < rank_right) {
6052 if(signed_left == signed_right || !signed_right) {
6058 if(signed_left == signed_right || !signed_left) {
6067 * Check the semantic restrictions for a binary expression.
6069 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6071 expression_t *const left = expression->left;
6072 expression_t *const right = expression->right;
6073 type_t *const orig_type_left = left->base.type;
6074 type_t *const orig_type_right = right->base.type;
6075 type_t *const type_left = skip_typeref(orig_type_left);
6076 type_t *const type_right = skip_typeref(orig_type_right);
6078 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6079 /* TODO: improve error message */
6080 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6081 errorf(HERE, "operation needs arithmetic types");
6086 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6087 expression->left = create_implicit_cast(left, arithmetic_type);
6088 expression->right = create_implicit_cast(right, arithmetic_type);
6089 expression->base.type = arithmetic_type;
6092 static void semantic_shift_op(binary_expression_t *expression)
6094 expression_t *const left = expression->left;
6095 expression_t *const right = expression->right;
6096 type_t *const orig_type_left = left->base.type;
6097 type_t *const orig_type_right = right->base.type;
6098 type_t * type_left = skip_typeref(orig_type_left);
6099 type_t * type_right = skip_typeref(orig_type_right);
6101 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6102 /* TODO: improve error message */
6103 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6104 errorf(HERE, "operation needs integer types");
6109 type_left = promote_integer(type_left);
6110 type_right = promote_integer(type_right);
6112 expression->left = create_implicit_cast(left, type_left);
6113 expression->right = create_implicit_cast(right, type_right);
6114 expression->base.type = type_left;
6117 static void semantic_add(binary_expression_t *expression)
6119 expression_t *const left = expression->left;
6120 expression_t *const right = expression->right;
6121 type_t *const orig_type_left = left->base.type;
6122 type_t *const orig_type_right = right->base.type;
6123 type_t *const type_left = skip_typeref(orig_type_left);
6124 type_t *const type_right = skip_typeref(orig_type_right);
6127 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6128 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6129 expression->left = create_implicit_cast(left, arithmetic_type);
6130 expression->right = create_implicit_cast(right, arithmetic_type);
6131 expression->base.type = arithmetic_type;
6133 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6134 expression->base.type = type_left;
6135 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
6136 expression->base.type = type_right;
6137 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6138 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
6142 static void semantic_sub(binary_expression_t *expression)
6144 expression_t *const left = expression->left;
6145 expression_t *const right = expression->right;
6146 type_t *const orig_type_left = left->base.type;
6147 type_t *const orig_type_right = right->base.type;
6148 type_t *const type_left = skip_typeref(orig_type_left);
6149 type_t *const type_right = skip_typeref(orig_type_right);
6152 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6153 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6154 expression->left = create_implicit_cast(left, arithmetic_type);
6155 expression->right = create_implicit_cast(right, arithmetic_type);
6156 expression->base.type = arithmetic_type;
6158 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6159 expression->base.type = type_left;
6160 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6161 if(!pointers_compatible(type_left, type_right)) {
6163 "pointers to incompatible objects to binary '-' ('%T', '%T')",
6164 orig_type_left, orig_type_right);
6166 expression->base.type = type_ptrdiff_t;
6168 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6169 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6170 orig_type_left, orig_type_right);
6175 * Check the semantics of comparison expressions.
6177 * @param expression The expression to check.
6179 static void semantic_comparison(binary_expression_t *expression)
6181 expression_t *left = expression->left;
6182 expression_t *right = expression->right;
6183 type_t *orig_type_left = left->base.type;
6184 type_t *orig_type_right = right->base.type;
6186 type_t *type_left = skip_typeref(orig_type_left);
6187 type_t *type_right = skip_typeref(orig_type_right);
6189 /* TODO non-arithmetic types */
6190 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6191 if (warning.sign_compare &&
6192 (expression->base.kind != EXPR_BINARY_EQUAL &&
6193 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6194 (is_type_signed(type_left) != is_type_signed(type_right))) {
6195 warningf(expression->base.source_position,
6196 "comparison between signed and unsigned");
6198 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6199 expression->left = create_implicit_cast(left, arithmetic_type);
6200 expression->right = create_implicit_cast(right, arithmetic_type);
6201 expression->base.type = arithmetic_type;
6202 if (warning.float_equal &&
6203 (expression->base.kind == EXPR_BINARY_EQUAL ||
6204 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6205 is_type_float(arithmetic_type)) {
6206 warningf(expression->base.source_position,
6207 "comparing floating point with == or != is unsafe");
6209 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6210 /* TODO check compatibility */
6211 } else if (is_type_pointer(type_left)) {
6212 expression->right = create_implicit_cast(right, type_left);
6213 } else if (is_type_pointer(type_right)) {
6214 expression->left = create_implicit_cast(left, type_right);
6215 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6216 type_error_incompatible("invalid operands in comparison",
6217 expression->base.source_position,
6218 type_left, type_right);
6220 expression->base.type = type_int;
6223 static void semantic_arithmetic_assign(binary_expression_t *expression)
6225 expression_t *left = expression->left;
6226 expression_t *right = expression->right;
6227 type_t *orig_type_left = left->base.type;
6228 type_t *orig_type_right = right->base.type;
6230 type_t *type_left = skip_typeref(orig_type_left);
6231 type_t *type_right = skip_typeref(orig_type_right);
6233 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6234 /* TODO: improve error message */
6235 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6236 errorf(HERE, "operation needs arithmetic types");
6241 /* combined instructions are tricky. We can't create an implicit cast on
6242 * the left side, because we need the uncasted form for the store.
6243 * The ast2firm pass has to know that left_type must be right_type
6244 * for the arithmetic operation and create a cast by itself */
6245 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6246 expression->right = create_implicit_cast(right, arithmetic_type);
6247 expression->base.type = type_left;
6250 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6252 expression_t *const left = expression->left;
6253 expression_t *const right = expression->right;
6254 type_t *const orig_type_left = left->base.type;
6255 type_t *const orig_type_right = right->base.type;
6256 type_t *const type_left = skip_typeref(orig_type_left);
6257 type_t *const type_right = skip_typeref(orig_type_right);
6259 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6260 /* combined instructions are tricky. We can't create an implicit cast on
6261 * the left side, because we need the uncasted form for the store.
6262 * The ast2firm pass has to know that left_type must be right_type
6263 * for the arithmetic operation and create a cast by itself */
6264 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6265 expression->right = create_implicit_cast(right, arithmetic_type);
6266 expression->base.type = type_left;
6267 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6268 expression->base.type = type_left;
6269 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6270 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6275 * Check the semantic restrictions of a logical expression.
6277 static void semantic_logical_op(binary_expression_t *expression)
6279 expression_t *const left = expression->left;
6280 expression_t *const right = expression->right;
6281 type_t *const orig_type_left = left->base.type;
6282 type_t *const orig_type_right = right->base.type;
6283 type_t *const type_left = skip_typeref(orig_type_left);
6284 type_t *const type_right = skip_typeref(orig_type_right);
6286 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6287 /* TODO: improve error message */
6288 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6289 errorf(HERE, "operation needs scalar types");
6294 expression->base.type = type_int;
6298 * Checks if a compound type has constant fields.
6300 static bool has_const_fields(const compound_type_t *type)
6302 const scope_t *scope = &type->declaration->scope;
6303 const declaration_t *declaration = scope->declarations;
6305 for (; declaration != NULL; declaration = declaration->next) {
6306 if (declaration->namespc != NAMESPACE_NORMAL)
6309 const type_t *decl_type = skip_typeref(declaration->type);
6310 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6318 * Check the semantic restrictions of a binary assign expression.
6320 static void semantic_binexpr_assign(binary_expression_t *expression)
6322 expression_t *left = expression->left;
6323 type_t *orig_type_left = left->base.type;
6325 type_t *type_left = revert_automatic_type_conversion(left);
6326 type_left = skip_typeref(orig_type_left);
6328 /* must be a modifiable lvalue */
6329 if (is_type_array(type_left)) {
6330 errorf(HERE, "cannot assign to arrays ('%E')", left);
6333 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6334 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6338 if(is_type_incomplete(type_left)) {
6340 "left-hand side of assignment '%E' has incomplete type '%T'",
6341 left, orig_type_left);
6344 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6345 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6346 left, orig_type_left);
6350 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6351 "assignment", left->base.source_position);
6352 if (res_type == NULL) {
6353 errorf(expression->base.source_position,
6354 "cannot assign to '%T' from '%T'",
6355 orig_type_left, expression->right->base.type);
6357 expression->right = create_implicit_cast(expression->right, res_type);
6360 expression->base.type = orig_type_left;
6364 * Determine if the outermost operation (or parts thereof) of the given
6365 * expression has no effect in order to generate a warning about this fact.
6366 * Therefore in some cases this only examines some of the operands of the
6367 * expression (see comments in the function and examples below).
6369 * f() + 23; // warning, because + has no effect
6370 * x || f(); // no warning, because x controls execution of f()
6371 * x ? y : f(); // warning, because y has no effect
6372 * (void)x; // no warning to be able to suppress the warning
6373 * This function can NOT be used for an "expression has definitely no effect"-
6375 static bool expression_has_effect(const expression_t *const expr)
6377 switch (expr->kind) {
6378 case EXPR_UNKNOWN: break;
6379 case EXPR_INVALID: return true; /* do NOT warn */
6380 case EXPR_REFERENCE: return false;
6381 /* suppress the warning for microsoft __noop operations */
6382 case EXPR_CONST: return expr->conste.is_ms_noop;
6383 case EXPR_CHARACTER_CONSTANT: return false;
6384 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6385 case EXPR_STRING_LITERAL: return false;
6386 case EXPR_WIDE_STRING_LITERAL: return false;
6389 const call_expression_t *const call = &expr->call;
6390 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6393 switch (call->function->builtin_symbol.symbol->ID) {
6394 case T___builtin_va_end: return true;
6395 default: return false;
6399 /* Generate the warning if either the left or right hand side of a
6400 * conditional expression has no effect */
6401 case EXPR_CONDITIONAL: {
6402 const conditional_expression_t *const cond = &expr->conditional;
6404 expression_has_effect(cond->true_expression) &&
6405 expression_has_effect(cond->false_expression);
6408 case EXPR_SELECT: return false;
6409 case EXPR_ARRAY_ACCESS: return false;
6410 case EXPR_SIZEOF: return false;
6411 case EXPR_CLASSIFY_TYPE: return false;
6412 case EXPR_ALIGNOF: return false;
6414 case EXPR_FUNCNAME: return false;
6415 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6416 case EXPR_BUILTIN_CONSTANT_P: return false;
6417 case EXPR_BUILTIN_PREFETCH: return true;
6418 case EXPR_OFFSETOF: return false;
6419 case EXPR_VA_START: return true;
6420 case EXPR_VA_ARG: return true;
6421 case EXPR_STATEMENT: return true; // TODO
6422 case EXPR_COMPOUND_LITERAL: return false;
6424 case EXPR_UNARY_NEGATE: return false;
6425 case EXPR_UNARY_PLUS: return false;
6426 case EXPR_UNARY_BITWISE_NEGATE: return false;
6427 case EXPR_UNARY_NOT: return false;
6428 case EXPR_UNARY_DEREFERENCE: return false;
6429 case EXPR_UNARY_TAKE_ADDRESS: return false;
6430 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6431 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6432 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6433 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6435 /* Treat void casts as if they have an effect in order to being able to
6436 * suppress the warning */
6437 case EXPR_UNARY_CAST: {
6438 type_t *const type = skip_typeref(expr->base.type);
6439 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6442 case EXPR_UNARY_CAST_IMPLICIT: return true;
6443 case EXPR_UNARY_ASSUME: return true;
6444 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6446 case EXPR_BINARY_ADD: return false;
6447 case EXPR_BINARY_SUB: return false;
6448 case EXPR_BINARY_MUL: return false;
6449 case EXPR_BINARY_DIV: return false;
6450 case EXPR_BINARY_MOD: return false;
6451 case EXPR_BINARY_EQUAL: return false;
6452 case EXPR_BINARY_NOTEQUAL: return false;
6453 case EXPR_BINARY_LESS: return false;
6454 case EXPR_BINARY_LESSEQUAL: return false;
6455 case EXPR_BINARY_GREATER: return false;
6456 case EXPR_BINARY_GREATEREQUAL: return false;
6457 case EXPR_BINARY_BITWISE_AND: return false;
6458 case EXPR_BINARY_BITWISE_OR: return false;
6459 case EXPR_BINARY_BITWISE_XOR: return false;
6460 case EXPR_BINARY_SHIFTLEFT: return false;
6461 case EXPR_BINARY_SHIFTRIGHT: return false;
6462 case EXPR_BINARY_ASSIGN: return true;
6463 case EXPR_BINARY_MUL_ASSIGN: return true;
6464 case EXPR_BINARY_DIV_ASSIGN: return true;
6465 case EXPR_BINARY_MOD_ASSIGN: return true;
6466 case EXPR_BINARY_ADD_ASSIGN: return true;
6467 case EXPR_BINARY_SUB_ASSIGN: return true;
6468 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6469 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6470 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6471 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6472 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6474 /* Only examine the right hand side of && and ||, because the left hand
6475 * side already has the effect of controlling the execution of the right
6477 case EXPR_BINARY_LOGICAL_AND:
6478 case EXPR_BINARY_LOGICAL_OR:
6479 /* Only examine the right hand side of a comma expression, because the left
6480 * hand side has a separate warning */
6481 case EXPR_BINARY_COMMA:
6482 return expression_has_effect(expr->binary.right);
6484 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6485 case EXPR_BINARY_ISGREATER: return false;
6486 case EXPR_BINARY_ISGREATEREQUAL: return false;
6487 case EXPR_BINARY_ISLESS: return false;
6488 case EXPR_BINARY_ISLESSEQUAL: return false;
6489 case EXPR_BINARY_ISLESSGREATER: return false;
6490 case EXPR_BINARY_ISUNORDERED: return false;
6493 internal_errorf(HERE, "unexpected expression");
6496 static void semantic_comma(binary_expression_t *expression)
6498 if (warning.unused_value) {
6499 const expression_t *const left = expression->left;
6500 if (!expression_has_effect(left)) {
6501 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6504 expression->base.type = expression->right->base.type;
6507 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6508 static expression_t *parse_##binexpression_type(unsigned precedence, \
6509 expression_t *left) \
6512 source_position_t pos = HERE; \
6514 expression_t *right = parse_sub_expression(precedence + lr); \
6516 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6517 binexpr->base.source_position = pos; \
6518 binexpr->binary.left = left; \
6519 binexpr->binary.right = right; \
6520 sfunc(&binexpr->binary); \
6525 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6526 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6527 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6528 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6529 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6530 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6531 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6532 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6533 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6535 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6536 semantic_comparison, 1)
6537 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6538 semantic_comparison, 1)
6539 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6540 semantic_comparison, 1)
6541 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6542 semantic_comparison, 1)
6544 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6545 semantic_binexpr_arithmetic, 1)
6546 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6547 semantic_binexpr_arithmetic, 1)
6548 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6549 semantic_binexpr_arithmetic, 1)
6550 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6551 semantic_logical_op, 1)
6552 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6553 semantic_logical_op, 1)
6554 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6555 semantic_shift_op, 1)
6556 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6557 semantic_shift_op, 1)
6558 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6559 semantic_arithmetic_addsubb_assign, 0)
6560 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6561 semantic_arithmetic_addsubb_assign, 0)
6562 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6563 semantic_arithmetic_assign, 0)
6564 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6565 semantic_arithmetic_assign, 0)
6566 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6567 semantic_arithmetic_assign, 0)
6568 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6569 semantic_arithmetic_assign, 0)
6570 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6571 semantic_arithmetic_assign, 0)
6572 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6573 semantic_arithmetic_assign, 0)
6574 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6575 semantic_arithmetic_assign, 0)
6576 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6577 semantic_arithmetic_assign, 0)
6579 static expression_t *parse_sub_expression(unsigned precedence)
6581 if(token.type < 0) {
6582 return expected_expression_error();
6585 expression_parser_function_t *parser
6586 = &expression_parsers[token.type];
6587 source_position_t source_position = token.source_position;
6590 if(parser->parser != NULL) {
6591 left = parser->parser(parser->precedence);
6593 left = parse_primary_expression();
6595 assert(left != NULL);
6596 left->base.source_position = source_position;
6599 if(token.type < 0) {
6600 return expected_expression_error();
6603 parser = &expression_parsers[token.type];
6604 if(parser->infix_parser == NULL)
6606 if(parser->infix_precedence < precedence)
6609 left = parser->infix_parser(parser->infix_precedence, left);
6611 assert(left != NULL);
6612 assert(left->kind != EXPR_UNKNOWN);
6613 left->base.source_position = source_position;
6620 * Parse an expression.
6622 static expression_t *parse_expression(void)
6624 return parse_sub_expression(1);
6628 * Register a parser for a prefix-like operator with given precedence.
6630 * @param parser the parser function
6631 * @param token_type the token type of the prefix token
6632 * @param precedence the precedence of the operator
6634 static void register_expression_parser(parse_expression_function parser,
6635 int token_type, unsigned precedence)
6637 expression_parser_function_t *entry = &expression_parsers[token_type];
6639 if(entry->parser != NULL) {
6640 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6641 panic("trying to register multiple expression parsers for a token");
6643 entry->parser = parser;
6644 entry->precedence = precedence;
6648 * Register a parser for an infix operator with given precedence.
6650 * @param parser the parser function
6651 * @param token_type the token type of the infix operator
6652 * @param precedence the precedence of the operator
6654 static void register_infix_parser(parse_expression_infix_function parser,
6655 int token_type, unsigned precedence)
6657 expression_parser_function_t *entry = &expression_parsers[token_type];
6659 if(entry->infix_parser != NULL) {
6660 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6661 panic("trying to register multiple infix expression parsers for a "
6664 entry->infix_parser = parser;
6665 entry->infix_precedence = precedence;
6669 * Initialize the expression parsers.
6671 static void init_expression_parsers(void)
6673 memset(&expression_parsers, 0, sizeof(expression_parsers));
6675 register_infix_parser(parse_array_expression, '[', 30);
6676 register_infix_parser(parse_call_expression, '(', 30);
6677 register_infix_parser(parse_select_expression, '.', 30);
6678 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6679 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6681 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6684 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6685 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6686 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6687 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6688 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6689 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6690 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6691 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6692 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6693 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6694 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6695 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6696 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6697 T_EXCLAMATIONMARKEQUAL, 13);
6698 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6699 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6700 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6701 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6702 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6703 register_infix_parser(parse_conditional_expression, '?', 7);
6704 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6705 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6706 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6707 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6708 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6709 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6710 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6711 T_LESSLESSEQUAL, 2);
6712 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6713 T_GREATERGREATEREQUAL, 2);
6714 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6716 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6718 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6721 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6723 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6724 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6725 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6726 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6727 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6728 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6729 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6731 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6733 register_expression_parser(parse_sizeof, T_sizeof, 25);
6734 register_expression_parser(parse_alignof, T___alignof__, 25);
6735 register_expression_parser(parse_extension, T___extension__, 25);
6736 register_expression_parser(parse_builtin_classify_type,
6737 T___builtin_classify_type, 25);
6741 * Parse a asm statement constraints specification.
6743 static asm_constraint_t *parse_asm_constraints(void)
6745 asm_constraint_t *result = NULL;
6746 asm_constraint_t *last = NULL;
6748 while(token.type == T_STRING_LITERAL || token.type == '[') {
6749 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6750 memset(constraint, 0, sizeof(constraint[0]));
6752 if(token.type == '[') {
6754 if(token.type != T_IDENTIFIER) {
6755 parse_error_expected("while parsing asm constraint",
6759 constraint->symbol = token.v.symbol;
6764 constraint->constraints = parse_string_literals();
6766 constraint->expression = parse_expression();
6770 last->next = constraint;
6772 result = constraint;
6776 if(token.type != ',')
6787 * Parse a asm statement clobber specification.
6789 static asm_clobber_t *parse_asm_clobbers(void)
6791 asm_clobber_t *result = NULL;
6792 asm_clobber_t *last = NULL;
6794 while(token.type == T_STRING_LITERAL) {
6795 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6796 clobber->clobber = parse_string_literals();
6799 last->next = clobber;
6805 if(token.type != ',')
6814 * Parse an asm statement.
6816 static statement_t *parse_asm_statement(void)
6820 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6821 statement->base.source_position = token.source_position;
6823 asm_statement_t *asm_statement = &statement->asms;
6825 if(token.type == T_volatile) {
6827 asm_statement->is_volatile = true;
6831 add_anchor_token(')');
6832 add_anchor_token(':');
6833 asm_statement->asm_text = parse_string_literals();
6835 if(token.type != ':') {
6836 rem_anchor_token(':');
6841 asm_statement->inputs = parse_asm_constraints();
6842 if(token.type != ':') {
6843 rem_anchor_token(':');
6848 asm_statement->outputs = parse_asm_constraints();
6849 if(token.type != ':') {
6850 rem_anchor_token(':');
6853 rem_anchor_token(':');
6856 asm_statement->clobbers = parse_asm_clobbers();
6859 rem_anchor_token(')');
6864 return create_invalid_statement();
6868 * Parse a case statement.
6870 static statement_t *parse_case_statement(void)
6874 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6876 statement->base.source_position = token.source_position;
6877 statement->case_label.expression = parse_expression();
6879 if (c_mode & _GNUC) {
6880 if (token.type == T_DOTDOTDOT) {
6882 statement->case_label.end_range = parse_expression();
6888 if (! is_constant_expression(statement->case_label.expression)) {
6889 errorf(statement->base.source_position,
6890 "case label does not reduce to an integer constant");
6892 /* TODO: check if the case label is already known */
6893 if (current_switch != NULL) {
6894 /* link all cases into the switch statement */
6895 if (current_switch->last_case == NULL) {
6896 current_switch->first_case =
6897 current_switch->last_case = &statement->case_label;
6899 current_switch->last_case->next = &statement->case_label;
6902 errorf(statement->base.source_position,
6903 "case label not within a switch statement");
6906 statement->case_label.statement = parse_statement();
6910 return create_invalid_statement();
6914 * Finds an existing default label of a switch statement.
6916 static case_label_statement_t *
6917 find_default_label(const switch_statement_t *statement)
6919 case_label_statement_t *label = statement->first_case;
6920 for ( ; label != NULL; label = label->next) {
6921 if (label->expression == NULL)
6928 * Parse a default statement.
6930 static statement_t *parse_default_statement(void)
6934 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6936 statement->base.source_position = token.source_position;
6939 if (current_switch != NULL) {
6940 const case_label_statement_t *def_label = find_default_label(current_switch);
6941 if (def_label != NULL) {
6942 errorf(HERE, "multiple default labels in one switch");
6943 errorf(def_label->base.source_position,
6944 "this is the first default label");
6946 /* link all cases into the switch statement */
6947 if (current_switch->last_case == NULL) {
6948 current_switch->first_case =
6949 current_switch->last_case = &statement->case_label;
6951 current_switch->last_case->next = &statement->case_label;
6955 errorf(statement->base.source_position,
6956 "'default' label not within a switch statement");
6958 statement->case_label.statement = parse_statement();
6962 return create_invalid_statement();
6966 * Return the declaration for a given label symbol or create a new one.
6968 static declaration_t *get_label(symbol_t *symbol)
6970 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6971 assert(current_function != NULL);
6972 /* if we found a label in the same function, then we already created the
6974 if(candidate != NULL
6975 && candidate->parent_scope == ¤t_function->scope) {
6979 /* otherwise we need to create a new one */
6980 declaration_t *const declaration = allocate_declaration_zero();
6981 declaration->namespc = NAMESPACE_LABEL;
6982 declaration->symbol = symbol;
6984 label_push(declaration);
6990 * Parse a label statement.
6992 static statement_t *parse_label_statement(void)
6994 assert(token.type == T_IDENTIFIER);
6995 symbol_t *symbol = token.v.symbol;
6998 declaration_t *label = get_label(symbol);
7000 /* if source position is already set then the label is defined twice,
7001 * otherwise it was just mentioned in a goto so far */
7002 if(label->source_position.input_name != NULL) {
7003 errorf(HERE, "duplicate label '%Y' (declared %P)",
7004 symbol, label->source_position);
7006 label->source_position = token.source_position;
7009 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7011 statement->base.source_position = token.source_position;
7012 statement->label.label = label;
7016 if(token.type == '}') {
7017 /* TODO only warn? */
7019 warningf(HERE, "label at end of compound statement");
7020 statement->label.statement = create_empty_statement();
7022 errorf(HERE, "label at end of compound statement");
7023 statement->label.statement = create_invalid_statement();
7027 if (token.type == ';') {
7028 /* eat an empty statement here, to avoid the warning about an empty
7029 * after a label. label:; is commonly used to have a label before
7031 statement->label.statement = create_empty_statement();
7034 statement->label.statement = parse_statement();
7038 /* remember the labels's in a list for later checking */
7039 if (label_last == NULL) {
7040 label_first = &statement->label;
7042 label_last->next = &statement->label;
7044 label_last = &statement->label;
7050 * Parse an if statement.
7052 static statement_t *parse_if(void)
7056 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7057 statement->base.source_position = token.source_position;
7060 add_anchor_token(')');
7061 statement->ifs.condition = parse_expression();
7062 rem_anchor_token(')');
7065 add_anchor_token(T_else);
7066 statement->ifs.true_statement = parse_statement();
7067 rem_anchor_token(T_else);
7069 if(token.type == T_else) {
7071 statement->ifs.false_statement = parse_statement();
7076 return create_invalid_statement();
7080 * Parse a switch statement.
7082 static statement_t *parse_switch(void)
7086 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7087 statement->base.source_position = token.source_position;
7090 expression_t *const expr = parse_expression();
7091 type_t * type = skip_typeref(expr->base.type);
7092 if (is_type_integer(type)) {
7093 type = promote_integer(type);
7094 } else if (is_type_valid(type)) {
7095 errorf(expr->base.source_position,
7096 "switch quantity is not an integer, but '%T'", type);
7097 type = type_error_type;
7099 statement->switchs.expression = create_implicit_cast(expr, type);
7102 switch_statement_t *rem = current_switch;
7103 current_switch = &statement->switchs;
7104 statement->switchs.body = parse_statement();
7105 current_switch = rem;
7107 if (warning.switch_default
7108 && find_default_label(&statement->switchs) == NULL) {
7109 warningf(statement->base.source_position, "switch has no default case");
7114 return create_invalid_statement();
7117 static statement_t *parse_loop_body(statement_t *const loop)
7119 statement_t *const rem = current_loop;
7120 current_loop = loop;
7122 statement_t *const body = parse_statement();
7129 * Parse a while statement.
7131 static statement_t *parse_while(void)
7135 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7136 statement->base.source_position = token.source_position;
7139 add_anchor_token(')');
7140 statement->whiles.condition = parse_expression();
7141 rem_anchor_token(')');
7144 statement->whiles.body = parse_loop_body(statement);
7148 return create_invalid_statement();
7152 * Parse a do statement.
7154 static statement_t *parse_do(void)
7158 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7160 statement->base.source_position = token.source_position;
7162 add_anchor_token(T_while);
7163 statement->do_while.body = parse_loop_body(statement);
7164 rem_anchor_token(T_while);
7168 add_anchor_token(')');
7169 statement->do_while.condition = parse_expression();
7170 rem_anchor_token(')');
7176 return create_invalid_statement();
7180 * Parse a for statement.
7182 static statement_t *parse_for(void)
7186 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7187 statement->base.source_position = token.source_position;
7189 int top = environment_top();
7190 scope_t *last_scope = scope;
7191 set_scope(&statement->fors.scope);
7194 add_anchor_token(')');
7196 if(token.type != ';') {
7197 if(is_declaration_specifier(&token, false)) {
7198 parse_declaration(record_declaration);
7200 expression_t *const init = parse_expression();
7201 statement->fors.initialisation = init;
7202 if (warning.unused_value && !expression_has_effect(init)) {
7203 warningf(init->base.source_position,
7204 "initialisation of 'for'-statement has no effect");
7212 if(token.type != ';') {
7213 statement->fors.condition = parse_expression();
7216 if(token.type != ')') {
7217 expression_t *const step = parse_expression();
7218 statement->fors.step = step;
7219 if (warning.unused_value && !expression_has_effect(step)) {
7220 warningf(step->base.source_position,
7221 "step of 'for'-statement has no effect");
7224 rem_anchor_token(')');
7226 statement->fors.body = parse_loop_body(statement);
7228 assert(scope == &statement->fors.scope);
7229 set_scope(last_scope);
7230 environment_pop_to(top);
7235 rem_anchor_token(')');
7236 assert(scope == &statement->fors.scope);
7237 set_scope(last_scope);
7238 environment_pop_to(top);
7240 return create_invalid_statement();
7244 * Parse a goto statement.
7246 static statement_t *parse_goto(void)
7250 if(token.type != T_IDENTIFIER) {
7251 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
7255 symbol_t *symbol = token.v.symbol;
7258 declaration_t *label = get_label(symbol);
7260 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7261 statement->base.source_position = token.source_position;
7263 statement->gotos.label = label;
7265 /* remember the goto's in a list for later checking */
7266 if (goto_last == NULL) {
7267 goto_first = &statement->gotos;
7269 goto_last->next = &statement->gotos;
7271 goto_last = &statement->gotos;
7277 return create_invalid_statement();
7281 * Parse a continue statement.
7283 static statement_t *parse_continue(void)
7285 statement_t *statement;
7286 if (current_loop == NULL) {
7287 errorf(HERE, "continue statement not within loop");
7290 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7292 statement->base.source_position = token.source_position;
7300 return create_invalid_statement();
7304 * Parse a break statement.
7306 static statement_t *parse_break(void)
7308 statement_t *statement;
7309 if (current_switch == NULL && current_loop == NULL) {
7310 errorf(HERE, "break statement not within loop or switch");
7313 statement = allocate_statement_zero(STATEMENT_BREAK);
7315 statement->base.source_position = token.source_position;
7323 return create_invalid_statement();
7327 * Check if a given declaration represents a local variable.
7329 static bool is_local_var_declaration(const declaration_t *declaration) {
7330 switch ((storage_class_tag_t) declaration->storage_class) {
7331 case STORAGE_CLASS_AUTO:
7332 case STORAGE_CLASS_REGISTER: {
7333 const type_t *type = skip_typeref(declaration->type);
7334 if(is_type_function(type)) {
7346 * Check if a given declaration represents a variable.
7348 static bool is_var_declaration(const declaration_t *declaration) {
7349 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7352 const type_t *type = skip_typeref(declaration->type);
7353 return !is_type_function(type);
7357 * Check if a given expression represents a local variable.
7359 static bool is_local_variable(const expression_t *expression)
7361 if (expression->base.kind != EXPR_REFERENCE) {
7364 const declaration_t *declaration = expression->reference.declaration;
7365 return is_local_var_declaration(declaration);
7369 * Check if a given expression represents a local variable and
7370 * return its declaration then, else return NULL.
7372 declaration_t *expr_is_variable(const expression_t *expression)
7374 if (expression->base.kind != EXPR_REFERENCE) {
7377 declaration_t *declaration = expression->reference.declaration;
7378 if (is_var_declaration(declaration))
7384 * Parse a return statement.
7386 static statement_t *parse_return(void)
7388 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7389 statement->base.source_position = token.source_position;
7393 expression_t *return_value = NULL;
7394 if(token.type != ';') {
7395 return_value = parse_expression();
7399 const type_t *const func_type = current_function->type;
7400 assert(is_type_function(func_type));
7401 type_t *const return_type = skip_typeref(func_type->function.return_type);
7403 if(return_value != NULL) {
7404 type_t *return_value_type = skip_typeref(return_value->base.type);
7406 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7407 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7408 warningf(statement->base.source_position,
7409 "'return' with a value, in function returning void");
7410 return_value = NULL;
7412 type_t *const res_type = semantic_assign(return_type,
7413 return_value, "'return'", statement->base.source_position);
7414 if (res_type == NULL) {
7415 errorf(statement->base.source_position,
7416 "cannot return something of type '%T' in function returning '%T'",
7417 return_value->base.type, return_type);
7419 return_value = create_implicit_cast(return_value, res_type);
7422 /* check for returning address of a local var */
7423 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7424 const expression_t *expression = return_value->unary.value;
7425 if (is_local_variable(expression)) {
7426 warningf(statement->base.source_position,
7427 "function returns address of local variable");
7431 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7432 warningf(statement->base.source_position,
7433 "'return' without value, in function returning non-void");
7436 statement->returns.value = return_value;
7440 return create_invalid_statement();
7444 * Parse a declaration statement.
7446 static statement_t *parse_declaration_statement(void)
7448 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7450 statement->base.source_position = token.source_position;
7452 declaration_t *before = last_declaration;
7453 parse_declaration(record_declaration);
7455 if(before == NULL) {
7456 statement->declaration.declarations_begin = scope->declarations;
7458 statement->declaration.declarations_begin = before->next;
7460 statement->declaration.declarations_end = last_declaration;
7466 * Parse an expression statement, ie. expr ';'.
7468 static statement_t *parse_expression_statement(void)
7470 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7472 statement->base.source_position = token.source_position;
7473 expression_t *const expr = parse_expression();
7474 statement->expression.expression = expr;
7476 if (warning.unused_value && !expression_has_effect(expr)) {
7477 warningf(expr->base.source_position, "statement has no effect");
7484 return create_invalid_statement();
7488 * Parse a statement.
7490 static statement_t *parse_statement(void)
7492 statement_t *statement = NULL;
7494 /* declaration or statement */
7495 add_anchor_token(';');
7496 switch(token.type) {
7498 statement = parse_asm_statement();
7502 statement = parse_case_statement();
7506 statement = parse_default_statement();
7510 statement = parse_compound_statement();
7514 statement = parse_if();
7518 statement = parse_switch();
7522 statement = parse_while();
7526 statement = parse_do();
7530 statement = parse_for();
7534 statement = parse_goto();
7538 statement = parse_continue();
7542 statement = parse_break();
7546 statement = parse_return();
7550 if(warning.empty_statement) {
7551 warningf(HERE, "statement is empty");
7553 statement = create_empty_statement();
7558 if(look_ahead(1)->type == ':') {
7559 statement = parse_label_statement();
7563 if(is_typedef_symbol(token.v.symbol)) {
7564 statement = parse_declaration_statement();
7568 statement = parse_expression_statement();
7571 case T___extension__:
7572 /* this can be a prefix to a declaration or an expression statement */
7573 /* we simply eat it now and parse the rest with tail recursion */
7576 } while(token.type == T___extension__);
7577 statement = parse_statement();
7581 statement = parse_declaration_statement();
7585 statement = parse_expression_statement();
7588 rem_anchor_token(';');
7590 assert(statement != NULL
7591 && statement->base.source_position.input_name != NULL);
7597 * Parse a compound statement.
7599 static statement_t *parse_compound_statement(void)
7601 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7603 statement->base.source_position = token.source_position;
7606 add_anchor_token('}');
7608 int top = environment_top();
7609 scope_t *last_scope = scope;
7610 set_scope(&statement->compound.scope);
7612 statement_t *last_statement = NULL;
7614 while(token.type != '}' && token.type != T_EOF) {
7615 statement_t *sub_statement = parse_statement();
7616 if(is_invalid_statement(sub_statement)) {
7617 /* an error occurred. if we are at an anchor, return */
7623 if(last_statement != NULL) {
7624 last_statement->base.next = sub_statement;
7626 statement->compound.statements = sub_statement;
7629 while(sub_statement->base.next != NULL)
7630 sub_statement = sub_statement->base.next;
7632 last_statement = sub_statement;
7635 if(token.type == '}') {
7638 errorf(statement->base.source_position,
7639 "end of file while looking for closing '}'");
7643 rem_anchor_token('}');
7644 assert(scope == &statement->compound.scope);
7645 set_scope(last_scope);
7646 environment_pop_to(top);
7652 * Initialize builtin types.
7654 static void initialize_builtin_types(void)
7656 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7657 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7658 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7659 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7660 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7661 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7662 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7663 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7665 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7666 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7667 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7668 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7672 * Check for unused global static functions and variables
7674 static void check_unused_globals(void)
7676 if (!warning.unused_function && !warning.unused_variable)
7679 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7680 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7683 type_t *const type = decl->type;
7685 if (is_type_function(skip_typeref(type))) {
7686 if (!warning.unused_function || decl->is_inline)
7689 s = (decl->init.statement != NULL ? "defined" : "declared");
7691 if (!warning.unused_variable)
7697 warningf(decl->source_position, "'%#T' %s but not used",
7698 type, decl->symbol, s);
7703 * Parse a translation unit.
7705 static translation_unit_t *parse_translation_unit(void)
7707 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7709 assert(global_scope == NULL);
7710 global_scope = &unit->scope;
7712 assert(scope == NULL);
7713 set_scope(&unit->scope);
7715 initialize_builtin_types();
7717 while(token.type != T_EOF) {
7718 if (token.type == ';') {
7719 /* TODO error in strict mode */
7720 warningf(HERE, "stray ';' outside of function");
7723 parse_external_declaration();
7727 assert(scope == &unit->scope);
7729 last_declaration = NULL;
7731 assert(global_scope == &unit->scope);
7732 check_unused_globals();
7733 global_scope = NULL;
7741 * @return the translation unit or NULL if errors occurred.
7743 translation_unit_t *parse(void)
7745 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7746 label_stack = NEW_ARR_F(stack_entry_t, 0);
7747 diagnostic_count = 0;
7751 type_set_output(stderr);
7752 ast_set_output(stderr);
7754 lookahead_bufpos = 0;
7755 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7758 translation_unit_t *unit = parse_translation_unit();
7760 DEL_ARR_F(environment_stack);
7761 DEL_ARR_F(label_stack);
7767 * Initialize the parser.
7769 void init_parser(void)
7772 /* add predefined symbols for extended-decl-modifier */
7773 sym_align = symbol_table_insert("align");
7774 sym_allocate = symbol_table_insert("allocate");
7775 sym_dllimport = symbol_table_insert("dllimport");
7776 sym_dllexport = symbol_table_insert("dllexport");
7777 sym_naked = symbol_table_insert("naked");
7778 sym_noinline = symbol_table_insert("noinline");
7779 sym_noreturn = symbol_table_insert("noreturn");
7780 sym_nothrow = symbol_table_insert("nothrow");
7781 sym_novtable = symbol_table_insert("novtable");
7782 sym_property = symbol_table_insert("property");
7783 sym_get = symbol_table_insert("get");
7784 sym_put = symbol_table_insert("put");
7785 sym_selectany = symbol_table_insert("selectany");
7786 sym_thread = symbol_table_insert("thread");
7787 sym_uuid = symbol_table_insert("uuid");
7788 sym_deprecated = symbol_table_insert("deprecated");
7789 sym_restrict = symbol_table_insert("restrict");
7790 sym_noalias = symbol_table_insert("noalias");
7792 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7794 init_expression_parsers();
7795 obstack_init(&temp_obst);
7797 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7798 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7802 * Terminate the parser.
7804 void exit_parser(void)
7806 obstack_free(&temp_obst, NULL);